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
Issues Allow control statements (if, else, endif, etc.) to be closed so they can be inlined In line with the discussion here: The pertinent parts quoted: However, if the case is that Jinja2's (% if <expr> %}, because it has a closing %} allows it to be inlined like {% if <expr> %} <html> {% else %} <html> {% endif %}, then I'd want to think a bit bigger here. I'd want to go into match_control_line() as we did and just find some way to make the newline optional: % if <expr>:\n <html>\n % else:\n <html>\n % endif\n we could perhaps just co-opt the { } verbosity: {% if <expr>:} <html> {% else:} <html> {% endif} or just rip them off totally: {% if <expr> %} <html> {% else %} <html> {% endif %} either of the above would require a rewritten (either in-place or additional version of) match_control_line(), as we'd be doing the same kind of matching which we do in match_expression(), which is that we need to make use of parse_until_text() so that we properly skip over anything that might be Python code. I'd want the two formats to be completely interchangeable: % if expr: <html> {% else %} <html> % endif {% if <expr> %} <html> % elif <expr>: <html> % else: <html> {% endif %} just some ideas but I'd need someone to be motivated to help patch out lexer.py and add new tests as well. I've frequently used Python's native {{{1 if 1 else 0}}} syntax, but it doesn't always seem ideal. This is the only thing I can think of that other template languages can do that I wish Mako had. Thank you for making Mako. thanks for logging this. You're welcome.
https://bitbucket.org/zzzeek/mako/issue/218/allow-control-statements-if-else-endif-etc
CC-MAIN-2015-14
refinedweb
273
59.67
iPhone Backup Extractor provides ready access to WhatsApp data for consumers, and the Reincubate Cloud Data API provides programmatic access to this data. Working with WhatsApp data WhatsApp data is stored in iTunes and iCloud backups, and an archive of WhatsApp message data can also be directly stored on the iCloud by the app itself. WhatsApp's namespace is net.whatsapp.WhatsApp. They use Shared, TodayExtension, ShareExtension namespaces, too. There are a number of helpful files in WhatsApp's data, but the most notable is ChatStorage.sqlite. This stores all messages sent and received. Recovery of deleted messages is possible for WhatsApp. As WhatsApp is CallKit-compliant on iOS, its call history is available in our general CallKit call history API module. The ricloud API makes WhatsApp data available in an easy use JSON format. It is accessible using the whatsapp_messages module name. Here's a sample of some of that data: { "whatsapp_messages": [ { "handle": "0123456789@s.whatsapp.net", "attachments": [], "text": "Hi, it's me.", "date": "2016-06-17 15:29:53.573508", "from_me": true, "contact": null, "conversation_id": 3, "group_handles": null, "id": 6 }, { "handle": "0123456789@s.whatsapp.net", "attachments": [], "text": "Hey there!", "date": "2016-07-15 11:43:25.035354", "from_me": true, "contact": { "phone": "+0123456789", "contact_id": 13002 }, "conversation_id": 4, "group_handles": null, "id": 13 }, { "handle": "0123456789@s.whatsapp.net", "attachments": [], "text": null, "date": "2016-07-15 11:43:25.422725", "from_me": false, "contact": { "phone": "+0123456789", "contact_id": 13002 }, "conversation_id": 4, "group_handles": null, "id": 14 }, ] } About WhatsApp WhatsApp is a messaging app for mobile devices, with over 1 billion users worldwide, allowing photos and video sharing, and in-app calls. Businesses use the app for marketing, customer communication and internal communications purposes, especially in areas where mobile devices are used more frequently than emails, social media or blogs. In 2014, WhatsApp was bought by Facebook, and reached 1 billion active users in February 2016.
https://reincubate.com/app-data/whatsapp-data/
CC-MAIN-2019-30
refinedweb
310
58.08
I think the title says it all. I’m learning how to write better unit tests and I think that a great way to do it would be to look at some real, production sofware that has really good unit test written. Can you recommend some examples? The language doesn’t matter. Tag: Unit How to Automate Unit test for HMI application? I have the requirement like this: . Write python script, which run on the test Machine and interact with HMI Application. · Automatic test can trigger the command from HMI (Button click action) / take the screen short of widget / screen for the status indication and compare it with expected results (compare with expected value/ pixmap) . · Automatic test run every night and generate the test report of executed test cases. Please, suggest some good solutions as this is very urgent. Thanks, Aniprada Does it make sense to write one unit test and loop it through similar components? I have a situation where I have different forms, each with 4 or 5 steps (components), and I decided to write one unit test per step. After doing it, I noticed they were very similar and I could just loop through them, changing some values based on the loop index. All good and worked fine, until one of the forms failed and I couldn’t figure out which step was failing . I could provide another generic solution for it, but this failure made me wonder if it really makes sense to reuse code for tests like this. Well… as developers, we always want to reduce code duplicates, but I think for unit/snapshot tests, it’s a best practice to have every test explicit. The advantage I see by duplicating code in this situation is that it makes it more clear, easy to debug when a failure happens and also, once it’s test code, it doesn’t impact production code. What are your thoughts on it? Does it worth to have generic code to test several similar components, or is it better and safer to have it more explicit, even if you have to duplicate the code? I also read this article on twitter, a few days ago that opened my mind for this approach even more: WDYT? How exactly should unit tests be written without mocking extensively? As I understand, the point of unit tests is to test units of code in isolation. This means, that: - They should not break by any unrelated code change elsewhere in the codebase. - Only one unit test should break by a bug in the tested unit, as opposed to integration tests (which may break in heaps). All of this implies, that every outside dependency of a tested unit, should be mocked out. And I mean all the outside dependencies, not only the “outside layers” such as networking, filesystem, database, etc.. This leads to a logical conclusion, that virtually every unit test needs to mock. On the other hand, a quick Google search about mocking reveals tons of articles that claim that “mocking is a code smell” and should mostly (though not completely) be avoided. Now, to the question(s). - How should unit tests be written properly? - Where exactly does the line between them and integration tests lie? Update 1 Please consider the following pseudo code: class Person { constructor(calculator) {} calculate(a, b) { const sum = this.calculator.add(a, b); // do some other stuff with the `sum` } } Can a test that tests the Person.calculate method without mocking the Calculator dependency (given, that the Calculator is a lightweight class that does not access “the outside world”) be considered a unit test? Struggling with cyclical dependancies in unit tests I? Unit testing as non developer How possible is it for a non-dev, Qa person, to on board themselves to learn how to unit test production code? SI have an understanding of how code is written and understand basic logic but what do you consider the learning curve would be for me if I wanted to learn how to write unit tests for my team? Not overnight obviously, but over time? Is it even feasible? Is there a good reason not to use a unit test framework’s Assert methods to throw exceptions in actual app code? For instance, insteead of if (MyFancyObject is null) throw new InvalidOperationException(); I could simply say Assert.IsNotNull(MyFancyObject); But I hardly ever see this done – is there a good reason not to? getting error as “failed mount unit issue when restart the system I am getting issue while restart my Ubuntu 18.04 system. It suddenly crash and giving error as “failed mount unit issue” when I restart the system. PS sorry for less discription. Please find screenshot of error. Is there a unit of measurement that can express code execution speed in absolute terms? I’ve always seen code execution speed measured either in units of time (e.g. t milliseconds), or using asymptotic analysis (e.g. O(n log n)). These methods are relative to hardware performance though, they’re not absolute terms. For space performance, we have the same asymptotic analysis, but we can also measure that performance in bytes, which allows us to express (and predict) space performance in both relative and absolute terms. e.g. algorithm X’s space complexity is O(n) or n * 32 bytes of memory for implementation Y in language Z. For example we can look at this code: for i in n: pass And if we know this will be executed using a 64-bit build of CPython, we can say this for loop will take up 72 + n * 8 bytes for the integer array and 8 bytes for each reference (independent of context/overhead). My question is: Is there a unit of measurement we can use to express a piece of code’s execution speed (or CPU usage) in absolute terms, similar to bytes for memory? How to write DRY Unit Tests when order of method calls matters Suppose I’m writing a calculator engine with a class as follows… public class ArithmeticExpression { ArithmeticExpression Add(double operand) { /* ... */ } ArithmeticExpression Subtract(double operand) { /* ... */ } // ... other useful operations like division, multiplication, etc. double ProduceResult() { /* ... */ } } … and the goal is to defer evaluation of the expression until ProduceResullt() is called, so that correct order of all stacked operations is maintained. My question is: How should I tackle with unit testing this class without getting overwhelmed by the number of combinations of method calls? It is clear to me that the order of calls should be tested somehow, but writing tests like this: public void Multiply_CalledAfterAdd_TakesPrecedenceOverAdd() { // ... } public void Multiply_CalledAfterDivide_EvaluatesLeftToRight() { // ... } can get maddening and out of control quite quickly. And it’s not even about those 16 tests for the four basic arithmetic functions. Suppose in the future I decide to extend the calculator with a modulo operation – that’s 9 almost identical tests more to begin with. On the other hand – the whole puprose of the class is to keep the order of operations maintained, so it’s got to be verified somehow. Wrapping up – I know the example is trivial, but it’s a general problem that I struggle to find an answer to. Any help is appreciated, thanks.
https://proxieslive.com/tag/unit/
CC-MAIN-2019-43
refinedweb
1,203
62.58
I am transitioning to Ruby from Java and trying to understand Ruby scoping. It seems class variables behave the same as static variables in Java. Is this interpretation correct? If so, are Ruby global variables then equivalent to public static variables in Java? There's a lot of similarity between Ruby and Java by virtue of them being object-oriented, but their family tree is different. Ruby leans very heavily on Smalltalk while Java inherits from the C++ school of thinking. The difference here is that Ruby's concept of public/private/protected is a lot weaker, they're more suggestions than rules, and things like static methods or constants are more of a pattern than a construct in the language. Global variables are frowned on quite heavily, they can cause chaos if used liberally. The Ruby way is to namespace things: $ugly_global = 0 # Not recommended, could conflict with other code # Ownership of this variable isn't made clear. $ugly_global += 1 # Works, but again, it's without context. module UglyCounter # Defines a module/namespace to live in def self.current # Defines a clear interface to this value @counter ||= 0 # Initializes a local instance variable end def self.current=(v) # Allow modification of this value @counter = v.to_i # A chance to perform any casting/cleaning end end UglyCounter.current += 1 # Modifies the state of a variable, but # the context is made clear. Even a thin layer like this module gives you the ability to intercept read/write operations from this variable and alter the behaviour. Maybe you want to default to a particular value or convert values into a normalized form. With a bare global you have to repeat this code everywhere. Here you can consolidate it. Class variables are a whole different thing. They're also best avoided because sharing data between the class and instances of this class can be messy. They're two different contexts and that separation should be respected. class MessyClass @@shared = 0 def counter @@shared end def counter=(v) @@shared = v end end This is a pretty rough take on how to use a shared class-level instance variable. The problem here is each instance is directly modifying it, bypassing the class context, which means the class is helpless. This is fundamentally rude, the instance is over-extending its authority. A better approach is this: class CleanerClass def self.counter @counter ||= 0 end def self.counter=(v) @counter = v.to_i end # These are reduced to simple bridge methods, nothing more. Because # they simply forward calls there's no breach of authority. def counter self.class.counter end def counter=(v) self.class.counter = v end end In many languages a static class method becomes available in the scope of an instance automatically, but this is not the case in Ruby. You must write bridge/proxy/delegate methods, the terminology here varying depending on what you're used to.
https://codedump.io/share/E322wZwPiCWN/1/are-ruby-class-variables-similar-to-the-java-static-variables
CC-MAIN-2017-34
refinedweb
483
58.08
The Tcl Dev Kit Debugger provides a variety of features that help you to find and fix bugs in Tcl scripts quickly. These features include: This section lists the platforms and Tcl versions that the Tcl Dev Kit Debugger supports. It then describes how to start the Tcl Dev Kit Debugger and provides a tour of the Tcl Dev Kit Debugger main window. The Tcl Dev Kit Debugger can debug any Tcl/Tk script running in a Tcl version 7.6 and Tk version 4.2 or later interpreter. This includes any extensions to those interpreters that do not radically redefine any standard Tcl commands. Important: Renaming or radically redefining any standard Tcl commands may cause the Tcl Dev Kit Debugger to fail. An example of a radical redefinition of the proc command would be to redefine it to take four arguments instead of three. In particular, avoid altering the Tcl commands listed below: To run the Tcl Dev Kit Debugger on a Windows system, select Tcl Dev Kit Debugger from the Tcl Dev Kit program group on the Windows Start menu, or double-click the tcldebugger.exe file (the default location is C:\Tcl\bin). Alternatively, enter tcldebugger.exe at the command prompt. To enable Code Profiling and Coverage, select File|Project Settings and choose one of the options on the Coverage & Profiling tab. To run the Tcl Dev Kit Debugger on a Unix system, enter tcldebugger at the shell prompt. The main window is made up of the following components: The menus and toolbar in the main window are used run, step through, interrupt, kill, or restart your code. You can change the appearance of the Tcl Dev Kit Debugger by toggling the display of elements in the main window from the View menu: The function of each button is described in the following sections. When you hover the mouse over a toolbar button, a description of the functionality appears as a pop-up below the mouse pointer and on the left side of the status bar. The Stack Frames display shows the most recent stack levels and highlights the current location in your code when the application is stopped. If you select a stack level, the Tcl Dev Kit Debugger shows the code and variable values for that stack level in the Code display and the Variable display. When the application encounters a breakpoint, the last stack frame is automatically selected and highlighted in the Stack Frame display. The call stack includes an entry for each distinct scope or body of code. It displays stack frame information in this format: stack level, Tcl command, and relevant arguments. Stack level 0 indicates the global level. Stack level 1 indicates that a procedure is invoked from level 0; stack level 2 indicates that a procedure is invoked from stack level 1, and so on. Note: If your code is in an event loop when you click the Pause button, no code is shown in the Code display and the top level in the stack frame displays "event." The following example shows a sample stack frame: 0 global 0 source myScriptFile 1 proc myProc arg1 arg2 arg3 2 namespace eval myNamespace 3 proc myproc3 0 uplevel 1 proc myproc3 args In this example, the stack level is reset to 0 by the uplevel command; the uplevel command can be called explicitly in your source code or implicitly by a callback. As with any other procedure call, the namespace eval command creates a new level. You can navigate through the application by clicking on specific stack frames, which affects both the Variable and Code displays. When you double-click any part of a stack frame, the Code display scrolls to and highlights the current command in that stack frame. For example, if you want to see the code that caused a stack frame to be created, you can double-click the frame directly above the frame in question. In addition to highlighting the current command, if the last stack frame is selected, the Tcl Dev Kit Debugger indicates the current command with a yellow Run Arrow in the Code bar. The Tcl Dev Kit Debugger also indicates the current command with a green triangular History Arrow in the Code bar. When you click a stack frame, the Variable display shows the variables in that stack frame. For example, if you want to see global variables, you can double-click any Level 0 stack frame. If you click directly on an argument in a proc stack frame, the Variable window scrolls to and highlights the selected argument. The Variable display shows all of the existing variables in the selected stack frame. The value of each variable is updated whenever the application is stopped. The value for each array appears as an ellipsis (...). You can expand and contract the display of the array by clicking the ellipsis. When an array is expanded, each index is listed with its corresponding value. To set a variable breakpoint, click the breakpoint margin to the left of the variable display. The application will stop whenever the variable is modified. See Manipulating Breakpoints for more information. When a variable value exceeds the size of the display, double-click the variable to open the Data Display window, which will show the entire value. See Displaying Data for more information. Variable Value Formats In each of the windows where variable values are displayed (the Variable pane, the Data Display window and the Watch Variables window), you can configure the format in which the variable values are displayed. Right-click the variable in the Variable pane and select the desired format. The following formats are supported: If the chosen format is not appropriate for the specified variable (for example, selecting Integer: As Hex for a variable that contains a non-numeric string), the format transformation will not be performed. When specifying the format for variable values, note that the format specified in either the Variable pane or the Watch Variables window will be inherited by the Data Display window (depending on which source was used to call the Data Display window). If the message "No variable info for this stack" appears in the Variable display, it means that the stack level that is highlighted in the Stack display is hidden. Stack levels are hidden as a result of calls to Tcl commands like vwait and uplevel. When vwait is called, it creates a new stack, and all of the non-zero levels of the old stack are hidden until the vwait call returns. When uplevel is called with the absolute level for x, all of the levels of the old stack that are greater than x are hidden until the uplevel call returns. The Code display shows exactly one Tcl code source at a time. A code source is a file opened from the File menu, a file that has been sourced by the application, or a chunk of code dynamically created at runtime by commands such as eval. The Window menu lists all the open files, allowing you to select the file you want to view. You can also select a code source to view from the Breakpoint and Procedures windows. See Using Breakpoints and Finding Procedures. When the application is stopped, an arrow or triangle appears in the code bar indicating the current command with highlighted text. For example, in the Tcl Dev Kit Debugger main window, the portion of the code that is highlighted is code that is about to be executed and it is also indicated by the yellow run arrow in the code bar. Code is also highlighted if it is found using the Find command. See Going to a Specified Line for information on commands that you can use to move through and search for specific portions of code. If you see the message "No Source Code..." in the Code display, there are two possible reasons: The status bar is located at the bottom of the Tcl Dev Kit Debugger. The section on the left displays the information about the state of the debugger session. If you hover the mouse pointer over a toolbar button, this section of the status bar will display a usage tip for the button. Errors and warnings are indicated by the red and yellow icons in the middle of the status bar. The background color of these icons is configured in the debugger preferences. To the right of the errors and warnings icons, an asterisk ("*") will be displayed if the current code source is uninstrumented. See About Tcl Dev Kit Instrumentation for more information. The far right portion of the status bar displays the current file name and path and line number. The Result display shows the result and completion code of the most recently executed Tcl command. The Result display is not a scrolling window; the Tcl Dev Kit Debugger displays only as much of the result as can fit in the Result display. You can double-click on the result to display it in the Data Display window (see Displaying Data). Note: The performance of the Tcl Dev Kit Debugger can decrease if your application produces particularly long results (for example, reading a large file into a variable) and you have the Result display visible. If you want to increase performance in cases like this, toggle off the Result display by selecting View|Result. You can manage multiple projects with the Tcl Dev Kit Debugger. The Tcl Dev Kit Debugger saves project information in files with the .tpj extension. Projects store a variety of information about an application including: The file format for debugger projects changed after the first version of the Tcl Dev Kit. Version 1 .tpj files can still be opened by the debugger; changes to version 1 projects will still be stored in the version 1 format. However, information about variable value formatting cannot be stored in version 1 project files. New projects use the latest .tpj format. By default, when the Tcl Dev Kit Debugger starts, it automatically reloads the last project you had open. You can change this behavior as described in Startup and Exit Preferences. Note: You must have a project open to perform any debugging actions. To create a new project: The Tcl Dev Kit Debugger Project window will open.. Tip: If there are one or more interpreters you commonly use, you can change your default project settings to include them in the Interpreter drop-down list: The interpreters you specify are now available for all new projects you create afterwards. Once you create your new project, the Tcl Dev Kit Debugger displays the Tcl script file you specified in the Code display of the main window. The Tcl Dev Kit Debugger does not run the script until you tell it to do so, as described in Controlling your Application. There are two ways that you can open an existing project in the Tcl Dev Kit Debugger: If you already have a project open, the Tcl Dev Kit Debugger asks if you want to save that project. When you open an existing project, the Tcl Dev Kit Debugger restores all of the project settings and breakpoints in effect when you saved the project. The Tcl Dev Kit Debugger also displays the Tcl script file that you were viewing when you saved the project. To save a project, select File|Save Project. The first time you save a project, specify the file name and location for your project. The Tcl Dev Kit Debugger saves your project settings and any breakpoints and any watch variables you have set. To save a project with a different name, select File|Save Project As. To close a project, select File|Close Project. If you made changes, the Tcl Dev Kit Debugger asks if you want to save the project before closing it. Closing a project closes the project file and clears all the Tcl Dev Kit Debugger displays. To change the settings of the current project, select File|Project Settings. The Tcl Dev Kit Debugger displays the Project window. From this window you can change the script, interpreter, instrumentation, error, and coverage and profiling settings for a project as described in the sections below. Note: Changes that you apply to your project settings while your application is running don't take effect until the next time you restart your application. The Application tab lets you select basic application settings such as the Tcl script to debug and the Tcl interpreter to use. The contents of the Application tab depend on the Debugging Type option you select: If you select the Local Debugging option, the Application tab appears as shown below. You can change the following Local Debugging settings for a project:. If you select the Remote Debugging option, the Application tab appears as shown below. The only application setting you can change when debugging remotely is the TCP port that the Tcl Dev Kit Debugger uses to communicate with the remote application. This is the port that you need to pass to debugger_init when starting your debugging session from a remote application. See Debugging Remote, Embedded, and CGI Applications for information on remote debugging. Note: Changes that you apply to your project settings (by clicking either the OK or Apply button) while your application is running don't take effect until the next time you restart your application. The Instrumentation tab lets you select files and classes of procedures that the Tcl Dev Kit Debugger should and should not instrument. Instrumenting a file gives the Tcl Dev Kit Debugger control over its execution, and allows you to set breakpoints, single-step through the file, and perform other debugging tasks. If a file is not instrumented, you can't perform debugging tasks while your application is executing the file (or procedures defined in that file). For more information about instrumentation, see About Tcl Dev Kit Instrumentation. Some cases of when you would want to control which files are instrumented and which files are not include: The top half of the Project Instrumentation dialog determines the files that the Tcl Dev Kit Debugger instruments. (By default, all files are instrumented.) The first list box identifies a set of files to instrument, and the second list box identifies a subset of exceptions that are not instrumented. File name patterns follow the "string match" pattern conventions. (See the Tcl "string manual page" in the ActiveTcl User Guide for more information on pattern syntax.) Whenever your application sources a script file, the Tcl Dev Kit Debugger compares the file name against the patterns you specify in this dialog to determine whether to instrument it. For example, setting the pattern "app*.tcl" in the first list box and "*GUI.tcl" in the second list box causes the Tcl Dev Kit Debugger to instrument files such as appMain.tcl and appStats.tcl, but not instrument a file named appGUI.tcl. The patterns will match file names in both absolute and relative paths. To add a pattern to a list box, type the pattern in the String Match Pattern field, and then click the Add button next to the appropriate list box. To remove a pattern from the list, click the file or pattern to highlight it, then click the Remove button. Note: If you delete all patterns in the first list box and then apply the setting (by clicking either the OK or Apply button), the Tcl Dev Kit Debugger automatically adds the pattern "*" to the first list box. If the Tcl Dev Kit Debugger didn't do this, then you could accidentally cause the Tcl Dev Kit Debugger not to instrument any files, in which case you couldn't control your application with the debugger. The lower half of the Project Instrumentation dialog provides finer control of the instrumentation of procedures and control structures in a script file: Note: Changes that you apply to your project settings (by clicking either the OK or Apply button) while your application is running don't take effect until the next time you restart your application. Use the Startup & Exit tab to specify how the Tcl Dev Kit Debugger handles subprocesses. The Errors tab lets you specify how the Tcl Dev Kit Debugger handles errors in your Tcl script: Note: For more information on how the Tcl Dev Kit Debugger handles errors, see Error Handling. Note: Changes that you apply to your project settings (by clicking either the OK or Apply button) while your application is running don't take effect until the next time you restart your application. The Coverage & Profiling tab lets you choose to run the Tcl Dev Kit Debugger with coverage or profiling or neither. By default, new debugger projects run with neither coverage nor profiling. To change the setting, select File|Project Settings, and click the Coverage & Profiling tab. The setting specified here will determine what type of results are displayed in the Code Coverage and Profiling dialog box (Edit|Code Coverage). Select one of the following options: For more information see Code Profiling and Coverage. You can change any of the default project settings so that new projects you create have those settings. Changing the default project settings doesn't affect any existing projects you might have. For example, if you commonly use a set of packages that you don't want the Tcl Dev Kit Debugger to instrument, you could set those files in the default project settings. Then, any new project you create would pick up those instrumentation settings by default. To set the default project settings: Opening a file in the Tcl Dev Kit Debugger gives you the opportunity to create or check existing line-based breakpoints in the file before the file is sourced in the application. Breakpoints cause the application to stop before a line of code is executed so that you can examine the state of the application that you are debugging. See Using Breakpoints. To open a file: The file that you opened appears in the Tcl Dev Kit Debugger. You can view it using the scroll bars and menus. Tip: You can open a file at any time, even when an application is already running. When you open a file, the Tcl Dev Kit Debugger reloads the file if the file has not been sourced by the running application or if no application is running. If the application is running and has sourced the file, modifications to that file cannot be seen in the Code display until that file is sourced again or the file is reopened after the application is terminated. This section describes how to use the basic features of the Tcl Dev Kit Debugger. Click the Run button to run your code with the Tcl Dev Kit Debugger. When the application stops, the Tcl Dev Kit Debugger indicates the line of code that it is processing with an arrow and highlights the portion of the line that it is about to execute. Once the application is running, it stops at these events: The Run to Cursor button lets you to create a temporary breakpoint that is automatically removed the next time the Tcl Dev Kit Debugger stops. When your application is stopped, you can move the cursor to the line of code where you want to stop, and press the Run To Cursor button. Note: If the application stops for any reason, such as encountering another breakpoint or reaching the line containing the cursor, the temporary breakpoint is removed. The operation of the Run to Cursor feature is similar to those of line-based breakpoints. If the cursor is not set, or if it is on a line that is either empty or contains only comments or curly braces, clicking the Run to Cursor button is equivalent to clicking the Run button. The application stops just before evaluating the first command on the line regardless of where you place the cursor on a line of code. The Tcl Dev Kit Debugger offers four ways of stepping through your scripts: Step In, Step Out, Step Over, and Step To Result. When your application is stopped, you can step from the current command, indicated by the yellow run arrow in the code bar. To use the stepping features, click the corresponding button on the toolbar when your application is stopped. See The Toolbar for a description of the buttons. Note: If the application stops for any reason, such as encountering an error or breakpoint, after any of the Step buttons is pressed, the step is considered to be completed. The Step In feature provides the finest granularity at which you can stop and inspect your application. Stepping in causes the application to stop just before executing the next instrumented command. Stepping in is useful for following the control flow of your application as it sources files, calls procedures, and evaluates command substitutions. For example, if your application is stopped on the command myProc [incr x 5] you can Step In and stop the application before it evaluates the subcommand incr x 5. You can Step In again to stop the application on the first line of code in the body of the myProc procedure. The following list describes the rules of behavior for the Step In function: Stepping out causes the application to stop before executing the next command after the current stack level or body of code returns. The Step Out feature is useful for backing out of code you are no longer interested in inspecting. For example: if you are stopped in the body of the myProc procedure in the following application: 1 source someFile.tcl 2 myProc [incr x 5] 3 myNextProc $x and you would like to progress to the myNextProc $x command, you can Step Out of the myProc procedure, and then Step In the myNextProc procedure. The following list describes the rules of behavior for the Step Out function: Stepping over causes the application to stop just before executing the next command after the current command in your application is fully executed. The Step Over feature is useful for following the application as it progresses through a body of code at the current stack level. For example, suppose you are stopped on line 1 in the following application: 1 source someFile.tcl 2 set x 1 3 myProc [incr x 5] 4 puts $x If you Step Over the source command, the application stops at set x 1. If you continue to click Step Over, myProc [incr x 5] becomes the new current command, followed by puts $x. The following list describes the rules of behavior for the Step Over function: Stepping to Result executes the current command and stops execution. After using Step to Result, the Tcl Dev Kit Debugger highlights the command just executed and displays the result and return code of that command in the Command Results display of the debugger main window. The Step to Result feature is useful for examining the results of nested commands. For example, suppose you click Step In at line 3 in the following application: 1 source someFile.tcl 2 set x 1 3 myProc [incr x 5] 4 puts $x If you click Step to Result, your application executes the subcommand and stops. You can then examine the result of the subcommand before continuing. By comparison, clicking Step In again at this point would execute the subcommand [incr x 5] and immediately Step In to myProc, and clicking Step Over would execute both the [incr x 5] subcommand and the call to myProc before stopping. Clicking the Pause button causes the Tcl Dev Kit Debugger to interrupt the application while it is running. You can interrupt the application at any time; when you interrupt, an implicit breakpoint is added to the next command to be executed in the script. The application stops as it would at any other breakpoint, and you can then interact with the application. Note: If your code is in an event loop when you click the Pause button, no code is shown in the Code display and the top level in the stack frame displays "event." Note: If your application is executing uninstrumented Code or is in a long-running command, the Tcl Dev Kit Debugger may not be able to stop the application immediately. Clicking the Stop button causes the Tcl Dev Kit Debugger to end the application's process. When you kill the application that you are debugging, information about its state is no longer available. You can then restart the application or launch another application. Note: You cannot terminate remote applications using the Stop button. You can terminate a remote application by interrupting the application and typing "exit" in the Eval Console. See Manipulating Data. Click the Restart button to terminate the current application and then restart the same application. This is equivalent to killing the application and immediately restarting it. When you restart an application, the Tcl Dev Kit Debugger automatically reloads the main script. This is useful if you have modified the script to fix a bug and want to start the application over to test the change. If you have modified files other than the main script and wish to set or change breakpoints in those files, you can open them by selecting File|Open File rather than viewing the stale files from the Window menu. To quit the Tcl Dev Kit Debugger, select File|Exit, or click the Close button in the Tcl Dev Kit main window. A breakpoint causes the application to stop so that you can examine its state. You can add breakpoints in an application at any time. Using breakpoints, you can obtain information, such as variables and their values, the current call stack, and valid procedure names. Tcl Dev Kit supports two types of breakpoints: "line-based" and "variable". Line-based breakpoints let you to specify a line of code where the application should stop. Line-based breakpoints cause the Tcl Dev Kit Debugger to stop before executing each command and subcommand on the specified line. Line-based breakpoints are persistent across runs of the application and debugger sessions. The Tcl Dev Kit Debugger does not stop at line-based breakpoints that are set in uninstrumented lines of code, blank lines, comment lines, and lines that contain only curly braces. However, variable breakpoints can be triggered if the variable is modified in uninstrumented code. See About Tcl Dev Kit Instrumentation for information. Variable breakpoints cause the application to stop when the variable is modified. Variable-based breakpoints are not stored in the application after you close it, or when the variable is removed, unset, or goes out of scope, for example: a local variable in a procedure goes out of scope when the procedure returns. Note: The Variable breakpoints track the unique location where the variable is stored in memory rather than the name of the variable. You can not set a variable breakpoint until the variable exists in the application. You can create breakpoints in the main Debugger window. To set a line-based breakpoint, click the code bar in the left margin in the Code display. The line-based breakpoint appears as a small stop sign, and causes the application to stop just before the line is executed. To create a Variable breakpoint, click the left margin in the Variable display adjacent to the variable. The breakpoint appears as a large "V" in the Variable display. The "V" also appears in the code bar of the Code display when the variable breakpoint is triggered causing the application to stop. The variable breakpoint triggers when the value of the variable changes. You can also create and disable breakpoints from the Breakpoints submenu (Debug|Breakpoints) or in the Breakpoints window. To delete a breakpoint, click the breakpoint in the Code or Variable display. To display the Breakpoints window, click the "B" in the toolbar or select View|Breakpoints. The Breakpoints window displays line-based and variable breakpoints, as shown in The Breakpoints Window. The line-based breakpoints in the Breakpoints window indicate the file and line number where the breakpoint has been set. To select a breakpoint, click the line to the right of the breakpoint in the Breakpoints window to highlight it. You can delete, disable, and enable breakpoints: The disabled breakpoint is shown as a hollow stop sign for a line-based breakpoint or hollow "V" for a variable-based breakpoint. Disabling and enabling breakpoints can be helpful when you want to keep all of your breakpoints but may not want to use all of them at the same time. Note: You can select multiple breakpoints to be disabled or enabled by clicking the breakpoints while pressing the Ctrl key. You can perform the following actions on a selected breakpoint: Clicking this button causes the Tcl Dev Kit Debugger to display the code containing the corresponding line in the Code display. You can click the Remove All button to remove all of the breakpoints. The information for a variable breakpoint in the Breakpoints window appears in the form of two sets. The first set contains the variable name followed by the absolute stack level at which the variable breakpoint was created. The second set contains information regarding the last time the variable breakpoint was triggered. If the second set is empty, the variable breakpoint has never been triggered. Otherwise, the second set contains the name and stack level of the variable that triggered the variable breakpoint. In most cases, the second set will not differ from the first set. However, when a variable is aliased by the global and upvar commands, any instance of that variable can trigger the variable breakpoint. The second set is helpful when you have an aliasing bug in your code. The following is an example of an aliased variable a whose variable breakpoint gets triggered by a variable named x: 1 proc foo {} { 2 upvar #0 a x 3 set x 52 4 } 5 set a 50 6 puts "global var a is set" 7 set a 51 8 foo If you stop this application on line 6, you can create a variable breakpoint for the global variable a. If you open the Breakpoints window, you will see the following: {a: 0} {: } If you continue to run the application, the variable breakpoint is triggered on line 7. The following appears in the Breakpoints window: {a: 0} {a: 0} If you continue to run the application again, the variable breakpoint is triggered once more on line 3. The following appears in the Breakpoints window: {a: 0} {x: 1} The Tcl Dev Kit Debugger can debug subprocesses (and threads) that are "spawned" from a debugging session. These subprocesses are launched by modifying your script and and setting "spawnpoints" at appropriate positions within the script. Spawnpoints are set similarly to breakpoints. If spawnpoints have been set, green arrows are displayed in the margin at the left of the Tcl Dev Kit Debugger's main window. Set and remove spawnpoints by right-clicking in the left margin in the Tcl Dev Kit Debugger's main window. Alternatively, select Debug|Breakpoints, and choose one of the spawnpoints options: thread::create, spawnand execcommands. When you run the debugger with spawnpoints set, a new Code display tab is launched for each spawned subprocess/thread. Once a subprocess has been spawned, you can debug it as you would a regular session in the Tcl Dev Kit Debugger. To close the connection between the debugger and a subprocess, select Debug|Stop or click the Close active debugger connection button on the toolbar. Note: It is not possible to have multiple projects open in the debugger, with separate debugging sessions for each. The new sessions can only be subprocesses of the main session. Furthermore, data is not shared between sessions. Each session has its own breakpoints and file information. Only breakpoints and spawnpoints in the main session are saved and restored. If you want to spawn a new session, you must modify the main script in a debugger project by adding the following proc command, along with a spawn command for each subprocess that you want to debug. Spawnpoints (indicated by green arrows) are then set at these lines. So, in the example shown below, the spawnpoints are set on the lines containing the spawn commands for subprocess1.tcl and subprocess2.tcl. proc spawn {cmd args} { return [eval [linsert $args 0 \ exec [info nameofexecutable] $cmd]] } puts "Running the profiled multipliers in parallel" spawn [file join [file dirname [info script]] subprocess1.tcl] spawn [file join [file dirname [info script]] subprocess2.tcl] puts "Launch complete" Note that the command name, signature, and functionality have to match the definition of spawn.pdx, which is wrapped in tcldebugger.exe. Use the Virtual Filesystem Explorer to view the contents of this file. The virtual path is /tcldebugger.exe/debugger/. Although the spawn procedure described above is the simplest and most effective way to debug a subprocess, there is an alternative method that makes it possible to invoke subprocesses in remote locations. This method requires that you create a main script containing the exec command and modify the script that you want to debug. Set a spawnpoint in the Tcl Dev Kit Debugger's main window at the line containing the exec command. Create a main script similar to the following: puts "launch" exec C:\Tcl\bin\<TclInterpreter$gt; C:\<DirectoryName>script.tcl puts "OK" modify the script to be debugged similarly to the following: package_require tcldebugger_attach if {[info exists ::env(DEBUG_INFO)]} { foreach {host port cdata} $::env(DEBUG_INFO) break debugger_init $host $port $cdata } debugger_eval { <your code> } The Tcl Dev Kit Debugger provides utilities that help you navigate to specific portions of the code that you are debugging, including the Procedures window, the Goto command, the Find command, and the Window menu. The Tcl Dev Kit Debugger highlights the specified line. Tip - You can also use the Goto What drop-down list to move up or move down the lines in your code from the insertion cursor. Select Move Up Lines or Move Down Lines and type the number of lines that you want to move. The Tcl Dev Kit Debugger highlights the code that matches the string that you typed. If the string is not found, the Code Display does not change. You can find subsequent matching strings by clicking the Find Next button or pressing the <F3> key. You can use the Procedures window to view the list of procedures that have been defined in your application. To open the Procedures window, click the "P" button on the toolbar in the main Tcl Dev Kit Debugger window, or select View|Procedures. In order for procedures associated with the current application to be displayed in the Procedures window, the Tcl Dev Kit Debugger must be active. To view procedures, set a breakpoint, and then run the debugger. To narrow down the list, you can type a pattern in the text box and click Search. The default pattern is an asterisk ("*"), which lists all of the defined procedures in the application. Pattern strings can be one or more characters and follow the search conventions that are used with the Tcl glob command. The matches for the string are shown in the display area of the Procedures window. This is useful for finding specific procedures if you have large applications with many procedures. For example, if you type "tcl*" in the text box of the Procedures window, tclLog, tclMacPkgSearch, and all other procedures beginning with "tcl" are displayed in the display area of the Procedures window. You can display both instrumented and uninstrumented procedures by selecting Show Uninstrumented Procs. Uninstrumented procedures are indicated by asterisks in the display area of the Procedures window. For more information, see About Tcl Dev Kit Instrumentation. When you select a procedure from the list, you can perform any of the following actions on it: The Tcl Dev Kit Debugger detects errors according to the criteria described in Error Handling. Using the Syntax errors dialog box, you can view a summary list of errors and warnings that have been encountered up to the current debugging point. Note that errors and warnings will not necessarily prevent users from running the script. Errors such as false positives incorrectly detected by the Tcl Dev Kit Checker will have no effect at run-time, whereas runtime or instrumentation errors may prevent the application from running. To open the Syntax errors dialog, select View|Syntax errors, or press Alt + F5. Lines containing syntax errors and warnings are colored in the code display window according to the configuration of the debugger preferences. To display the code causing a syntax error in the code display, select the error and click Show Code. Select the Window menu to display all of the files that are open in the Tcl Dev Kit Debugger. The Tcl Dev Kit Debugger provides several windows in which you can display and monitor specific aspects of the application that you are debugging. These include the Watch Variable window, and the Data Display window. For information on the Breakpoints window, see Viewing Breakpoints in the Breakpoints Window. To open the Watch Variables window, click the "W" button on the toolbar. Alternatively, select View|Watch Variables. The Watch Variables window displays variable names and values at the stack level that is selected in the Stack Frames display. The values in the Watch Variables window are updated each time the application stops, and also each time you select a new stack level in the Stack Frames display in the main window. If a variable name or value is not defined at the selected stack level, then "<No Value>" appears instead of a value. To add a variable name to the Watch Variables window: The variable name and the current value of the variable are displayed in the variable list. To remove a specific variable, click the line, then click the Remove button. To remove all variables, click the Remove All button. To invoke the Data Display window, which displays the full unabbreviated value of a variable, click the desired variable then click the Data Display button. Alternatively, double-click the desired variable. The Watch Variables window is useful for observing variables in different stack levels that have the same name. For example, suppose the following script is stopped just before executing line 10: 1 proc bar {x} { 2 puts $x 3 } 4 5 proc foo {y} { 6 baz [expr {$y + 3}] 7 } 8 9 set x 2 10 foo $x The stack display is shown below: 0 global 0 source sample.tcl 1 proc foo y 2 proc bar x If you are watching the variable named x, you will see the value change as you select different stack levels. At level 2, x has the value 5. At level 1, x is not defined, so "<No Value>" is displayed. At level 0, x has the value 2. Variable Value Formats In each of the windows where variable values are displayed (the Variable pane, the Data Display window and the Watch Variables window), you can configure the format in which the variable values are displayed. The following formats are supported: If the chosen format is not appropriate for the specified variable (for example, selecting Integer: As Hex for a variable that contains a non-numeric string), the format transformation will not be performed. When you add a variable to the Watch Variables window, select the desired display format from the drop-down list, then press Add. If "No Transformation" is selected, the variable value format will not be transformed. Once a variable has been added to the list, you cannot change the display format. However, you can add the same variable more than once, specifying a different format each time. If you specify the same variable and variable format twice, the combination will only be displayed once. When you add an array variable to the Watch Variables window, you cannot specify the variable value format for individual elements. (The format will be inherited from the setting in the Variable pane.) To transform individual elements, add the array variable with the specific element, rather than the entire array variable. For example, if you specify the array "foo", elements in the array will be displayed in the same format as in the Variable pane. However, if you specify "foo(bar)", you may specify the variable value format for the "bar" element in the "foo" array. The Data Display is used to see the full unabbreviated value of a variable, which can be helpful if you are looking at long strings. To open the Data Display window, double-click a variable in the Variable display in the main window, or double-click a variable in the Watch Variable window. Alternatively, select View|Data Display. By default, the variable that was highlighted when the Data Display window was invoked will be displayed. To display a different variable, double-click the desired variable in the Variable pane or the Watch Variables window. Alternatively, type the variable name in the Data Display window and click Display. The variable is linked to the stack level that is highlighted in the Stack display at the time the variable is entered in the Data Display window. Once the variable is entered, changing the stack level in the Stack display will not affect the value of the variable. The value that is displayed for the variable is updated each time the application stops. If "<No Value>" appears, it means that either the variable was unset or the stack level attached to the variable has returned. Like variable breakpoints, a variable in the Data Display is associated with a location in memory. Once "<No Value>" appears, the previous memory location is no longer reserved for that particular variable, so "<No Value>" for the variable will reappear. Variable Value Formats In each of the windows where variable values are displayed (the Variable pane, the Data Display window and the Watch Variables window), you can configure the format in which the variable values are displayed. Select the desired format from the Display drop-down list. The following formats are supported: If the chosen format is not appropriate for the specified variable (for example, selecting Integer: As Hex for a variable that contains a non-numeric string), the format transformation will not be performed. The variable value format is inherited from either the Variable pane or the Watch Variables window, depending on where the Data Display window was invoked. To specify a different format, select the desired format from the Display drop-down list. View As Menu Use the drop-down View As menu to select the format for the variables. The Tcl Dev Kit Debugger attempts to match the display to the variable type. For example, if the variable is scalar, it will display with line wraps, and if it is an array, it will display as an array. You can view the variable with the following formats: Note: Ordered lists can be displayed as arrays. To open the Eval console, click the "E" button on the toolbar, or select View|Eval Console. The Eval console is used to pass commands to an application or to call procedures. Any time that the application is paused (either at a breakpoint or as a result of a debugger command like "Step Over" or "Step Out") you may enter commands in the Eval console to be evaluated by the application. Use the Stack Level drop-down list to select the stack in which you want to evaluate commands. (The deepest stack level is selected by default when the Eval Console windows is invoked.) You may also change the current stack level by using the keyboard shortcuts Ctrl + Plus (to move to the next higher stack level) and Ctrl + Minus (to move to the next lower stack level). The stack levels correspond to the numerical levels displayed in the Stack Frames window. The Eval Console maintains a command history. To invoke a command previously entered in the Eval Console, use the Up Arrow key (or Ctrl + p) to scroll through previous commands. Use the Down Arrow key (or Ctrl + n) to scroll through commands subsequent to the current command. The Tcl Dev Kit Debugger detects all errors in the application including runtime and parsing errors. A parsing error is an error that is caused by code that is not syntactically valid. An example of a parsing error is a script that is missing a close brace. The Tcl Dev Kit Debugger detects parsing errors during instrumentation, whenever a file is sourced or a procedure is created dynamically by the application. When a parsing error occurs, the Tcl Dev Kit Debugger cannot understand the script's control flow following the error, and cannot continue instrumenting the code. The Tcl Dev Kit Debugger displays a dialog box in which you choose to either quit the application or continue the application with the partially instrumented script. If you choose to continue debugging the partially instrumented script, the same error appears as a runtime error if the code is executed. See About Tcl Dev Kit Instrumentation for details on the implications of continuing despite the parsing error. An example of a runtime error is an attempt to read a non-existent variable. The Tcl Dev Kit Debugger detects all runtime errors, including both those caught and those not caught by a Tcl script. How the Tcl Dev Kit Debugger handles runtime errors depends on the Error settings that you specify for your project. See Changing Project Error Settings for more information on specifying your project Error settings. If you have set: When the Tcl Dev Kit Debugger detects a runtime error in accordance with the rules above, it stops execution of your application and displays a dialog box such as the one shown in the Tcl Dev Kit Debugger Tcl Error Dialog. You have the choice of either delivering the error or suppressing the error: While your application is stopped, you can examine your Tcl script, view and change variable values, set breakpoints, and use all the other features of the Tcl Dev Kit Debugger. If you single-step or run your application without first selecting whether to deliver or suppress the error, the Tcl Dev Kit Debugger delivers the error if your application catches it and suppresses it otherwise. Use the Syntax errors dialog to view a list of all the errors contained in the current program. Also, lines containing syntax errors and warnings are colored in the code display window according to the configuration of the debugger preferences. If you hover the mouse pointer over a line containing a syntax error or warning, the text of the error will be displayed in the Status Bar in the bottom left corner. The Eval Console displays output written to STDOUT or STDERR. When a program calls for input via a [gets] or [read stdin] statement, the Eval Console will display an (STDIN) % prompt where data for STDIN can be entered. (Each subsequent [gets] or [read stdin] statement will generate a new prompt, and will require new input.) The code line which called for input will be indicated in the code display window. The Eval Console window is opened automatically when STDOUT or STDERR is generated, or when STDIN input is required. The Tcl Dev Kit Debugger includes a tool for analyzing code coverage. Coverage and Profiling settings are specified on the Coverage & Profiling tab in the Project dialog box (File|Project Settings). For more about Coverage and Profiling options, see Changing Project Coverage and Profiling Settings. Code Coverage and Profiling has three components: Coverage information is collected as the debugger runs. The code displayed in the debugger is updated as each line is processed. If you have configured Coverage and Profiling to "Highlight Uncovered Code...", each line that has not been processed will highlighted in green (the default color). If you have configured Coverage and Profiling to "Highlight Covered Code...", each line that has been processed will be displayed in a shade of orange (the default color); lines that have been processed a number of times will be highlighted with a darker color. The more times a line has been processed, the darker the color. Select View|Code Coverage, or click the "Code Coverage" button on the toolbar, to open the Code Coverage and Profiling dialog. If you have set breakpoints in the file, coverage or profiling coloration will be updated in the code display pane as the debugger stops at each breakpoint. The pane that displays the source code will be colored to indicate either "covered" (code lines that have been processed) or "uncovered" (code lines that have not been processed) based on the selection in the Code Coverage and Profiling dialog. The coverage function stores the coverage and profiling analysis from the last time the debugger was run in the current session. Unless you manually clear the coverage information (using the Clear All Coverage button in the Code Coverage and Profiling dialog), you will be asked if you wish to save the coverage information from the last debugger run. Highlight Uncovered Code for Selected File Each line of code in the Code Display that has not been processed will be displayed with a green background. Highlight Covered Code for Selected File Each line of code in the Code Display that has been processed will be displayed in orange. Lines that have been processed multiple times will be highlighted with a darker shade. The darker the shade, the more times the line has been processed. Show Code When a file is selected on the Files tab, or a call selected on the Calls tab, click the Show Code button to shift the code display in the debugger to the desired file or call. Clear Selected Coverage When multiple files are displayed on the Files tab, you can clear the coverage display for one or more files, rather than clearing the display for all files. Select the file for which you wish to clear coverage, then click Clear Selected Coverage. Coverage will be cleared regardless of whether covered or uncovered code has been selected for display. Clear All Coverage To clear all coverage information, click Clear All Coverage. Coverage will be cleared regardless of whether covered or uncovered code has been selected for display. Save Data To export coverage information for the project, click Save Data. This will create a file in CSV (comma separated values) format in the specified directory. The file contains the following columns: For more information about Code Coverage and Profiling, see the Coverage Analysis Tutorial and the Hotspot Analysis Tutorial. You can specify preferences to customize the Tcl Dev Kit Debugger. To modify Preferences, select Edit|Preferences. Click the tabs to select your preferences for Appearance, Windows, Instrumentation, and Startup and Exit, and Browser preferences. You can choose the following Appearance preferences: Tip: The Tcl Dev Kit Debugger attempts to optimize your font and size preferences. If you type a font that is unavailable, the Tcl Dev Kit Debugger finds the most similar font on your computer and substitutes it. ActiveState recommends that you only use fixed-width fonts. Note: Small font sizes can cause misalignment of the symbols in the Code Bar and their corresponding lines of code. If you experience problems, increase the font size. After changing the Appearance tab settings, click the OK button to save your choices and close the Preferences window, the Cancel button to cancel your choices and close the Preferences window, or the Apply button to apply your choices and keep the Preferences window open. You can modify the following Windows preferences: After changing the Windows tab settings, click the OK button to save your choices and close the Preferences window, the Cancel button to cancel your choices and close the Preferences window, or the Apply button to apply your choices and keep the Preferences window open. The Startup preference controls the Tcl Dev Kit Debugger's behavior when you start the debugger: The Exit preferences control the Tcl Dev Kit Debugger's behavior when you quit the debugger: After changing the Startup & Exit tab settings, click the OK button to save your choices and close the Preferences window, the Cancel button to cancel your choices and close the Preferences window, or the Apply button to apply your choices and keep the Preferences window open. The Tcl Dev Kit Debugger uses a Web browser to display the ActiveState Web site when you click on the ActiveState URL in the About Tcl Dev Kit Debugger window. You can select one of the following choices for your Web browser with Tcl Dev Kit: After changing the Browser tab settings, click the OK button to save your choices and close the Preferences window, the Cancel button to cancel your choices and close the Preferences window, or the Apply button to apply your choices and keep the Preferences window open. When you begin running an application, the Tcl Dev Kit Debugger transparently processes the specified Tcl/Tk script. It modifies the code to enable communication between the Tcl Dev Kit Debugger and the script. This process is known as instrumentation. The Tcl Dev Kit Debugger launches the application with the instrumented script in place of the original script. The instrumentation was designed to be as unobtrusive as possible. However, you can expect some slowdown in applications as a result of the instrumentation. You can specify which procedures to instrument in the Procedures window; see Finding Procedures. You can also specify files and classes of procedures to leave uninstrumented; see Changing Project Instrumentation Settings. In addition to the files and procedures that you tell the Tcl Dev Kit Debugger not to instrument, there are also some instances of dynamically created code that the Tcl Dev Kit Debugger cannot instrument. These include "if" statements with computed bodies and callbacks from Tcl commands. When the application is executing uninstrumented code, it cannot communicate with the Tcl Dev Kit Debugger. If you want to interrupt or to add a breakpoint to the script while uninstrumented code is executing, the application cannot respond until it reaches the next instrumented statement. The Tcl Dev Kit Debugger indicates that a procedure or file is uninstrumented by listing the procedure or file name preceded by an asterisk ("*") in the Procedures window, Windows menu, and the Code display status bar. In some cases, the Tcl Dev Kit Debugger can't directly launch your application. Some examples where this is often true include CGI applications, embedded applications, and applications that must run on a system other than your debugging system. For applications such as these, the Tcl Dev Kit Debugger supports remote debugging. In remote debugging sessions, your application starts as it normally would and then establishes a special connection to the Tcl Dev Kit Debugger. You can then use the Tcl Dev Kit Debugger to perform all debugging tasks as you would in a local debugging session. To debug a remote application, you must perform the following steps: The following sections describe how to perform these tasks. For your application to establish and maintain communication with the Tcl Dev Kit Debugger, you must modify your application to use the tcldebugger_attach package, which is contained in the lib subdirectory of your Tcl Dev Kit installation. Use the following package command: package require tcldebugger_attach Your script must call the debugger_init procedure and, optionally, the debugger_eval and debugger_break procedures. You can modify your script in one of two ways: create a new "wrapper" script that sources your existing script, or modify your existing script. The following procedures are available for remote debugging: For more information about these commands see the Tcl Dev Kit Command-Line Reference. If you decide to create a new script, that script should load the tcldebugger_attach package, and then source the file that was originally the main script of your application. This new script becomes the main script of your application. # Assume $myOriginalMainScript contains the path of your # original script. source $myOriginalMainScript If you decide to modify your existing script, you must change it to load the "tcldebugger_attach" package and call the debugger_init procedure. Once debugger_init is called, other files sourced by the script will automatically be instrumented. If you want the Tcl Dev Kit Debugger to instrument code in the file that calls debugger_init, the code that you wish to instrument must be encapsulated in a call to the debugger_eval procedure. See About Tcl Dev Kit Instrumentation for more details on instrumentation. debugger_eval { # ... your code goes here ... } Before you begin debugging a remote application, you must create a remote debugging project in the Tcl Dev Kit Debugger. This causes the Tcl Dev Kit Debugger to listen on a specified port for your application to establish a connection. To create a remote debugging project: After you have modified your application for remote debugging and created a remote debugging project in the Tcl Dev Kit Debugger, you can launch your remote application for debugging. Simply run your application as you would normally. Your application stops just before it evaluates the first command in the debugger_eval script, or the first time it sources a file, whichever comes first. The Tcl Dev Kit Debugger displays your script in its main window, and you can begin debugging as you would a local application. You can view the connection status while debugging by selecting View|Connection Status. The status displays in The Connection Status window. The Connection Status Window displays the following information: The Tcl Dev Kit Debugger works properly with most custom Tcl interpreters. However, to properly instrument and execute your application, the Tcl Dev Kit Debugger must be able to pass debugging information to your Tcl script as command-line arguments. Therefore,. First, you must create a special Tcl wrapper script. The listing below shows a sample implementation of such a script for Unix systems. To use it, you must either change the line setting the cmdPrefix variable, replacing "tclsh" with whatever command you need to run your Tcl interpreter, or you must set your TCLDEBUGGER_TCLSH environment variable to contain that command. #!/bin/sh #\ exec tclsh $0 ${1+"$@"} if {$argc < 1} { puts stderr "wrong # args: location of appLaunch.tcl is required" } if {[info exists env(TCLDEBUGGER_TCLSH)]} { set cmdPrefix "$env(TCLDEBUGGER_TCLSH)" } else { set cmdPrefix "tclsh" } set customScriptName "/tmp/launchScript.[pid]" set appLaunchPath [lindex $argv 0] set f [open $customScriptName w] puts $f " file delete -force $customScriptName set argv0 [list $appLaunchPath] set argv [list [lrange $argv 1 end]] set argc \[llength \$argv\] source \$argv0 " close $f catch { eval exec $cmdPrefix [list $customScriptName 2>@stderr >@stdout <@stdin] } Then, to debug your application select the wrapper script as your interpreter (that is, type the path and name of the wrapper script in the Interpreter field of the Project Application Settings Tab). Specify the script and any script arguments for your application in the Project Application Settings Tab as normal. For an example of wrapping a Tcl script on the Windows platform, see DOS BAT Magic on The Tcl'ers Wiki.
http://docs.activestate.com/tdk/5.0/Debugger.html
CC-MAIN-2014-35
refinedweb
9,849
59.33
Introduction YAML stands for YAML Ain't Markup Language, it is a data-serialization language most commonly used for specifying project configuration details. The main motivation behind YAML is that it is designed to be in a format which is humanly friendly. With a glance we can get an understanding of the properties and their respective values, and also the relationship between properties if it exists. As the YAML files are now being frequently used, almost in every other project we come across a scenario where we have to manage data in YAML files through our code. There are a lot of open-source libraries available for handling YAML files in Java. To achieve this, we can use either of the two popular libraries: Jackson or SnakeYAML. In this article, we'll be focusing on How to Read and Write YAML Files in Java with SnakeYAML. SnakeYAML SnakeYAML is a YAML-parsing library with a high-level API for serialization and deserialization of YAML documents. The entry point for SnakeYAML is the Yaml class, similar to how the ObjectMapper class is the entry point in Jackson. load() method, or in batch via the loadAll() method. The methods accept an InputStream, which is a common format to encounter files in, as well as String objects containing valid YAML data. On the other hand, we can dump() Java objects into YAML documents with ease - where the keys/fields and values are mapped into a document. Naturally, SnakeYAML works well with Java Maps, given the <key>:<value> structure, however, you can work with custom Java objects as well. If you're using Maven, install SnakeYAML by adding the following dependency: <dependency> <groupId>org.yaml</groupId> <artifactId>snakeyaml</artifactId> <version>${org.snakeyaml.version}</version> </dependency> And if you're using Gradle, installing SnakeYAML is as simple as including the following in your Gradle file: compile group: 'org.yaml', name: 'snakeyaml', version: '{version}' You can check out the latest version of the library on Maven Central Repository. Reading YAML with SnakeYAML SnakeYAML allows you to read a YAML file into a simple Map object or parse the file and convert it into a custom Java object. Depending on your requirements you can decide in which format you want to read your YAML files. Let's take a look at both approaches. Read YAML File as Map in Java Let's start by reading a simple YAML file as a set of key-value pairs. The file we will be reading will have the following data: id: 20 name: Bruce year: 2020 address: Gotham City department: Computer Science Let's assume that we have this YAML in our Java project's resources folder. Let's load the file in as an InputStream first. Then, we'll construct the Yaml instance, which is the entry point to using the library. The Yaml instance introduces us to methods, such as load() which allow us to read and parse any InputStream, Reader or String with valid YAML data: InputStream inputStream = new FileInputStream(new File("student.yml")); Yaml yaml = new Yaml(); Map<String, Object> data = yaml.load(inputStream); System.out.println(data); The method returns a Java Map in which the name of the properties are used as keys against their respective values. Note that the values in the Map are of type Object, because in a YAML file - we can have our data as string values, numbers or even collections. All of these can be fit into an Object so it encompasses any value we might put in. If we print our data object in which we have loaded the YAML file we will get the following result: {id=20, name=Bruce, year=2020, address=Gotham City, department=Computer Science} As you can see that the properties from YAML file are simple mapped as key-value pairs in a java Map object. Lets update our YAML file to to contain collection data as well. The update YAML file look like this: id: 20 name: Bruce year: 2020 address: Gotham City department: Computer Science courses: - name: Algorithms credits: 6 - name: Data Structures credits: 5 - name: Design Patterns credits: 3 Now our YAML file contains a collection courses which has multiple data values. To read the updated YAML file there is no need to update our Java code. Our previous code will be able to successfully load the YAML file into our Map object. After reading the file the result be: { id=20, name=Bruce, year=2020, address=Gotham City, department=Computer Science, courses=[{name=Algorithms, credits=6}, {name=Data Structures, credits=5}, {name=Design Patterns, credits=3}] } The courses element in the YAML file is read as an ArrayList where each value in the list is a Map object itself. Read YAML Object as Custom Java Object Now that we have successfully consumed the YAML file in our Java code as simple key-value pairs, lets load the same file as a custom Java object, which is a much more common use-case. We will use the following Java classes to load data into from our YAML files: public class Person { private long id; private String name; private String address; // Getters and setters } public class Student extends Person { private int year; private String department; private List<Course> courses; // Getters and setters } public class Course { private String name; private double credits; // Getters and setters } We will load the data into a Student object, where the courses element from the YAML file will be converted into a List of type Course. We will use the same YAML file which we have used in the previous example and load it in as an InputStream: InputStream inputStream = new FileInputStream(new File("student_with_courses.yml")); Yaml yaml = new Yaml(new Constructor(Student.class)); Student data = yaml.load(inputStream); System.out.println(data); Now when we are creating our Yaml class object, we are specifying the data type we want to cast the data into. The new Constructor(Student.class) tells SnakeYAML to read the data from YAML file map it to our Student object. The mapping is straightforward and the names of your object attributes will have to match the names of the YAML attributes ( courses -> courses). This results in: Student[Person[id=20, name='Bruce', address='Gotham City'], year=2020, department='Computer Science', courses=[Course[name='Algorithms', credits=6.0], Course[name='Data Structure', credits=5.0], Course[name='Design patters', credits=3.0]]] As you can see SnakeYAML has successfully created the Student object while keeping the Student class inheritance (Parent class Person) and association with the Course class intact. Writing YAML with SnakeYAML Now that we have successfully read YAML files in our Java code, lets start writing data into YAML files using our Java project. Similar to reading YAML documents, we can write simple Java Map and a custom Java object into a YAML file. Write Map Into YAML Lets first write a simple Map object to a YAML file: Map<String, Object> dataMap = new HashMap<>(); dataMap.put("id", 19); dataMap.put("name", "John"); dataMap.put("address", "Star City"); dataMap.put("department", "Medical"); Now, let's create a new PrintWriter object, with the output directory in mind, and dump() the dataMap using that writer. Note: The dump() method accepts any Writer: PrintWriter writer = new PrintWriter(new File("./src/main/resources/student_output.yml")); Yaml yaml = new Yaml(); yaml.dump(dataMap, writer); This results in a file that contains: {address: Star City, name: John, id: 19, department: Medical} Note: is that the output YAML file does not have the values in the same sequence in which we added them in our Java Map object, since we've used a HashMap which doesn't preserve the order of entry. You can fix this issue by using a LinkedHashMap instead. Write Custom Java Object into YAML Now lets try and save our Student class in YAML format in the output file. For this we will use following code to setup the Student object: Student student = new Student(); student.setId(21); student.setName("Tim"); student.setAddress("Night City"); student.setYear(2077); student.setDepartment("Cyberware"); Course courseOne = new Course(); courseOne.setName("Intelligence"); courseOne.setCredits(5); Course courseTwo = new Course(); courseTwo.setName("Crafting"); courseTwo.setCredits(2); List<Course> courseList = new ArrayList<>(); courseList.add(courseOne); courseList.add(courseTwo); student.setCourses(courseList); Now, let's use our Yaml instance with a Writer implementation to dump() the data into a file: PrintWriter writer = new PrintWriter(new File("./src/main/resources/student_output_bean.yml")); Yaml yaml = new Yaml(); yaml.dump(student, writer); This results in: !!model.Student address: Night City courses: - {credits: 5.0, name: Intelligence} - {credits: 2.0, name: Crafting} department: Cyberware id: 21 name: Tim year: 2077 If you take a closer look at the YAML output files generated by our code, you will see that in the first example, all the data was dumped in a single line whereas in the second example the Course object values are written in a single line each under the courses element. Although both the generated output files have valid YAML syntax, if you want to create a YAML file in the more commonly used format where each value is written on a single line and there are not parentheses, you can tweak the DumperOptions object, and pass it into the Yaml constructor: DumperOptions options = new DumperOptions(); options.setIndent(2); options.setPrettyFlow(true); options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); Yaml yaml = new Yaml(options); Here, we have specified the indentation and YAML document flow using the DumperOptions object. Now when we use the dump function on the Yaml instance we will get differently formatted output: !!model.Student address: Night City courses: - credits: 5.0 name: Intelligence - credits: 2.0 name: Crafting department: Cyberware id: 21 name: Tim year: 2077 Conclusion As YAML files are becoming more frequent in use, especially for specifying project properties and build and deployment meta-data, it's increasingly useful to be able to handle them using code. Through SnakeYAML, we can easily manage YAML files in our Java project, and minimal amount of code is used to either load YAML files into our project or write data into YAML files. SnakeYAML also provides formatting options so you can tweak and customize to your needs. The source code for the sample code can be found on GitHub.
https://stackabuse.com/reading-and-writing-yaml-files-in-java-with-snakeyaml/
CC-MAIN-2021-17
refinedweb
1,715
51.78
I need to write a program that will read magnetic cards and display the card code on the screen in binary format (1's and 0's). The signal from the card reader is connected to the parallel port and can be read in from address 0x379. This is program that I have written but I'm not sure if it works or not. If it does not work I will not have time to fix it so it must work the first time. If something is wrong with the program can someone please tell me. #include <stdio.h> #include <conio.h> void main() { char cls,rcp,prevCls=0,prevRead=0; int in; do { in = inp(0x379); cls = (in & 0x80); rcp = (in & 0x20); if (!rcp && cls && prevRead) printf("%d",(in >> 4) & 1); else if (!cls && prevCls) printf("\n\n"); prevRead = rcp; prevCls = cls; } while (!kbhit()); return 0; }
http://cboard.cprogramming.com/c-programming/18684-magnetic-card-reader-prog.html
CC-MAIN-2014-52
refinedweb
147
83.46
Delayed Deltas for Thinking Sphinx (with Resque) This code is HEAVILY borrowed from ts-delayed-delta. Installation This gem depends on the following gems: thinking-sphinx, resque, and resque-lock-timeout. gem install ts-resque-delta Add ts-resque-delta to your Gemfile file, with the rest of your gem dependencies: gem 'ts-resque-delta', '1.1.1' If you're using Rails 3, the rake tasks will automatically be loaded by Rails. If you're using Rails 2, add the following line to your Rakefile: require 'thinking_sphinx/deltas/resque_delta/tasks' Add the delta property to each define_index block: define_index do # ... set_property :delta => ThinkingSphinx::Deltas::ResqueDelta end If you've never used delta indexes before, you'll want to add the boolean column named :delta to each model's table (note, you must set the :default value to true): def self.up add_column :foos, :delta, :boolean, :default => true, :null => false end Also, I highly recommend adding a MySQL index to the table of any model using delta indexes. The Sphinx indexer uses WHERE table.delta = 1 whenever the delta indexer runs and ... = 0 whenever the normal indexer runs. Having the MySQL index on the delta column will generally be a win: def self.up # ... add_index :foos, :delta end Usage Once you've got it all set up, all you need to do is make sure that the Resque worker is running. You can do this by specifying the :ts_delta queue when running Resque: QUEUE=ts_delta,other_queues rake resque:work Additionally, ts-resque-delta will wrap thinking-sphinx's thinking_sphinx:index and thinking_sphinx:reindex tasks with thinking_sphinx:lock_deltas and thinking_sphinx:unlock_deltas. This will prevent the delta indexer from running at the same time as the main indexer. Finally, ts-resque-delta also provides a rake task called thinking_sphinx:smart_index (or ts:si for short). This task, instead of locking all the delta indexes at once while the main indexer runs, will lock each delta index independently and sequentially. Thay way, your delta indexer can run while the main indexer is processing large core indexes. Contributors (for ts-delayed-delta) - Aaron Gibralter - Ryan Schlesinger (Locking/ smart_index) Original Contributors (for ts-delayed-delta) - Pat Allan - Ryan Schlesinger (Allowing installs as a plugin) - Maximilian Schulz (Ensuring compatibility with Bundler) - Edgars Beigarts (Adding intelligent description for tasks) - Alexander Simonov (Explicit table definition) Copyright (c) 2011 Aaron Gibralter, and released under an MIT Licence.
http://www.rubydoc.info/gems/ryansch-ts-resque-delta/frames
CC-MAIN-2017-09
refinedweb
398
51.58
From this point onwards, this tutorial assumes you have done the Django Tutorial and will show you how to integrate the tutorial’s poll app into the django CMS. Hereafter, if a poll app is mentioned, we are referring to the one you get after completing the Django Tutorial. Also, make sure the poll app is in your INSTALLED_APPS. We assume your main urls.py looks something like this: from django.conf.urls.defaults import * from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', (r'^admin/', include(admin.site.urls)), (r'^polls/', include('polls.urls')), (r'^', include('cms.urls')), ) A Plugin is a small bit of content you can place on your pages. For our polling app we would like to have a small poll plugin which shows a poll and let’s the user vote. In your poll application’s models.py add the following: from cms.models import CMSPlugin class PollPlugin(CMSPlugin): poll = models.ForeignKey('polls.Poll', related_name='plugins') def __unicode__(self): return self.poll.question Note django CMS plugins must inherit from cms.models.CMSPlugin (or a subclass thereof) and not models.Model. Run manage.py syncdb to create the database tables for this model or see Using South with django CMS to see how to do it using South Now create a file cms_plugins.py in the same folder your models.py is in. After having followed the Django Tutorial and adding this file your polls app folder should look like this: polls/ __init__.py cms_plugins.py models.py tests.py views.py The plugin class is responsible for providing the django CMS with the necessary information to render your Plugin. For our poll plugin, write following plugin class: from cms.plugin_base import CMSPluginBase from cms.plugin_pool import plugin_pool from polls.models import PollPlugin as PollPluginModel from django.utils.translation import ugettext as _ class PollPlugin(CMSPluginBase): model = PollPluginModel # Model where data about this plugin is saved name = _("Poll Plugin") # Name of the plugin render_template = "polls/plugin.html" # template to render the plugin with def render(self, context, instance, placeholder): context.update({'instance':instance}) return context plugin_pool.register_plugin(PollPlugin) # register the plugin Note All plugin classes must inherit from cms.plugin_base.CMSPluginBase and must register themselves with the cms.plugin_pool.plugin_pool. You probably noticed the render_template attribute in the above plugin class. In order for our plugin to work, that template must exist and is responsible for rendering the plugin. The template should look something like this: <h1>{{ instance.poll.question }}</h1> <form action="{% url polls.views.vote instance.poll.id %}" method="post"> {% csrf_token %} {% for choice in instance.poll.choice_set.all %} <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" /> <label for="choice{{ forloop.counter }}">{{ choice.choice }}</label><br /> {% endfor %} <input type="submit" value="Vote" /> </form> Note We don’t show the errors here, because when submitting the form you’re taken off this page to the actual voting page. Right now, external apps are statically hooked into the main urls.py. This is not the preferred approach in the django CMS. Ideally you attach your apps to CMS pages. For that purpose you write a CMSApp. That is just a small class telling the CMS how to include that app. CMS Apps live in a file called cms_app.py, so go ahead and create it to make your polls app look like this: polls/ __init__.py cms_app.py cms_plugins.py models.py tests.py views.py In this file, write: from cms.app_base import CMSApp from cms.apphook_pool import apphook_pool from django.utils.translation import ugettext_lazy as _ class PollsApp(CMSApp): name = _("Poll App") # give your app a name, this is required urls = ["polls.urls"] # link your app to url configuration(s) apphook_pool.register(PollsApp) # register your app Now remove the inclusion of the polls urls in your main urls.py so it looks like this: from django.conf.urls.defaults import * from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', (r'^admin/', include(admin.site.urls)), (r'^', include('cms.urls')), ) Now open your admin in your browser and edit a CMS Page. Open the ‘Advanced Settings’ tab and choose ‘Polls App’ for your ‘Application’. Unfortunately, for these changes to take effect, you will have to restart your server. So do that and afterwards if you navigate to that CMS Page, you will see your polls application.
http://docs.django-cms.org/en/2.3.2/extending_cms/extending_examples.html
CC-MAIN-2014-41
refinedweb
727
53.07
DreamSSH is a highly configurable pure-Python, Twisted-based SSH server.InstallYou can install from PyPI, which will give you the latest released (hopefully stable) version of the software: sudo pip install dreamsshIf you like living on the edge, you can install from the github master branch: sudo pip install, you can just get the code itself: git clone you used pip to install DreamSSH, then you will have the necessary libraries installed. If you will be running from source code, you'll need to do the following: sudo pip install pyasn1 sudo pip install PyCrypto sudo pip install twistedOnce the dependencies are installed, you'll need to generate the keys for use by the server: twistd dreamssh keygenRunningOnce you have DreamSSH installed, interacting with the server is as easy as the following: twistd dreamsshThat will run in daemonized mode. If you'd like to run it in the foreground and watch the log output to stdout, just do:twistd -n dreamsshTo log into the shell, use this command: twistd dreamssh shellIf you'd like to try out the alternate "toy" shell: twistd dreamssh --interpreter=echoWhen you're ready to shut it down: twistd dreamssh stopFor those who have a clone of the git repo, there are development convenience make targets: make keygen make daemon make run make shell make stopUsingWhen you log into the Python shell: twistd dreamssh shellYou are greeted with something that looks like this::>>:: Welcome to::________ ____________________ __:___ __ \_________________ _______ _____ ___/_ ___/__ / / /:__ / / /_ ___/ _ \ __ `/_ __ `__ \____ \_____ \__ /_/ /:_ /_/ /_ / / __/ /_/ /_ / / / / /___/ /____/ /_ __ /:/_____/ /_/ \___/\__,_/ /_/ /_/ /_//____/ /____/ /_/ /_/::: You have logged into a DreamSSH Server.: Type 'ls()' or 'dir()' to see the objects in the current namespace.:: Enjoy!::>>If you follow the hints given in the banner, you can get a listing of available objects with the following command::>> ls() __builtins__ - data app - dreamssh.shell.pythonshell.CommandAPI.app banner - dreamssh.shell.pythonshell.CommandAPI.banner clear - dreamssh.shell.pythonshell.CommandAPI.clear config - dreamssh.config exit - dreamssh.shell.pythonshell.CommandAPI.exit info - dreamssh.shell.pythonshell.CommandAPI.info ls - dreamssh.shell.pythonshell.CommandAPI.ls os - os pprint - pprint.pprint quit - dreamssh.shell.pythonshell.CommandAPI.quit services - data sys - sysIf you opt for the 'echo' shell: twistd dreamssh --interpreter=echoThen executing any command will looks something like this::>> execute any commandinput = execute any command, filename = < console >The echo shell is intended to provide insight or a starting point for developers who want to implement their own shell their users can ssh into.
http://linux.softpedia.com/get/System/Shells/DreamSSH-85654.shtml
CC-MAIN-2013-48
refinedweb
436
53.75
Myths about useEffect by Kent C. Dodds I've taught React to tens of thousands of developers. Before and after hooks were released. One thing I've observed is people tend to struggle with the useEffect hook and there are some common hang-ups for them that I'd like to address here. ❌ Lifecycles ❌ ✅ Synchronize Side Effects ✅ The biggest struggle I've observed is developers who have experience with React class components and lifecycle hooks like constructor, componentDidMount, componentDidUpdate, and componentWillUnmount. You can definitely map these to function components with hooks, but that's a big mistake. Allow me to illustrate. Here's an example of some fun UI: Here's a class component implementation of that DogInfo component: class DogInfo extends React.Component {controller = nullstate = {dog: null}// we'll ignore error/loading states for brevityfetchDog() {this.controller?.abort()this.controller = new AbortController()getDog(this.props.dogId, {signal: this.controller.signal}).then((dog) => {this.setState({dog})},(error) => {// handle the error},)}componentDidMount() {this.fetchDog()}componentDidUpdate(prevProps) {// handle the dogId changeif (prevProps.dogId !== this.props.dogId) {this.fetchDog()}}componentWillUnmount() {// cancel the request on unmountthis.controller?.abort()}render() {return <div>{/* render dog's info */}</div>}} That's a pretty standard class component for this type of interaction. It's using the constructor, componentDidMount, componentDidUpdate, and componentWillUnmount lifecycle hooks. If we naively mapped those lifecycles to hooks, here's how it might look: function DogInfo({dogId}) {const controllerRef = React.useRef(null)const [dog, setDog] = React.useState(null)function fetchDog() {controllerRef.current?.abort()controllerRef.current = new AbortController()getDog(dogId, {signal: controllerRef.current.signal}).then((d) => setDog(d),(error) => {// handle the error},)}// didMountReact.useEffect(() => {fetchDog()// eslint-disable-next-line react-hooks/exhaustive-deps}, [])// didUpdateconst previousDogId = usePrevious(dogId)useUpdate(() => {if (previousDogId !== dogId) {fetchDog()}})// willUnmountReact.useEffect(() => {return () => {controllerRef.current?.abort()}}, [])return <div>{/* render dog's info */}</div>}function usePrevious(value) {const ref = useRef()useEffect(() => {ref.current = value}, [value])return ref.current} There are still some holdouts on hooks. If this is what I thought hooks meant, then I would be a hooks holdout too. Here's the crux of the issue: useEffect is not a lifecycle hook. It's a mechanism for synchronizing side effects with the state of your app. So, in our example, all we care about is: "When the dogId changes, fetch the new dog's information." With that as our goal, useEffect becomes much simpler for this case:>} 🤯 Oh snap. That's way better right?! When the React team introduced hooks, their goal wasn't to simply add lifecycles to function components. Their goal was to fundamentally improve the mental model for application side-effects. And they did. Big time. So remember this gem by Ryan Florence: The question is not "when does this effect run" the question is "with which state does this effect synchronize with" useEffect(fn) // all state useEffect(fn, []) // no state useEffect(fn, [these, states]) I can ignore eslint-plugin-react-hooks/exhaustive-deps ❌ Well, technically you can. And sometimes there's a good reason to. But most of the time it's a bad idea and ignoring that rule will lead to bugs. I see this concern come up often when people say: "But I only want this to run on mount!" Again. That's thinking in lifecycles and is wrong. If your useEffect callback has dependencies, then you need to make sure that your effect callback is re-run anytime those dependencies change. Otherwise your side-effects will fall out of sync with the state of the app. Long story short, you'll have bugs. Don't ignore this rule. One giant useEffect ❌ Honestly, I don't see this one a whole lot, but I want to include it just in case. No shame if this is you. It happens. One of the things I love about useEffect over lifecycles is it allows me to really separate concerns. Here's a quick example: Here's some pseudocode for that demo: class ChatFeed extends React.Component {componentDidMount() {this.subscribeToFeed()this.setDocumentTitle()this.subscribeToOnlineStatus()this.subscribeToGeoLocation()}componentWillUnmount() {this.unsubscribeFromFeed()this.restoreDocumentTitle()this.unsubscribeFromOnlineStatus()this.unsubscribeFromGeoLocation()}componentDidUpdate(prevProps, prevState) {// ... compare props and re-subscribe etc.}render() {return <div>{/* chat app UI */}</div>}} See those four concerns? They're all mixed up. If we wanted to share that code with anything else, it would be a mess. I mean, render props were awesome, but hooks are way better. I've seen some people create a monster useEffect hook that does all the things: function ChatFeed() {React.useEffect(() => {// subscribe to feed// set document title// subscribe to online status// subscribe to geo locationreturn () => {// unsubscribe from feed// restore document title// unsubscribe from online status// unsubscribe from geo location}})return <div>{/* chat app UI */}</div>} But this makes that individual callback pretty complicated. I'd suggest a different approach. Don't forget that you can separate logical concerns into individual hooks: function ChatFeed() {React.useEffect(() => {// subscribe to feedreturn () => {// unsubscribe from feed}})React.useEffect(() => {// set document titlereturn () => {// restore document title}})React.useEffect(() => {// subscribe to online statusreturn () => {// unsubscribe from online status}})React.useEffect(() => {// subscribe to geo locationreturn () => {// unsubscribe from geo location}})return <div>{/* chat app UI */}</div>} And with this approach, it's much easier to extract this code into a custom hook for each individual concern if that's what you need or want to do: function ChatFeed() {// NOTE: this is pseudo-code,// you'd likely need to pass values and assign return valuesuseFeedSubscription()useDocumentTitle()useOnlineStatus()useGeoLocation()return <div>{/* chat app UI */}</div>} The self-encapsulation of hooks in general is a huge win. Let's make sure we take advantage of that. Needlessly externally defined functions ❌ I've seen this one a few times as well. Let me just give you a before/after: // before. Don't do this!function DogInfo({dogId}) {const [dog, setDog] = React.useState(null)const controllerRef = React.useRef(null)const fetchDog = React.useCallback((dogId) => {controllerRef.current?.abort()controllerRef.current = new AbortController()return getDog(dogId, {signal: controllerRef.signal}).then((d) => setDog(d),(error) => {// handle the error},)}, [])React.useEffect(() => {fetchDog(dogId)return () => controller.current?.abort()}, [dogId, fetchDog])return <div>{/* render dog's info */}</div>} We already saw how simple the above code can be in our earlier example, but let me show that to you again:>} The specific thing I'm trying to call out here is the idea of defining a function like fetchDog outside of the useEffect callback. Because it's external, you have to list it in the dependencies array to avoid stale closures. And because of that you also have to memoize it to avoid infinite loops. Oh, and then we had to create a ref for our abort controller. Phew, seems like a lot of work. If you must define a function for your effect to call, then do it inside the effect callback, not outside. Conclusion When Dan Abramov introduced hooks like useEffect, he compared React components to atoms and hooks to electrons. They're a pretty low-level primitive, and that's what makes them so powerful. The beauty of this primitive is that nicer abstractions can be built on top of these hooks which is frankly something we struggled with before hooks. Since the release of hooks, we've seen an explosion of innovation and progress of good ideas and libraries built on top of this primitive which ultimately helps us develop better apps. I love it. And I want to teach you all about these primitives as well as abstractions built on top of them in EpicReact.Dev 🚀 Join me.
https://epicreact.dev/myths-about-useeffect/
CC-MAIN-2021-10
refinedweb
1,245
50.53
Plone Customization Of Third Party Content Types Sometimes a third party product is almost exacly what you want to use. But sometimes it has some features that you do not want and you get annoyed and do not really know how to proceed. One option is to make a copy of the product and rewrite it. But doing this will put you in a maintenance nightmare since all updates of the original product will be hard of not impossible to insert into your version of it. One solution and/or best practice is inheritance. As you may remember this is what it looked like when we created an instance of my message before this little tutorial (do not get confused over the use of Swedish in the screen shot - somehow the browser I used was set on Swedish at the time of my screenshots): The inheritance trick By inheriting the product into a product controlled by you you can do minor modifications and still be able to allow the original product to upgrade (hopefully only with minor problems). I will illustrate this principle by overriding an old version of my message (the Plone Archetypes View Template Modifications version) into a product I call MyInheritedMessage. This will include the usual set of files or even more - but they are almost empty. Also your average product contains dozens of files and usually this approach only require about the same amount of files. Also the total number of lines of code is less than 100 in the inherited product (counting blank lines and comments). __init__.py config.py configure.zcml message.py Extensions/Install.py profiles/default/types/MyMessage.xml In order for the framework to see the different products as one content type there will be inheritance also the behavior I want to change is the default values of the fields in the my message content type. So some important code is stored in message.py: from Products.Archetypes.atapi import * from Products.MyMessage.message import MyMessage as MotherMessage from Products.MyMessage.message import schema as MotherSchema from Products.MyInheritedMessage.config import PROJECTNAME schema = MotherSchema.copy() schema['title'].default='Untitled' schema['alpha'].default='42' schema['bravo'].default='1337' schema['charlie'].default='-713' class MyMessage(MotherMessage): schema = schema registerType(MyMessage, PROJECTNAME) As you can see I: - import the class I want to override - override that class with a new class with the same name - modify the schema (this is optional but the reason for this whole tutorial) Overriding the old my message Four lines of xml will make this new product override the old my message and force plone into using the inherited one. These are stored in profiles/default/types/MyMessage.xml: <?xml version="1.0"?> <object name="MyMessage"> <property name="product">MyInheritedMessage</property> </object> These lines will be activated when the product my inherited message is installed. Most likely you will need to have the product my message installed prior to that - but I have not tried what happens otherwise. So this is what it should look like when you install the new product. As you might have guessed our content type called my message is now replaced with a new content type called, you guessed it: my message. So how does one know that we are using the new one? Well we just have to try it to see it. That is why you should introduce a little something to separate your products - even if it is just a new default value. The final result As you might have guessed any new instances of my message will have the properties defined in the old my message product, and also any behavior defined in my inherited message. In case of conflicts the new features will override the old - just like we wanted. Download link See also Plone Cms. This page belongs in Kategori Programmering.
http://pererikstrandberg.se/blog/index.cgi?page=PloneCustomizationOfThirdPartyContentTypes
CC-MAIN-2017-39
refinedweb
643
59.74
Howdy, I am just learning the c languge from Sam's Teach yourself C. I am on to Understanding Arrays, there is a question I had that was not answered in the book. The question was write a program to display the total memory space taken by the array(I understand this part), what I was wondering if you had a array of floating numbers to print the array out would I use a for loop or a while loop, because I cant figure out how to get it to work with a for loop, If i change i to a double or float it still wont work here is my code, And thank you all for your time and your suggestions. Code:#include <stdio.h> main() { double list_data[6] = { 1.12345, 2.12345, 3.12345, 4.12345, 5.12345, 6.12345}; int i, size; size = sizeof(list_data); printf("The size of list_data is %d\n", size); for (i=0; i<list_data[i]; i++) printf(" %.5f\n", list_data[i]); return (0); }
http://cboard.cprogramming.com/c-programming/112029-help-basic's.html
CC-MAIN-2016-07
refinedweb
171
71.18
All of my production Arduino projects allow some sort of configuration changes. Various operational constants are maintained in EEPROM. When the Arduino is first started, I can change these settings and rewrite them into EEPROM if I have a terminal connected to the Arduino. Generally, I am OK with connecting my laptop to one of these arduinos to make configuration changes, should the need arise. But I would like the option to be able to configure using an LCD screen and push buttons if reconfiguring were regularly necessary or if connecting a USB cable to the arduino were difficult. I have spent a lot of time over the years configuring datacom equipment and much of it is configured using a small LCD and a couple of buttons like this ADTRAN TSU This particular device uses enter/up/down/cancel to navigate its menus. This is the kind of functionality I’d like to replicate on an arduino. I purchased a LinkSprite LCD/Keypad shield for the arduino from Sparkfun. It looks like this: The docs says the shield uses digital pins 4-9 and analog pin 0. The schematic indicates pin D10 is being used as well and looking at the board a trace does appear to go somewhere. The LCD display is a normal display and can be accessed using the standard liquidCrystal library. The buttons are a bit weird. All 5 buttons connect to a single analog port and each has a different resistor assigned to it so that when each button is pressed, the analog port returns a different value. I started out having a lot of trouble dealing with these switches. I started at the LinkSprite site and downloaded their sample code. Well, that was for Version 2 of this board and evidently sparkfun (at the time of purchase any way) was selling V1. V2 appears to allow you to press buttons simultaneously and V1 doesn’t. I found the correct sample code here. This code worked fine for me; however, I found it rather difficult to follow. I wrote my own getkey function which is far clearer (at least to me) #include <LiquidCrystal.h> const int maxDeviation = 5; enum keyNameE {none=0, right=1, up=2, down=3, left=4, select=5}; // initialize the library with the numbers of the interface pins LiquidCrystal lcd(8, 9, 4, 5, 6, 7); int getKey( ) { int curValue; curValue = analogRead(A0); if (abs(curValue-0) < maxDeviation) return right; else if (abs(curValue-143) < maxDeviation) return up; else if (abs(curValue-332) < maxDeviation) return down; else if (abs(curValue-507) < maxDeviation) return left; else if (abs(curValue-740) < maxDeviation) return select; else return none; } // getKey void setup() { // set up the LCD's number of columns and rows: lcd.begin(16, 2); lcd.print("hello, world!"); Serial.begin(9600); } void loop() { int curValue; int i; int lastValue = 1023; while (true) { i = getKey(); switch(getKey()) { case none: lcd.setCursor(0,1); lcd.print("NONE "); break; case right: lcd.setCursor(0,1); lcd.print("RIGHT "); break; case up: lcd.setCursor(0,1); lcd.print("UP "); break; case down: lcd.setCursor(0,1); lcd.print("DOWN "); break; case left: lcd.setCursor(0,1); lcd.print("LEFT "); break; case select: lcd.setCursor(0,1); lcd.print("SELECT "); break; } } // while } It is very disappointing that getKey cannot return an enumeration. I spent way too much time trying to force it. From what I gather, the Arduino IDE’s preprocessing some how messes this up such that I can only return an int. Fortunately I can still use the enum labels in the switch so clarity is maintained. If you use this code and find that certain buttons aren’t recognized, increase the deviation constant. I found +/- 5 worked every time on my board, but if your resistors’ deviation is more than mine, you might have an issue. Once I had the sample code running smoothly, I set out to code my reconfig function which allows configuring of the arduino via the shield. Here’s a short video of how this functions: I’m not going to post the code here. It isn’t a simple function call. You must encode the strings into a switch statement so really it consists of a skeleton function that is hand-modified and then getKey and another function that handles the scrolling. If someone really wants this code, drop me a line and I’ll make it available.
https://bigdanzblog.wordpress.com/2015/01/23/linksprite-lcdkeypad-arduino-shield-for-software-configuration/
CC-MAIN-2017-39
refinedweb
738
62.58
This is an addin for Reflector that allows you to list all BizTalk artifacts contained in an assembly and extract them. Installation Donwload the attached file and extract Reflector.BizTalkDecompiler.dll into the same directory as Reflector (otherwise it won't work). Go to View|Add-Ins in Reflector, and Add Reflector.BizTalkDecompiler.dll. Usage Using File|Open..., add the BizTalk assembly you'll like to decompile to Reflector's assemblies list. Right click on the BizTalk assembly and select "BizTalk Server 2006 Artifacts". You should see a list of all artifacts, with their type, name and namespace they were compiled into. Click the "Decompile..." button to decompile all selected artifacts into source files. You can select / de-select artifacts by using the selection check box on the right. In the decompile dialog, specify the path to the directory where files should be created and press "Decompile". The decompile dialog is multi-threaded for a more responsive user interface. Screenshot Limitations [Update June 19, 2006 - 10:00] This addin was compiled for the .NET Fraework 2.0 and Reflector 4.2 (and above). It will not work with the .NET Framework 1.1: you will get an error comparable to: System.BadImageFormatException: The format of the file 'Reflector.BizTalkDecompiler.dll' is invalid.File name: "Reflector.BizTalkDecompiler ᜧ.ᜀ(String A_0) I am currently investigating a port to .NET 1.1 but I do not promise I'll do it. The addin was designed for BizTalk Server 2006 which requires the .NET Framework 2.0 so you should have any problem. Most BizTalk artifacts can be decompiled back to their original source form (Pipelines, Schemas). Some artifacts cannot be decompiled to their original source (Maps). When decompiling a map, the addin will export the XSLT which was generated by the compiler, not the actual .btm file. [Update June 9, 2006 - 13:00] Recovering the full source of orchestrations is possible but invovles a manual step. After exporting, open the .odx file in the BizTalk Orchestration Designer (in Visual Studio) and save it without making any change. The editor will rebuild missing information which cannot be infered from the compiled assembly. Once this is done, the resulting .odx file should behave as if it was the source of the orchestration. Feedback welcome! [Update June 9, 2006 - 12:20] This tool is handy but I'd like to make sure everyone understands that is is offered "AS IS" with no warranty. I did not anticpate so much interest in the tool so I had to append this legal disclaimer. This being said, if you found a bug, want a new feature or just want to say that you are using BizTalk decompiler and you love it, feel free to use the "Email" link above to drop me a note!
http://blogs.msdn.com/b/gzunino/archive/2006/06/09/623391.aspx
CC-MAIN-2014-41
refinedweb
466
60.41
. New Features - Duplicating Components - Transforming Components - Undo/Redo - Configuration Searching - Auto Updating - Screenshots Duplicating Components How many times have you copied and pasted a set of source code and/or configuration and modify a couple of values to save on some keystrokes? The designer now has the same ability by providing you the ability to duplicate sets of components and then modify their values. Take a look at this quick sample where I've leveraged the duplicate functionality to quickly build a form without dragging and dropping the components and setting up common configurations over and over. Building a simple form: Transforming Components When developing you are capable of quickly changing a component from one class to another without losing your configurations by changing the class that you are extending from or instantiating. For Example: MyGrid = Ext.extend(Ext.grid.EditorGridPanel, { }); // or new Ext.grid.EditorGridPanel({ }); Developing in the Designer should not be any different. If after creating a GridPanel I decide that I really meant to use an EditorGridPanel. I can right click on the component within the inspector and see which transformation options are available. A GridPanel can be transformed to an EditorGridPanel and vice-versa. Let's put together a GridPanel. When we drag out a field for a particular column the designer intelligently knows that in order to use a TextField within a column it must convert itself to an EditorGrid. The designer will automatically perform this transformation for you. Another interesting transformation is converting a TabPanel to a Panel and then setting the layout to accordion. Fields are capable of transforming between types. Component Undo/Redo If you make a mistake while putting together your application you can undo/redo the last change that was made via the Undo and Redo buttons in the top toolbar. A current limitation of this feature is that if you perform a transform on a top level component then the history is reset. Configuration Searching A critical feature missing in prior releases was the ability to search configurations which are available to the component you have currently selected. In the past, if you were searching for a component configuration you had to look through the entire list available! The screenshot to the right demonstrates searching for the 'la' configuration in a FormPanel. You can now unset configurations by clicking on the x on the right hand side of the configuration. This is useful when you want to remove setting a configuration and not just set it to "". Newly Added Components Some of the exciting new components added are: - EditorGrid - ButtonGroup - BoxComponent - Slider Auto-Update We are using Adobe AIR's Auto Update framework to provide updates to the designer as we push out new public releases. When we release a new version you will be prompted to update to the latest version. You can expand out the "Release Notes" to see what enhancements and bug fixes have been made. Adobe AIR provides us the ability to quickly deploy updates to all of you as new versions are released seamlessly. Auto Updating the Designer via Adobe AIR Screenshots - Leveraging ActionScript within Ext JS One feature we wanted to implement within the designer was taking screenshots of your budding prototype directly within the application. Imagine this, you quickly mock up a borderlayout complete with tabs, a grid, and a form and then click the screenshot button. You can then choose to save the screenshot of the component you've just created as a PNG. We thought that this would probably be a simple task within AIR but ended up having to do quite some digging to figure out how to accomplish it. In order to create a screenshot of the applications current state we can use air.BitmapData to retrieve the raw bitmap data of the current screen by calling the draw method. var capture = new air.BitmapData( window.htmlLoader.stage.stageWidth, window.htmlLoader.stage.stageHeight); capture.draw( window.htmlLoader ); The contents of the variable capture now has the raw bitmap data of our entire application. We'd like to convert this into a modern format like PNG and save it to the file system. We will use PNGEncoder from as3corelib. You can compile and use any arbitrary actionscript code to a SWF and expose it to JavaScript within Adobe AIR by including it in the page by giving it a type of application/x-shockwave-flash. Use the mxmlc compiler from the Flex SDK to compile the code: aaron@aaron-desktop:~/as3corelib-.92.1/src$ mxmlc -source-path=. com/adobe/images/PNGEncoder.as Loading configuration file /home/aaron/FlexSDK/frameworks/flex-config.xml /home/aaron/as3corelib-.92.1/src/com/adobe/images/PNGEncoder.swf (1242 bytes) You can then copy the file into your project and include the file: We can now encode the raw bitmap data and write it to the file system: var file = air.File.documentsDirectory.resolvePath('screenshot.png'); var stream = new air.FileStream(); // Encode image captured from air.BitmapData var png = window.runtime.com.adobe.images.PNGEncoder.encode( capture ); stream.open( file, air.FileMode.WRITE ); stream.writeBytes( png, 0, 0 ); stream.close(); When you import classes from ActionScript into your HTML App they will immediately be placed in the window.runtime namespace with their appropriate package namespaces. Therefore our class com.adobe.images.PNGEncoder is placed in window.runtime.com.adobe.images.PNGEncoder. (As an aside this is all AIRAliases.js file which you include simply provides smaller aliases from window.runtime into the air namespace.) When taking the screenshot we also use a clipping rectangle and the copyPixels method to to grab only the bounding rectangle of the currently active component. Summary We've added lots of features which should improve your productivity when building user interfaces with the designer. We hope you like our progress and as always we greatly appreciate your feedback. For those of you that have suggestions, questions, found bugs, or just want to make a remark—we are listening. There are 201 responses. Add yours. Tweets that mention Ext JS - Blog -- Topsy.com5 years ago [...] This post was mentioned on Twitter by Aaron Conran. Aaron Conran said: @extjs New blog post: Ext JS Designer Preview #ext #xds New Features to improve productivity [...] Medvedev5 years ago Hello, Aaron! It’s awesome app. How can I save project in JavaScript in this designer? prometheus5 years ago Hi Medvedev, project saving ability will come in the stable release, in the time when ExtJS 3.1 released, if I knows as right. Sergey Popov5 years ago Looks great, looking forward to see demo with import/export and save/load functionality. Mats5 years ago Looks fantastic, can’t wait for the release!! IntelliJ IDEA??????? » Blog Archive »5 years ago [...] ExtJS??Blog?? JS Designer????????1.0.5???????????????????title?config??????????????????????????????????????????????????????????????? [...] Henry5 years ago Ext JS FTW! Troy McCabe5 years ago Incredible upgrades to 1.0 that was previously out. Makes it _so_ much easier to do tedious tasks, or templated configs. Excited for what else is in the pipes too, you guys do great stuff! Nickolay5 years ago Great work! Will it support user extensions of different kinds (for example layouts)? Aaron Conran5 years ago Nickolay - Yes, it’s in the works to support user extensions of all kinds (Components, Plugins and Layouts). When we complete the marketplace infrastructure more details will follow on how to implement your own user extensions for use in the designer. Crysfel5 years ago Awesome!! really impressive. thank you for this update. Eric Berens5 years ago Very nice work Aaron and team. I have to say using the designer has helped in prototyping and debugging complex layouts. I look forward to future functionality and work on the project. Keep it up! Paul5 years ago Nothing major but just pointing out that the “download” link above doesn’t work in Safari on the Mac. Firefox is fine. Jonathan Griffin5 years ago Speechless as always! Brian Deacon5 years ago I’ll bite. Even after learning what a .cpgz is and figuring out how to crack it open… I still don’t see how to install this. It’s an Air app, yes? Link to some intall instructions? Eric Berens5 years ago @Brian If you have Adobe Air installed () you should be able to download the file and run it. The installer will automatically start. Ian5 years ago Is it just my AIR environment…but how do you actual see the JS code that gets generated from the UI you create by all the dragging and dropping? I don’t see any place or button that says view code, neither does any JS file get created in my install dirs (I’m assuming my environment is restricting this). Has anyone been able to see the generated code for their components? Brian Deacon5 years ago @Eric Dunno if this happens automagically in a windows environment, but on my mac, I had to rename the .air.zip to just .air and then the extension association picked it up. (And now I just learned that .air files are just zip files with a different name…) Claude5 years ago Great job Aaron! It’s great to see Designer make so much progress. Designer has helped us complete prototypes much faster than before since we are able to visualize the components and use real data. Keep up the god work! Claude5 years ago God-like work or good work, your choice. :D Aaron Conran5 years ago @Ian Code generation is not currently in the designer. This will come in the ‘Pro’ version release in a month’s time. If you’d like to take a look at what the code will look like: @Clause lol @Brian Did this only happen with Safari? How about Firefox? Tof5 years ago Good stuff! Can we download it without Air packaging like a tar or zip file? ??5 years ago ?????????????????? Mark5 years ago This is fantastic. Look forward to the release! Mark5 years ago This is fantastic. I look forward to the release! nickevin5 years ago ?? ???????? ?????? friends, the generated code features are fee-charging Gisma5 years ago ?????, ?????, ????? Jason5 years ago Aaron you are a genius! Great stuff man. Murat Çorlu5 years ago This will be great with saving or viewing design code support. Great job! Burivuh5 years ago This is awesome! =) FashionPRG5 years ago ????? ??????? ??????. ?????????? ???????????. ???????? ?? ?? ? ???????? ??????????... ????????? ??? ??????? ))) tamsuper5 years ago i will test it now. Ext Designer Preview | ExtDesenv5 years ago [...] o mais novo preview do Ext Designer para deixar os membros da comunidade ainda mais ansiosos! Devo confessar que a cada lançamento de [...] josé mauricio5 years ago WOW!!! ExtJs rules! josé mauricio5 years ago extjs magic!!! Matt Bittner5 years ago When the Pro version is released, will it too require Air? Daily del.icio.us for October 2nd through October5 years ago [...] Ext JS Designer Preview Release – We are very excited to share our latest version of the Ext JS Designer. This new version adds many new features to improve your efficiency creating application designs. Once you get accustomed to these features its difficult to live without them. [...] Aaron Conran5 years ago @Matt Bittner - Yes, it will always require an install. A web version is not an option as we need to be able to write/read to the file system. It also enables us to do some pretty slick things given that we know our users *always* will have a WebKit browser and lightning fast JavaScript. Ethan Brooks5 years ago Will the production release be in available as in browser JavaScript that can be modified and incorporated other applications? Nuke5 years ago I am playing around sigma builder, it’s simple but easy to use. But when I go deeply into programming, documentation is poor. Anyway, this builder&it’s source could be used under LGPL license. Ajaxian » Ext JS Designer Preview5 years ago [...] Conran has published a new preview of Ext JS Designer which includes the new [...] Matt Bittner5 years ago Thanks, Aaron. Also one thing to keep in mind. I’m not sure about others, but I know the project I’m on resides not on the “internet”, per se, but instead a different, stand-alone network. If there are others, maybe there needs to be a way to “disconnect” the designer from automatically checking whatever Ext site for updates, etc. Maybe this is already within the app and if so, my apologies for wasting time. Aaron Conran5 years ago @Ethan Brooks - No, we took the desktop approach which allows us to read/write to the file system and be guaranteed that we know the environment that you are running in. @Nuke - Thanks for the link. It’s interesting to see what other people are doing in the same space. @Matt Bittner - This shouldn’t be a problem at this point. However, we are intending to add authentication to Ext so that you can dynamically get pro features and/or access to any components that you’ve purchased in the upcoming marketplace. That may pose an issue if you are in a secure financial/government environment as you are describing. Chester James5 years ago Music credits would of been nice, that’s a cool tune. Oh yeah and the designer is looking very slick. Rock on! Jordan Lee5 years ago Wow, looks like this will help to prototype new designs quickly. Looking forward to trying it out. NaYi - Programación y Herramientas online »5 years ago [...] Enlace | Ext Designer [...] Aaron Conran5 years ago @Chester James - Music is Pony Pony Run Run - Hey You Dan Schad5 years ago Nice concept but the download did yield a very good experience. The layout did not run correctly in firefox and wouldn’t start at all in explorer. Very interesting to see what this will finally work like. Aaron Conran5 years ago @Dan Schad - You need to install the Adobe AIR runtime to use the Designer. Ext JS Designer Preview « Articles5 years ago [...] Conran has published a new preview of Ext JS Designer which includes the new [...] ?5 years ago ?? bill5 years ago it feel so good ,and i like it Joel5 years ago Like Dan, i have Adobe Air installed but designer wont run on IE8. Running on firefox though. Love it. chamika somasiri5 years ago can you develop this as a EXTJS development tool this is useless tool i don’t want to get screen shots i want to build a working application please improve this in to EXTJS Development Tool like EXTJS IDE… Tommy Maintz5 years ago @Joel The Designer is not meant to run in the browser! It is an actual desktop application that you install locally. Adobe AIR is a platform that allows you to install applications written in HTML/Javascript. It allows us to open/write to files on the filesystem, and many other things that we need to provide certain functionality. If you have Adobe Air installed, and you run the .air file we have provided, it will ask you if you want to install the Designer, where you want to install it, etc. @chamika somasiri Taking screenshots is just one of the functionalities that we provide. I don’t know if you have actually read anything we have explained in our blogposts, but the Designer will of course allow you to build a working UI. It will generate Javascript classes for you, not just take screenshots. Ash5 years ago Am new to ext-js the designer preview looks great and seems ideal for a newbie like myself, would love to install and have a play around. Are there any installation instructions around. giuspel5 years ago Fantastic ... I look forward to the release of version 3.1. Stupid question : The button “Load Data” for JsonStore doesn’t work? Bye GREAT work Cristian5 years ago Hi. Congratulation for the great work! Impressive! A question: I want to integrate a designer in a web tool. It is possible to have a particular license (paying a fee of course) to embed ExtJs Designer in my application? Thank you, Cristian man5 years ago ??????? ?????, ???????? ?????? ?????????? ? ????? ?????? ????? Friday video: Ext JS Designer Preview « Posi5 years ago [...] More information can be found here. [...] Chris5 years ago I was checking out the preview via the download. What’s up with the viewport -> borderlayout? I don’t see any regions and nothing in the component properties related to regions… TriPToNe5 years ago Great stuff! But, - i cat’t save/load my designs, - when I change the component layout, (especially form -> table) the new layouts component config do not appear (OSX 10.5.8, Air 1.5.2, Ext Dp 1.0.5) - ext direct support? I’m also glad for a form to grid transform. I’m waiting for this tool very long time… It will be part of ExtJs distribution or a separated like JSBuilderX? ExtJs rocks! Keep good work! xxx5 years ago Don’t you think this is like becoming VS ASP.NET components now Aaron Conran5 years ago @ash - Install Adobe AIR and then download/install the .air file linked above. @giuspel - Did you specify a url for the JsonStore? Did you specify what fields would be in the response? @Christian - We haven’t made any decisions yet about OEMing the designer for integration with other products. @Chris - Viewport is just a specialized container. It does not immediately mean that it is a borderlayout. Change the layout configuration to ‘border’. Then drag and drop additional panel’s into the container. They will be auto-assigned regions which you can manipulate afterwards. @nicksaint - Yes, we will have a service that is capable of generating classes for what you design. @TripToNe - Code generation will be part of an additional service that plugs into the designer. Could you tell us more about your problem changing layouts from form to table? Ext Direct support is coming! :D It will be a separate tool like JSBuilder. We will distribute both a free and a paid version. Steve5 years ago Trying to use the jsonstore and it says url has not been set. i have a local server with some json i want to use in the grid. How would i go about setting the url? I set the url to and it still doesn’t work what am i doing wront? Michael5 years ago Nice job guys! Can’t wait until release. Currently, using Coolite.com for ASP.NET. Looking forward to an agnostic visual designer! Any idea when you guys will be ready for beta! I’m in! PS - Funky bg music! Heheh Ben5 years ago Aaron is the man! Keep up the great work. The designer is coming along nicely, can’t wait until I can see the code it generates. Ext JS Designer IDE ??? | ???5 years ago [...] ExtJS??Blog??- preview/????Ext JS Designer????????1.0.5? [...] Ext JS Designer 1.0.5?? | ???5 years ago [...] ??Ext JS Designer????? [...] Eddy5 years ago Bravo, voilà un super outil! Ext JS Designer 1.0.5 (Preview) | ExtJS????RIA????5 years ago [...] ExtJS???????????????????????? ExtJS Designer ? [...] Abner5 years ago Its getting very mature, I just tried this new version and I rellly enjoyed, but I see it’s just some demo cuz I can’t save or export the code. Anyway very nice job! g130135 years ago pity that it is payant, i understand why it is, seen the tremendous work that it represents and at the same time it is sad!. good work kriz5 years ago There is a bug…....... While I’m adding a jsonstore to a gridpanel,then quickadding the fields,I can not add any more fields.It doesn’t work. Tony Galfano5 years ago This is very impressive. I’m new to Extjs and have been exploring the various libraries hoping to find one that I can sink my teeth into and learn to integrate into my projects. This designer puts Extjs way out front for me. I do have a question about database connectivity. Is it possible to incorporate database connectivity and field binding into the designer? For example, when setting up the project you could select the database and have the fields available for inclusion in grids, forms and other data bound elements? Great work and I’ll most likely by a license for this great library….hope the designer release is coming soon too. Scott Hathaway5 years ago Hello - just wanted to give feedback on your visual designer. I really like the product. I work for Bell Helicopter and we would be purchasing it along with ext js support and licenses. We would much rather pay for the tool upfront instead of a yearly fee. Just my perspective. Scott jlhs55 years ago 3 questions. 1.- When is release a version? 2.- What will it cost? coldsore information5 years ago Looks fantastic, can’t wait for the release!! CA5 years ago The install is confusing because in IE the download link ends up saving a file named xds-1.0.5.zip, instead of the correct name of xds-1.0.5.air. A simple rename fixes this up but I suspect many people attempted to open and work with the contents of the zip. Download and install instructions when using IE: - Install Adobe Air: - Save download link file with a .air extension - Run .air file ?????5 years ago ???? ?????? ??? Chris Dawes5 years ago At the moment it’s a little annoying not to be able to quickly add json snippets in various places to speed up things, but I guess as you mentioned, it’s coming. You could add another tab to edit the json then click update and be back in the designer… kind of like ‘code’, ‘split’ and ‘design’ views in Dreamweaver. Surely the community version should allow you to actually get ‘something’ out of the designer… if so what? Can I whip up layouts for free? Are you going to charge per component or by a block of components? I like to own what I pay for… so I recon you should offer pricing for both models. Alfvin5 years ago Hi, nice app! I created a viewport, panel, grid panel, array store and data fields Inside Component Inspector panel (on the right), right clicking on data field.. then the context menu is stuck there forever, can’t close it. clicking new project, it’s still there.. Brent5 years ago Designer looks cool. But I’m not familiar with EXT JS so I’ve got a newbie question. How easy is it to link your controls to a database like MySQL? I’m from a Delphi background and would like to see controls that have a datasource so it can connect to a database table. This will allow it to display and save the contents back to the database. How easy is it to do this? TIA Brent Kobyn5 years ago Is anyway to buy the code generator for Ext JS designer preview? Tom5 years ago How download Ext JS Designer Preview? np5 years ago question - how do i run / install the extjs designer? Andrew Jones5 years ago @Tom, @np: There is a download link in the first paragraph. Thierry5 years ago Just amazing, there will be no more reasons for beginners to say I dont know ExtJS enough to start a project (great example, great doc, and now great designer) you are the best ! ?5 years ago ???? ?5 years ago ?????? anishanc5 years ago Code generation is not currently in the designer. When ‘Pro’ version will release ? Emernet5 years ago When will be available the new version? thanks Alex5 years ago When do you plan to generate EXT GWT code from this designer? Maybe some file.designer.java code? Serious, efficient, complex and MVC based apps with unit testing have to use such technology or you will be in trouble ... james5 years ago download? Chris5 years ago I read in a previous post where the guy said he would like the cost to be an up front charge and not a yearly charge. I agree with that. lylyliu5 years ago It’s very great Arno Nyhm5 years ago it works also for GXT? Johnson5 years ago Great stuff! awasome l5 years ago So when is this going to be released? kdemon5 years ago Extjs, the best framework of javascript that I know, excelent!!! Michael5 years ago Hello, So is this due to be released at the end of November or in December? Very impressive product. Michael George5 years ago Awesome! Great song, great framework! Great blog!!! Ext JS Designer Preview « Mas Husni5 years ago [...] Hingga saat ini, Ext JS hanya menyediakan aplikasi preview-nya saja, yang dapat diunduh di blog Ext JS. Atau untuk lebih singkatnya klik di sini untuk mengunduhnya.Aplikasi preview ini hanya dapat [...] SkullTraill5 years ago It downloaded in the .air format… Isn’t it a program? If so, how do I use it then? husni5 years ago Try downloading Adobe Air runtime at here: manfeng5 years ago Ext.fly()?????? Arul5 years ago Using Ext JS Designer to design a form finally how to get the source file any one explain.. Isaias5 years ago Hello Aaron, I did a test with this new version and found it very good. How do I save the source code and use in my applications? Do I need to buy the version to have this functionality? Thank you. 3xc3ption5 years ago qutoe Aaron Conran: “Code generation is not currently in the designer. This will come in the ‘Pro’ version release in a month’s time. If you’d like to take a look at what the code will look like:” best regards 3xc3ption amsaid5 years ago Great tool! the sad part is that ExtJs license makes tool and library unusable for small companies in small countries (the license will cost me more than i can earn with it). Only the rich can get richer Oscar5 years ago Congratulations, great work. Thank you Giuseppe5 years ago What a great tool! Did you plan to support treeview(s)? bruglur5 years ago When will be available the PRO version with the code generation? l5 years ago Really, when is it going to be availabe? Can we at least have a rough date? Ext JS - Blog5 years ago [...] while supporting faster, more robust applications. We are also still hard at work on the Ext Designer, which we hope to debut in the next few months. Make sure to update your version today and check [...] hguhf5 years ago Congratulations, good job. Thank you jeux gratuit5 years ago plz can i copie this article to my blog???????????, Frank5 years ago Designer looks good! I did a translation of this blog post, for Chinese readers. the url???????????: Florian5 years ago What i dont get is, how can i save what i have just designed? is there now way to get the code (config, components) out of the designer, or is this all about taking screenshots of them? Robert5 years ago Nice Video, Terrible Song. Perhaps I’m a little conservative to listen this crap. Sonic5 years ago Incredible upgrades to 1.0 that was previously out. Makes it _so_ much easier to do tedious tasks, or templated configs. Excited for what else is in the pipes too, you guys do great stuff! sam5 years ago We’re considering using ExtJs for new products, but we find writing user interfaces in code a time consuming and tedious task. Is there a timeframe for the release of the designer? limin5 years ago It’s very good! limin5 years ago good! Gabbay tecnologia desenvolvimento de sistemas5 years ago This is amazing. It´ll help for fast conding with greatful visual. Gastón5 years ago Great job! When will be released a version with a saving option? yaseen5 years ago Great work…....awesome…I am waiting for releas Courtney5 years ago any update on how soon this will b released. Looks amazing, a rough idea would be cool, eg feb/march ish anything? this teaser is torture! Tomy Adams5 years ago Ext JS Designer, a high-quality product. This quality of the product designers to easily access required. For this, there are various promotional and marketing methods. These result in the easiest one is the Google Ad. For this, I would recommend this site. GoogleAds far5 years ago what is the name of the song and artist? Leon5 years ago ??-?? ?????: lambert5 years ago como puedo hacer una consulta sql y mostrar los datos en un combo Bassam5 years ago How to use Array Store? 2010: The year Ext JS takes over : Ed Spencer5 years ago [...] is being placed on helping developers create their applications much more quickly, with the help of advanced creation tools and a standardised application architecture right out of the [...] Darwin Naranjo5 years ago Simplemente maravilloso! Harrison Clarity5 years ago I could not really watch the first video I see how much I’ve gained momentum on this issue serious projects and those who want to share information please visit the website Astosoft Tweets that mention Ext JS Designer Preview - Ext5 years ago [...] This post was mentioned on Twitter by Sofiane HASSINE, Nils Abegg. Nils Abegg said: wysiwyg editor for web app gui using ext js library [...] xiaomao1015 years ago ?????????????????? ??5 years ago ????Ext Jeff Kesselman5 years ago Is this going to be part of the Extjs 3.x package or will it require a seperate license fee? Jeff Kesselman5 years ago One more question…. I coudl not find a way to make a tree view. Is this still in development or did i miss something? Peter5 years ago ???????????? tony5 years ago Cool! If this can run on web, that would be the best. I did find something like this, but i,t doesn’t work well. extjs dev5 years ago i don’t know how to build code, i have build PNGEncoder.swf but i don’t know use it bee5 years ago ????????????????????????????? Bernd5 years ago From another post in forum, it said the price could be $200 (per year?). How much is it? When will it be released? Thanks. Alexey5 years ago AWESOME! I really impressed guys, i have seen a lot of in computing technologies, but you are real gurus!!! Good luck for you!! Druckertinte5 years ago Yea, that´s right Alexey. Thanks for the Video and for the many usefully Questions and Answers Anish5 years ago Wow good tool… Please add export and import facility. Jesus Manuel Olivas5 years ago This tool will be released any soon ? Jesus Manuel Olivas Werbeagentur Regensburg5 years ago Interesting tool i Think about to get it. greets robert Ext JS Designer Preview | ICSOCIAL BLOG5 years ago [...] Preview and solution click here!!! [...] Chear5 years ago good tool. totti5 years ago very good! Softdownload5 years ago I think this is a wonderful idea to talk about it, and I am really grateful I found your website Sean5 years ago Any thoughts on making a version for GXT? Nounou5 years ago Just discovered Ext-JS and really impressed by the product! Bernard5 years ago Is the tool built with ExtJS or ExtGWT? sasaki5 years ago When do you release it? wktk Josh Owen5 years ago Any release date? Rogerio5 years ago Please, I just need when do you release it? When do you release it? William Mansfield5 years ago I concur; Give us an estimated release date! Can’t very well plan to include it in any upcoming project expenses if we don’t have an idea on when we can have it. Diseño Web5 years ago wow es fantástico el potencial de esta aplicación. Vish5 years ago Hi, can you please tell me how I can get this tool? cars5 years ago c’est interessant , merci pour l’info ! Laxmikant5 years ago When is this product will be launched.. Anurak Ravirojana5 years ago ???????????? Very good!!! David Winnup5 years ago I have Pre-Ordered and my money has been taken, surely we deserve a release date emailed to us for pre-ordering? crashT5 years ago When is this product will be launched ... Can you say a Date? Edgar5 years ago I have bought a preorder but i deserve an mail confirmation and at least the release day :s scabies pictures5 years ago Nice product. I’ve already view the preview and it’s a very good software must have for ajax lover. Gigi5 years ago I check here everyday to see if a release date has been announced. As someone said earlier, how can we include it in project expenses if we don’t know when it will be released? My boss is having me evaluate UI prototyping tools at the moment. This seems like it would be an even better candidate than a straight UI mockup tool but unless this is to release imminently, we will have to go another direction. Gigi5 years ago Actually, looking a little closer at the demo above, I don’t see on the widgets list on the left a tree, a spinner, or even a combo box. Will these be included in the product? Michael5 years ago I testet the Designer preview and miss some things like the combo box, a tree. I´m thinking about the Pre-Order - does anybody know something about the release date? herpes photos5 years ago Excellent product should have for web developer. Thanks for your effort. dp5 years ago Has anyone got the release version(released today) and tried? Looking for more details / screen shots / features before I buy this. No further information available here except a link to buy.. Waiting.. Henry_James5 years ago cool~ Air Jordan5 years ago Nice blog! There have a chance that we can have an furthur exchanges. May be we have common interests. Let’s keep in touch. Also I will always pay attention to your blog. Rafael5 years ago Hi There, Great tool, but the pricing for single developer is very expensive. Unfortunatelly here in Brazil there’s no way for one developer pay 219USD for a piece of software. Leo5 years ago Hi, I agree with Rafael, is very expensive for brazilian people =( I’m student and want to use this great tool. Zahnimplantate5 years ago Thanks for the fantastic Article Feng5 years ago I have been using the preview version and expected to use the update function to get the final release. However it looks like the packaging has changed from Adobe AIR to Qt so have to download the full installer. Any reason for the switch? asd5 years ago I really don’t think this will have a stand in compare to the visual studio and php editors. Anyways good attemp. djnGO5 years ago very exciting indeed JavaScript????5 years ago QQ??84507704 Javascript????/jQuery/ExtJS silk pajamas5 years ago your blog is so hot, there are so many replies. this method is so worked for me, i want to design my website. maybe i can get something for your blog. i will come here frenqutly, and learn more. LED TV5 years ago Great articles & Nice a site…. ??5 years ago gigirdfdf gread music~.... women's sexy pajama5 years ago your ground music is good Giochi per ragazze5 years ago I have been using the preview version and expected to use the update function to get the final release. However it looks like the packaging has changed from Adobe AIR to Qt so have to download the full installer. Any reason for the switch? Webstandard-Blog5 years ago Awesome, I didn’t know that it is so easy. Thx for publishing the screencast! free 3d wallpapers5 years ago ???? ?????? ???!! air jordam4 years ago I have been using the preview version and expected to use the update function to get the final release. However it looks like the packaging has changed from Adobe AIR to Qt so have to download the full installer. Any reason for the treatment for heart disease4 years ago I ran across this post book-marked and that i definitely loved things i understand. will certainly book mark it too and in addition go through the other blogposts later on. Juegos4 years ago I like the interface of Ext JS Designer, looks great. Best wishes to you. Fayaz4 years ago can i use the ext designer for making mobile app which can be done by sencha touch…sinces snecha touch can be done with full of code and i dnt have any time…to code…so i just need an drag n drop designer for iphone apps… . can ext designer help me? Siki?4 years ago pozycjonowanie4 years ago Valuable info. Lucky me I found your site by accident, and I am shocked why this accident didn’t happened earlier! I bookmarked it. Boat Cover4 years ago Nice website, I agree with you 100%! tadalafil achat en Mulhouse4 years ago <a >tadalafil achat en Limoges</a>, tadalafil 10mg en Mulhouse , tadalafil 10mg en Tours tadalafil 10mg en Nantes , tadalafil acheter en Dijon, <a >tadalafil 10mg en Villeurbanne</a> yavuz4 years ago thanks Comments are Gravatar enabled. Your email address will not be shown.Commenting is not available in this channel entry.
https://www.sencha.com/blog/ext-js-designer-preview/
CC-MAIN-2015-11
refinedweb
6,165
75.81
The friendly PIL fork. from PIL import Image colors = ((0,160,0),(33,150,243),(88,88,88),(255,0,0)) with Image.open('tradingview.png') as im: px = im.load() x, y = 0, 0 currentColor = None processedPixels = [] i = 0 # Start searching through all the pixels for y in range(0, im.height): for x in range(0, im.width + 1): def getColor(x, y): try: return px[x, y] except IndexError: return if (x, y) in processedPixels: continue color = getColor(x, y) if color != currentColor: if currentColor is not None: max_x = x # The color line has ended, from min_x to max_x x_range = min_x, max_x # The left side of our rectangle must also be a solid color # So search from the top left until we have a solid left side for y2 in range(y+1, im.height+1): for x2 in range(min_x, max_x+1): if getColor(x2, y2) == currentColor: min_x = x2 break else: # No color in this line, so we have hit the bottom of the rectangle max_y = y2 break # The same for the right side for y2 in range(y+1, max_y+1): for x2 in range(max_x+1, min_x, -1): if getColor(x2, y2) == currentColor: max_x = x2 break # Check that this rectangle is of a reasonable size if max_x - min_x > 10 and max_y - y > 10: # Record that we've processed these pixels, to save time for y2 in range(y, max_y+1): for x2 in range(x_range[0], x_range[1]+1): processedPixels.append((x2, y2)) # Check that the box is not purely one color singleColor = True for y2 in range(y, max_y+1): for x2 in range(min_x, max_x+1): if getColor(x2, y2) != currentColor: singleColor = False break if not singleColor: break if not singleColor: i += 1 # Save the cropped image im.crop((min_x, y, max_x, max_y)).save("out_"+str(i)+".png") if color in colors: # Start a line with a relevant color currentColor = color min_x = x else: currentColor = None getsize. from PIL import Image, ImageFont font=ImageFont.truetype('Tests/fonts/FreeMono.ttf', size=14) print(font.getsize('Username')) # (68, 12) font=ImageFont.truetype('Tests/fonts/FreeMono.ttf', size=28) print(font.getsize('Username')) # (135, 23) Pillow is a fork of PIL. PIL has its last release in 2009 Pillow had its last release a week ago. So there are a variety of features, bug fixes and security fixes that have been performed since PIL. However, Pillow is largely backwards compatible with the PIL API. PIL does not support Python 3 Pillow supports Python 3, and dropped support for Python 2 a few releases ago. from PIL import Image im = Image.open('test.jpg') # completes successfully im.copy() # fails with OSError: image file is truncated (0 bytes not processed)
https://gitter.im/python-pillow/Pillow?at=5e21dbc95b81ab262e41c1e2
CC-MAIN-2020-50
refinedweb
453
64.2
Importing image to python :cannot import name 'imread' from scipy.misc import imreadimporterror cannot import name 'imread cannot import name 'imread' from 'scipy.misc' cs231n scipy imageio no module named 'imageio' importerror cannot import name misc importerror cannot import name imrotate write image python I'm new to python and I want to import an image. import numpy as np from scipy.misc import imread, imsave, imresize # Read an JPEG image into a numpy array img = imread('Cover.jpg') print(img.dtype, img.shape) but I face with following error: cannot import name 'imread' I've already successfully installed numpy and scipy. You also need to install PIL (Pillow) as that is what scipy uses to read images: pip install Pillow note from the docs: imread uses the Python Imaging Library (PIL) to read an image. The following notes are from the PIL documentation. however, you might want to think about switching to scipy.imageio.imread since scipy.misc.imread is deprecated : imread is deprecated! imread is deprecated in SciPy 1.0.0, and will be removed in 1.2.0. Use imageio.imread instead Cannot import name 'Image', You are importing a wrong module. To install PIL I used pip install pillow. then you can use: from PIL import Image. in your python code. from PIL import Image. What did you expect to happen? What actually happened? ImportError: cannot import name Image. What versions of Pillow and Python are you using? Pillow==3.3.1 Python==2.7.12+ I use Kali Rolling and virtualenv. Please include code that reproduces the issue and whenever possible, an image that demonstrates the issue. Apparently a lot of people had this issue and the solution was to install Pillow. Perhaps try to install Pillow and run it again sudo pip install Pillow==2.6.0 Source of information: ImportError: cannot import name 'imread' from 'scipy.misc' · Issue , When running this step: ]$ python setup.py Traceback (most recent call last): File out for reference:- image-to-python-cannot-import-name-imread?noredirect=1&lq=1 cannot import name 'ImageTK' - python 3.5. cannot import name 'ImageTK' Python does act up a little when importing TkImage and Image together. You need to First, you should have Pillow, later your scipy version should be lower than 1.1.0 pip install Pillow pip install scipy==1.1.0 ImportError: cannot import name 'PILLOW_VERSION' from , I got this error while importing Image from PIL import Image Traceback (most ImportError: cannot import name '_imaging' from 'PIL' (/lib/python3.7/site- packages/PIL/__init__.py). It installed pillow 6.2.1, python is 3.6.9. Description When import skimage it shows ImportError: cannot import name 'img_as_float32' Way to reproduce # Place the full code we need to recreate your issue here import skimage.io # upload all necessary images to github too! Install pillow pip3 install pillow As scipy.misc is deprecated you cannot use it but instead from PIL import Image import numpy as np im = Image.open('hopper.jpg') a = np.asarray(im) im = Image.fromarray(a) this returns an image object Importerror cannot import name requirementparseerror, I tried to import one image using PIL library, but I got this error while importing Image. from PIL' (unknown location) How can I solve this? Importing Pillow as a part of a flask project. cannot import name '_imaging' @nchouard If you can from PIL import Image in Python then this is likely a mod Note: Posting the already given advises with a bit more as my reputation does not allow to comment In the latest version of scipy (1.3.0) functions like imread, imsave, imresize is deprecated. Downgrading scipy from 1.3.0 to 1.1.0 works like a charm and you will be able to use not just imread but all the above-mentioned functions which are almost necessary in most situations The command for downgrading: pip install scipy==1.1.0 ImportError: cannot import name 'PILLOW_VERSION' from , Cannot import name 'PILLOW_VERSION' from 'PIL' anaconda3/lib/python3.7 not from the local environment which is python3.6 not python 3.7. I got this error while importing Image from PIL import Image Traceback (most what that worked for me: go to the fodler . C:\Users\{YOUR PC USER NAME}\AppData\Local\Programs\Python\Python37-32\Lib\site-packages and either delete or change the name of the PIL folder and DONE. Cannot import name 'PILLOW_VERSION' from 'PIL', ImportError: cannot import name '_imaging' from 'PIL' File "d:\programming\ python\lib\site-packages\PIL\Image.py", line 69, in <module> ImportError: cannot import name 'export_saved_model' from 'tensorflow.python.keras.saving.saved_model' #39367 Closed sohamsahare123 opened this issue May 10, 2020 · 6 comments Error importing '_imaging' from PIL when trying to use mlagents , And then everything goes fine in the python package installation. related to the libtvm_topi.so, do 'export LD_LIBRARY_PATH=/lib/python3.5/site-packages/ from ..cpp.image import bilinear_sample_nchw ImportError: cannot import name ImportError: cannot import name 'export_saved_model' from 'tensorflow.python.keras.saving.saved_model' I have also tried @kari0219 's suggestion and also tried doing that with conda uninstall -y tensorflow cannot import name 'bilinear_sample_nchw' - Questions, Solution - Can't import the aec file into After Effects [English] TʀᴀᴘAʀᴛᴢ------- Today a quick tutorial on the problem of importing the . 7's standard library. If the script name refers directly to a Python file, the directory containing that file is added to the start of sys.path, and the file is executed as the main module. Source: Python 2 and 3. Let’s recap the order in which Python searches for modules to import: built-in modules from the Python Standard Library (e.g. sys, math) - Possible duplicate of scipy.misc module has no attribute imread? - It's not a "workaround" since it is not a bug, it is expected behaviour, since scipy need PIL(Pillow) to be able to read images. It even says in the docs - Only this solution worked for me.
https://thetopsites.net/article/54358767.shtml
CC-MAIN-2021-25
refinedweb
995
58.99
Did you know that Amazon is a member of the .NET Foundation? And that Amazon Web Services (AWS) supports a variety of .NET platforms such as hosting for ASP.NET Core apps? There are also .NET SDKs to connect to AWS services from your .NET apps, PowerShell modules and extensions for Visual Studio, VSTS, VS Code, and JetBrains Rider to connect to and interact with many of AWS’s services. I didn’t know any of this and when it was being relayed to me for the first time, I was surprised and a little embarrassed. Not embarrassed that I wasn’t expert in any of this but just that I hadn’t thought to look at any of this until now. So where to begin? Well, there are also a host of database engines in AWS and, given my long relationship with Entity Framework and EF Core, that seemed like a good first stop for me. What I’ll do in this article is take an existing small ASP.NET Core API that uses EF Core, use EF Core migrations to create a database on AWS, interact with the database, and explore secrets management for the database credentials both locally and for a deployed app. RDS is the acronym for Amazon’s Relational Database Service. Amazon RDS is a database service that provides access to several relational databases on AWS: SQL Server, Oracle, MariaDB, MySQL, and PostgreSQL. It also has a database called Amazon Aurora, which is Amazon’s cloud-native, distributed relational database that’s MySQL and PostgreSQL compatible. And Aurora is fast; according to Amazon (aws.amazon.com/rds/aurora): five times faster than accessing MySQL directly through RDS and three times faster than PostgreSQL. With the exception of Aurora and Aurora Serverless (aws.amazon.com/rds/aurora/serverless/), the RDS databases are also available via AWS’s free tier, which makes them great targets for exploring AWS databases with existing EF Core database providers. An important concept about RDS databases is that you start by creating a database instance that’s like a server. When creating an instance, you configure it for the type of database you want (e.g., SQL Server or MySQL) along with other attributes that affect performance, scaling, and cost. Then you can create databases inside of an instance. More on this later. I’ll take an existing small ASP.NET Web API and retarget it to SQL Server Express on RDS to see what the experience is like. If you want to follow along, you can download the starting example from github.com/julielerman/codemagawsrds or on the CODE Magazine page associated with this article. Setting Up an Account with AWS Free Tier You’ll need an AWS account in order to do any of this work. And if you don’t have an account, it’s easy to create one using the Free Tier (aws.amazon.com/freetier) which gives access to a variety of services that are always free, others that are free for some amount of use (e.g., number of GBs or hours), others that are free for 12 months, as well as access to free trials for some additional services. The RDS services are in the 12 months bucket, giving you up to 750 hours a month, 20 GB of storage and 20 GB of backup—certainly enough to start exploring. Go to aws.amazon.com/freetier to create the account. It does require a credit card. You’ll initially create what is called a “root account.” That’s like a master account and once that exists, you can create Identity and Access Management (IAM) users in the root account. AWS strongly recommends, as a best practice, that you only use IAM users to build apps and services, not the root account. When you create an IAM user, you can associate two access types: programmatic and management console access. You don’t need to create the IAM account in advance as the AWS Toolkit for Visual Studio (which I’ll walk you through below) will give you some helpful guidance for creating IAM user credentials and even importing them into the toolkit. But you do need to have the root account before you start. Here’s a link to additional information about identities in your AWS account:. Setting Up the AWS Toolkit with Your Credentials The AWS Toolkit for Visual Studio can be installed from the Visual Studio extensions. There’s also an AWS Toolkit for Visual Studio Code (), which is focused on creating serverless functions and applications. When you first use the Toolkit’s Explorer, a Getting Started page prompts you connect the toolkit to your IAM account or create an IAM account. Once you’ve associated an IAM account, the explorer lets you see everything tied not just to that particular IAM account but filtered by regions. I’d done my first RDS experimentation online, creating a SQL Server and a PostgreSQL database, then interacting with them through Azure Data Studio. This was one of those silly exciting moments in the life of a developer when I first got everything connected. Satisfied that I’d worked this out correctly, I moved on to Visual Studio and the AWS Toolkit. I’ll walk you through the AWS Toolkit path for creating the IAM account and your first database instance, and then you’ll let EF Core create a database using migrations. The Toolkit’s Getting Started page (Figure 1) provides a link to the AWS Console and also lists a small set of steps to perform so that you can avoid getting caught up in credential management. Following these steps, I began by signing into the AWS Console with my root account and then added a new IAM user named JulieCodeMag, checking the Programmatic access type as instructed by the Getting Started page. The next step is to either add the user to an existing permissions group or directly to one of the AWS policies. Again, as per the instructions, from the possible power user policies, I chose AdministratorAccess, which is okay for my purposes, not production. After this, I just left the last few options at their default and let AWS create the user. Finally, I clicked the Download .csv button, saved the file and then imported the CSV file into the toolkit using an option on the Getting Started page. Note that the CSV file doesn’t populate one of the fields—Account Number—and that’s okay. Next, I renamed the profile from default to JulieCodeMag and saved the credentials. As a result, the AWS Explorer was then populated with nodes for all of the services that the toolkit provides access to. And because the JulieCodeMag user has broad access, I was able to see services tied to any of my IAM accounts created in the specific region. I’d created my test database instances in the US East (Ohio) region so if the explorer is filtered on that region, I’ll see those instances. If I changed the explorer region, I wouldn’t see those database instances. Creating an RDS Instance Through the Toolkit You will need a database instance (remember, this is like a running server) before EF Core can create databases in that instance. And you can create new instances through the toolkit, so let’s do that. Right-click on the Instances node under Amazon RDS, then choose Launch Instance. That means to launch (create) a new instance. You’ll then see a list of the possible engines for which you can create an instance including various SKUs of Microsoft SQL Server and all of the other RDS options. I’ll choose SQL Server Express. For those of you who’re used to using EF Core’s Windows default, SQL Server LocalDB, for development, LocalDB is a slice of Express (). But it’s not a separate option from Express. Once you’ve selected the engine, you’ll be prompted to configure the instance to specify the database version, memory (“DB Instance class”) for which I chose the smallest: micro and storage. You’ll also be prompted to set up a user name and password. The highest version available as I’m writing this is SQL Server 2017. The next page of the configuration, Network and Security, has a critical setting that you need to enable, which is to make the database publicly available (see Figure 2) for the sake of this exploration. Do keep in mind that it’s not a best practice for production. Although the Toolkit will be able to see the instance, you won’t be able to connect to it from your code or from any tools like Server Explorer in Visual Studio, SSMS, Azure Data Studio, etc. By default, the databases are locked down and only accessible from within the VPC that RDS creates to host the instance. Therefore it’s also necessary to allow a specific IP address (or range) to access RDS so that other Visual Studio tools, such as the SQL Server Object Browser, are able to connect. To do that, be sure to check the “Add current IP” option also shown in Figure 2. There’s one more page with configuration for backups and maintenance. By default, RDS backs up the instance immediately after creation and then performs backups daily. For this exploration, I recommend changing that setting to “No Automated Backups,” which makes the instance available more quickly. The rest of the defaults are okay for our purposes. The grid for DB Instances shows the status of each instance (see Figure 3) so you can see when the new instance (in my case “codemagmicro”) is available. I did experiment with creating various types of database instances from the Toolkit. As I expected, both PostgreSQL and MySQL instances took less time than SQL Server although the difference wasn’t significant Once the instance is available, I can use EF Core migrations against my little sample application to create a database in the instance. You can download the sample or create a new ASP.NET Core API. As I’m using VS, I’m doing that through the create project workflow, not the CLI. I left defaults as they are: e.g., no authentication and configured for HTTPS. Given that this is using Amazon’s cloud, the model goes back to Amazon’s roots with authors and books. And keeping it simple, one author can write multiple books but there are no co-authors, therefore it’s a strict one-to-many relationship. public class Author { public Author() { Books = new List<Book>(); } public int AuthorId { get; set; } public string Name { get; set; } public List<Book> Books { get; set; } } public class Book { public int BookId { get; set; } public int AuthorId { get; set; } public string Title { get; set; } } Starting with ASP.NET Core 3.0, EF Core is no longer included in the default dependencies, so you’ll have to add Microsoft.EntityFrameworkCore.SqlServer to the project via NuGet. Additionally, because you’ll be using migrations, add the Microsoft.EntityFrameworkCore.Tools package, which gives you the PowerShell version of the migration commands and the design time logic. With EF Core included, I then added a simple DbContext class called BookContext. Note the constructor that’s needed for ASP.NET Core to use Dependency Injection (DI). public class BookContext:DbContext { public BookContext (DbContextOptions<BookContext> options) : base(options) { } public DbSet<Author> Authors {get; set; } public DbSet<Book> Books { get; set; } } Now it’s time to wire up the API with the database instance and specify a database to work with. I’ll name mine BooksDatabase because I’m a very creative human. More importantly, I’ll need the server name. The URI is formed as (with no line breaks): [instancename].[AWS Server Name].[region].rds.amazonaws.com. The DB Instances view gives you two ways to access the server URI. One is by right-clicking the instance and choosing properties; then, in the properties window, you can see and copy the Endpoint value. The other is by right-clicking the instance and choosing Copy Address to Clipboard. In order to avoid accidentally posting my database credentials to GitHub, I’ll use ASP.NET Core’s Secret Manager () to protect these credentials during development. If you haven’t used that before, right-click on the project in Solution Explorer and choose Manage User Secrets. This opens up a hidden secrets.json file where you can specify key pairs for your secrets. { "DbPassword": "mysecretpassword", "DbUser": "theusername" } Then, in appsettings.json, I created the connection string without the user or password attributes. I’ve masked the server name with asterisks. "ConnectionStrings": { "BooksDb" : "Server=codemagmicro.***.us-east-2.rds.amazonaws.com,1433;Database=BookDatabase" }, Finally, in the startup file where I configure the services to use DI to spin up the BookContext, I build up the connection string from the configuration info found in appsettings.json and the user and password from the secrets, and then pass the resulting connection string to the SQL Server provider’s options. All of this is achieved with the following code that gets added to the ConfigureServices method in Startup.cs: var builder = new SqlConnectionStringBuilder (Configuration.GetConnectionString("BooksDb")); builder.UserID = Configuration["DbUser"]; builder.Password = Configuration["DbPassword"]; Services.AddDbContext<BookContext>(options => options.UseSqlServer(builder.ConnectionString)); If you prefer to debug against a local database, you can use a SQL Server LocalDb connection in appsettings.Development.json (which doesn’t require a password). But that would mean putting the full AWS connection string into your secrets file and your code won’t need to build the string as it’s currently doing. To keep this demo simple, I’ll run everything against the cloud database. Creating the Database with EF Core Migrations Now everything is in place to create and execute migrations. I’ll start by creating a migration file named Initial with the EF Core command, add-migration initial, in the Package Manager Console (PMC) window. Once the migration file is created, I’ll call update-database in the PMC to migrate (in this case, create) the BooksDatabase database in the codemagmicro instance. If you have all of the pieces in place—the website instance is publicly available (again for this exploration, not production), your IP address is allowed to connect, your IAM account has the correct permissions, and the database connection string (along with its secret user and password) are tied to the BooksContext through the ASP.NET Core DI services—EF Core should be able to create the BooksDatabase database in the codemagmicro instance on AWS. If there’s something missing, the command will fail and I’ve found that it provides pretty useful information in its error messages. Connecting to the Database Because this is a SQL Server database, you have a variety of options for connecting: SQL Server Management Studio, Azure Data Studio, and other third-party tools. The toolkit makes it easy to connect right through the data tools in Visual Studio. First, you’ll add the instance to Server Explorer and from there to the SQL Server Object Browser. Here’s how. In the AWS Explorer, right-click the RDS instance and select the Add to Server Explorer option. This launches a Connection Properties window with the server name and SQL Server Authentication user name already populated. Just fill in the password and connect. The server should now be listed under Data Connections in the Server Explorer. You can see your database in there, but I much prefer using SQL Server Object Explorer in Visual Studio. Just right-click on the server in Server Explorer and choose Browse in SQL Server Object Explorer, and the instance will be added to the Object Explorer for you where you can see the database that migrations just created (see Figure 4). Although this is enough for me to be satisfied that everything is working properly, it wouldn’t feel right not to finish up creating and testing out the API. To do so, I’ll need a controller that interacts with my model. The quickest path is using the Add Controller wizard (right-click on the Controllers folder to get to it) to create a new controller—API Controller with actions, using Entity Framework—for the Author class. Now you can run the API to start interacting with it. With the new API running locally, I used the wonderful Rest Client extension for Visual Studio Code () to easily send a request to the API. I ran a POST request to the URI to add an author using the new controller. This is just a simpler alternative to other great apps like Postman or Fiddler for sending requests. Use whatever you prefer. Here’s the rest call that I executed: POST HTTP/1.1 content-type: application/json { "name": "Julie" } Once that data was in the database, I browsed to the controller’s default (localhost:5001/api/authors), which requests the GET method of the controller and can see that the API is truly connecting to the AWS database and returning the single author in that table, as you can see in Figure 5. Getting the Secrets on AWS for the Deployed App So far, the database connection credentials are stored on my computer using ASP.NET Core Secret Manager. When I deploy the API to the AWS Cloud, it’ll need access to those secrets. AWS provides a few ways to store secrets and make them available to other AWS services. Because I’m relying on ASP.NET Core’s ability to read parameters, I’ll use the AWS Systems Manager Parameter Store to tuck away my user and password values. There are a few steps involved. The Parameter Store console is an option in the AWS Systems Manager service under the Application Management section. In there, you’ll find a bright orange “Create parameter” button and in the details page for the new parameter, you’ll need to enter four pieces of information, as shown in Figure 6: - Parameter name: a combination of some name you’ll use, specific to the app and the name of the parameter. Remember, my first secret is called DbPassword, so I’ll use /codemagapi/DbPassword as the name. - Type: an important step that I missed the first time around, be sure to set the type to SecureString. That encrypts the value for you. - KMS Key Source: choose My current account. Leave the associated KMS Key ID at its default (alias/aws/ssm). - Value: the password value That’s enough to finish up with the Create parameter button below. Follow the same steps to create the DbUser. Next, you’ll update the application to read the secrets from AWS instead of ASP.NET Core. Once I know that’s working, I’ll show you how to make the app read from the local secrets during development and from AWS at runtime. Begin by adding the Amazon.Extensions.Configuration.SystemsManager NuGet package to your project. This was originally created by community member Ken Hundley and adopted by the AWS team, who are now the maintainers. Next, you’ll add a new section into the appsettings.development.json file, which you can access by expanding the appsetting.json node in Solution Explorer. This section allows any AWS extension to use the permissions assigned to one of the AWS Toolkit profiles you created. I’ve only created one, JulieCodeMag and it’s using the us-east-2 region. Therefore, I’ve configured the section as follows: "AWS": { "Region": "us-east-2", "Profile": "JulieCodeMag" } Finally, you’ll tell the application (in program.cs) to load the AWS parameters into the ASP.NET Core’s configurations. The new code, the italicized ConfigureAppConfiguration method in this code snippet, goes in the CreateHostBuilder method in program.cs. public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args).ConfigureAppConfiguration((context, builder) => { builder.AddSystemsManager("/codemagapi"); }).ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); By default, ASP.NET Core reads configurations from a number of sources, such as the appsettings files, your system environment variables, the ASP.NET Core secrets, and more. There’s a precedence that if a setting, such as my DbPassword, is found in multiple configuration sources, the last one read is the one that’s used. Because the AWS configuration is added in after the others, its DbPassword overrides the DbPassword read from the ASP.NET Core secrets file. Because of the AWS setting in the appsettings.development.json file, the extension uses the permissions from the Toolkit’s JulieCodeMag profile to read the AWS Parameters online. That’s only needed during development. When you deploy your application to AWS, you’ll need to be sure that the VPC instance to which the app gets deployed has the needed permissions to read the parameters. I won’t be covering app deployment in this article, as I’m focused on the RDS usage with EF Core. To really validate that the parameters are being read from AWS, not the secrets file, you can edit either DbPassword or DbUser in your ASP.NET Core secrets, which would cause the app to fail when trying to connect to the database if they’re the ones being used. Running the app with these modifications gives me the same results as earlier when I browsed to the locally hosted API. The data that’s in the RDS database is output exactly as it was in Figure 5. Now that you have confidence that this is working, you may want to go back to reading from the local secrets while developing and the AWS parameters in production. To do that, you can force the app to only load the AWS configurations when the application environment is production, not development. I’ve updated ConfigureAppConfiguration method to conditionally load the AWS configurations: .ConfigureAppConfiguration((context, builder) => { if (context.HostingEnvironment.IsProduction()) { builder.AddSystemsManager("/codemagapi"); } }) Even though I’m not walking you through the final bit of deploying the API, I did publish the API to AWS Elastic Beanstalk in order to see for myself that everything was working as expected. See the deployment article noted in the sidebar to learn more about deploying apps to AWS from the toolkit. Final Thoughts I love the fact that these modern times enable developers to use the tool and platforms they choose and that companies like Microsoft and Amazon don’t force us to be siloed into a single organization. Amazon’s investment in the .NET Foundation and support for .NET developers is broad-minded. That’s important to me as a consultant and coach because I never know what stack my next client will be on. Being able to take all of my skills and investment in .NET development and the related IDEs and use them on AWS is valuable. And for me, apparently with some blinders on for a while, it’s a revelation. Thanks to the free tier, I also have the ability to explore how I can do that. I look forward to broadening my horizons further on AWS.
https://www.codemag.com/Article/2005041
CC-MAIN-2020-40
refinedweb
3,846
63.39
2011/6/30 Eric Blake <eblake redhat com>: > :( Simple tests show that [v]snprintf works correctly with mingw (I didn't test mingw64) in case of a too small buffer. It's only broken in the context of libvirt. I finally figured out that libintl is the cause for this, as Eric already suggested as a possible cause on IRC. It's not related to libtool at all. libintl.h is included by gnulib's gettext.h, that is included by internal.h, that is included by buf.h, that is included by buf.c. This it how we get it there to break in libvirt, because libintl.h (from) contains this section #if 1 #if !(defined snprintf && defined _GL_STDIO_H) /* don't override gnulib */ #undef snprintf #define snprintf libintl_snprintf extern int snprintf (char *, size_t, const char *, ...); #endif #if !(defined vsnprintf && defined _GL_STDIO_H) /* don't override gnulib */ #undef vsnprintf #define vsnprintf libintl_vsnprintf extern int vsnprintf (char *, size_t, const char *, va_list); #endif #endif gnulib's stdio.h is included prior to the inclusion of libintl.h so _GL_STDIO_H is defined, but gnulib detected that it doesn't need to replace [v]snprintf, therefore [v]snprintf isn't defined and both #if's are true and libintl.h replaces [v]snprintf with it's own broken version. I can reproduce the problem in a test program by including said libintl.h. -- Matthias Bolte
https://www.redhat.com/archives/libvir-list/2011-July/msg00015.html
CC-MAIN-2014-15
refinedweb
230
67.04
SIGSETOPS(3V) SIGSETOPS(3V) NAME sigsetops, sigaddset, sigdelset, sigfillset, sigemptyset, sigismember - manipulate signal sets SYNOPSIS #include <<signal.h>> int sigaddset(set, signo) sigset_t *set; int signo; int sigdelset(set, signo) sigset_t *set; int signo; int sigfillset(set) sigset_t *set; int sigemptyset(set) sigset_t *set; int sigismember(set, signo) sigset_t *set int signo; DESCRIPTION The sigsetops primitives manipulate sets of signals. They operate on data objects addressable by the application. They do not operate on any set of signals known to the system, such as the set blocked from delivery to a process or the set pending for a process. sigaddset() and sigdelset() respectively add and delete the individual signal specified by the value of signo from the signal set pointed to by set. sigemptyset() initializes the signal set pointed to by set such that all signals defined in this standard are excluded. sigfillset() initializes the signal set pointed to by set such that all signals defined in this standard are included. Applications shall call either sigemptyset() or sigfillset() at least once for each object of type sigset_t prior to any other use of that object. If such an object is not initialized in this way, but is none- theless supplied as an argument to any of sigaddset(), sigdelset(), sigismember(), sigaction(), sigprocmask(), sigpending(), or sigsus- pend() the results are undefined. sigismember() tests whether the signal specified by the value of signo is a member of the set pointed to by set. RETURN VALUES sigismember() returns: 1 if the specified signal is a member of set. 0 if the specified signal is not a member of set. -1 if an error is detected, and sets errno to indicate the error. The other functions return: 0 on success. -1 on failure and set errno to indicate the error. ERRORS For each of the following conditions, if the condition is detected, sigaddset(), sigdelset(), and sigismember() set errno to: EINVAL signo is an invalid or unsupported signal number. SEE ALSO sigaction(3V), sigpending(2V), sigprocmask(2V) 21 January 1990 SIGSETOPS(3V)
http://modman.unixdev.net/?sektion=3&page=sigemptyset&manpath=SunOS-4.1.3
CC-MAIN-2017-17
refinedweb
336
52.09
On Sat, 13 Mar 2004, Krista Bennett wrote: > > I don't really care too much about plausible deniability. I encrypt my > > harddrive. With that out of the way, records of what I've indexed and how > > would be really useful to me. I don't really care about records of what I've > > inserted since, if I inserted it instead of indexing it, I may actually be > > going for that plausible deniability thingy. > Well, it's certainly something that could be done, and I'll see about > putting something like that in this weekend if I get to it as an option > for anyone who'd want to use it. Let me bump in with a trivial but far-fetched fantasy. The thing that would solve all these problems would be a <drumroll...> content management wizzard! I have personally been too lazy to do much of anything to that end, my apologies, but I have a bit of a plan of how it could look like. The wizzard (lets have these double z's so as not to confuse with windows wizards) would be a GUI app (for example, extension to gnunet-gtk), that would basically maintain a bunch of tree widgets and store them in a $HOME/.wizzard/ directory on disk. Each tree would either represent a namespace or a directory hierarchy. For each tree node, the wizzard would know (perhaps by asking from gnunetd) what is the nodes status (inserted, indexed,lost,priority, and if indexed, is the file still available locally, etc) and allow user to change these, and change descriptions and keywords. Similarly new nodes, subtrees etc could be added/removed to/from the trees and on clicking 'commit' the wizzard would encode and send the required parts of the updated structure to gnunetd (i.e., fresh root blocks and the updated dir tree, not necessarily the actual files). Of course outside a regularly updating namespace, changing the descriptions and keywords and/or file content would cause keyword pollution, but thats something we can't avoid in GNUnet. The only hope currently is that people would start using namespaces and providing cross-links to other namespaces with related interests. A thing like content insertion wizzard might help the transition a lot. If the wizzard were augmented with e.g. a feature that would allow the user to maintain a 'friend list' in the namespace (for example as a regular, standardized file entry in the root-level directory, that would contain pointers to other namespaces), this would work towards establishing a link structure. gnunet-gtk could then try to fetch these lists automatically or on click, allowing surfing. I mean, perhaps in future, users are interested in locating very specific content by keyword search. But in the current phase I rather suspect that many would find it acceptable if they could find something that matches the overall 'genre' and be able to download the results. Building a informal trust hierarchy between namespaces is currently - to the best of my knowledge - the best answer to content availability problem. By this I simple mean that if person A finds a reliable namespace B to his liking, and B points to some other namespaces, it could be used as indication that the other namespaces would have some reliability as well. But I'd be quite happy with a realization of some less grand scheme first. We don't necessarily need to have the whole wizzardly corpulence to start with. ;) ;) Igor
http://lists.gnu.org/archive/html/gnunet-developers/2004-03/msg00005.html
CC-MAIN-2017-30
refinedweb
580
59.03
Format class for a volume made up of a list of images. More... #include <vil3d_slice_list.h> Format class for a volume made up of a list of images. The filename format can be a list of ';' delimited filenames. It can also be single filename where '#' represents a numeric character. A set of image files with contiguous numbering will be loaded, starting with the lowest number. The first 2D image to be loaded is the k=0 slice in the image, etc. Definition at line 23 of file vil3d_slice_list.h. Definition at line 18 of file vil3d_slice_list.cxx. Definition at line 20 of file vil3d_slice_list.cxx. Add a format reader to current list of those available. This function will take ownership of the passed object, and will delete it when the program dies. Definition at line 72 of file vil3d_file_format.cxx. Access to available format readers supplied by add_format. Definition at line 84 of file vil3d_file_format.cxx. Create an image_resource from an existing file. Implements vil3d_file_format. Definition at line 91 of file vil3d_slice_list.cxx. Make a "generic_image" on which put_section may be applied. Not implemented - Make a "generic_image" on which put_section may be applied. The file may be opened immediately for writing so that a header can be written. The file may be opened immediately for writing so that a header can be written. The width/height etc are explicitly specified, so that file_format implementors know what they need to do... Implements vil3d_file_format. Definition at line 166 of file vil3d_slice_list.cxx. Number of formats available (number added by add_format(). Definition at line 78 of file vil3d_file_format.cxx. default filename tag for this image. Implements vil3d_file_format. Definition at line 41 of file vil3d_slice_list.h.
http://public.kitware.com/vxl/doc/release/contrib/mul/vil3d/html/classvil3d__slice__list__format.html
crawl-003
refinedweb
282
60.92
Details Description According to j2se 1.4.2 specification for Charset.isSupported(String charsetName) the method must throw IllegalCharsetNameException "if the given charset name is illegal ". "Legal charset name must begin with either a letter or a digit. The test listed below shows that there is no the exception if to insert "-" or "_" symbols before standard sharset name, for example "-UTF-8" or "_US-ASCII". Moreover the method returns "true" in this case. BEA also does not throw the exception but returns "false". Code to reproduce: import java.nio.charset.*; public class test2 { public static void main (String[] args) { // string starts neither a letter nor a digit boolean sup=false; try catch (IllegalCharsetNameException e){ System.out.println("***OK. Expected IllegalCharsetNameException " + e); } } }) ***BAD. should be exception; sup=false ***BAD. should be exception; sup=false C:\tmp>C:\harmony\trunk\deploy\jre\bin\java -showversion test2 (c) Copyright 1991, 2005 The Apache Software Foundation or its licensors, as applicable. ***BAD. should be exception; sup=true ***BAD. should be exception; sup=true Suggested junit test case: ------------------------ CharserTest.java ------------------------------------------------- import java.nio.charset.*; import junit.framework.*; public class CharsetTest extends TestCase { public static void main(String[] args) public void test_isSupported() { boolean sup=false; // string starts neither a letter nor a digit try catch (IllegalCharsetNameException e){ //expected } // string starts neither a letter nor a digit try{ sup=Charset.isSupported("_US-ASCII"); fail("***BAD. should be exception IllegalCharsetNameException"); } catch (IllegalCharsetNameException e) { //expected } } } Activity - All - Work Log - History - Activity - Transitions The test looks invalid to me. You shoud only expect an java.nio.charset.IllegalCharsetNameException if the name itself contains disallowed characters, and both underscore and dash are permitted. The code Charset.isSupported("-UTF-8") should return false, not throw an exception. Yes, the test was wrong. See attached correct unit test. I've double checked Harmony Compatibility Guidelines and change my mind (and eat my words and attached test ). My test complies with the Java specification "Legal charset name must begin with either a letter or a digit". RI shows wrong behavior. What's the status of this issue? Is there anything that needs to or can be applied to the source (the test case) or is this invalid and can be closed? Nathan, This bug is very close with Harmony issue 311. The behaviour shared by Harmony and the RI does not comply with the specification. Would it be better to close this bug in corresponding way and to file a bug against Sun? I'm going to resolve this as 'won't fix' for the moment. Feel free to open a bug with Sun and we can revisit this later. Please try my patch according to the spec of Java 5.0
https://issues.apache.org/jira/browse/HARMONY-68
CC-MAIN-2015-40
refinedweb
449
59.4
Wondering what the difference is between the following: Case 1: Base Class public void DoIt(); public new void DoIt(); public virtual void DoIt(); public override void DoIt();. public class Base { public virtual void DoIt() { } } public class Derived : Base { public override void DoIt() { } } Base b = new Derived(); b.DoIt(); // Calls Derived.DoIt will call Derived.DoIt if that overrides Base.DoIt. The new modifier instructs the compiler to use your child class implementation instead of the parent class implementation. Any code that is not referencing your class but the parent class will use the parent class implementation. public class Base { public virtual void DoIt() { } } public class Derived : Base { public new void DoIt() { } } Base b = new Derived(); Derived d = new Derived(); b.DoIt(); // Calls Base.DoIt d.DoIt(); // Calls Derived.DoIt Will first call Base.DoIt, then Derived.DoIt. They're effectively two entirely separate methods which happen to have the same name, rather than the derived method overriding the base method. Source: Microsoft blog
https://codedump.io/share/zzbWqQNmDAA1/1/difference-between-new-and-override
CC-MAIN-2017-51
refinedweb
163
60.41
Lately, I've been working on building one of the app challenges on devchallenges.io. I decided to use Next.js with GraphQL as my stack. I was a little worried about how I would implement secure HTTP-only authentication but it turned out to be super simple! Let me show you how. Starting off we'll use a basic graphql API route adapted from the next.js example import { ApolloServer, gql } from 'apollo-server-micro' const typeDefs = gql` type Query { me: User } type Mutation { signup(username: String!, password: String!): User } type User { username: String! } ` const resolvers = { Query: { me(_parent, _args, context) { // what do we do here? }, }, Mutation: { signup(_parent, {username, password}, context) { // ?? }, } } const apolloServer = new ApolloServer({ typeDefs, resolvers }) export const config = { api: { bodyParser: false, }, } export default apolloServer.createHandler({ path: '/api/graphql' }) Here's where the fun begins. We'll import jsonwebtoken and cookies (make sure you add them to your dependencies!): import jwt from "jsonwebtoken"; import Cookies from "cookies"; Then we'll add a context within the apollo server where we'll create a cookie jar to set and get cookies within our resolves and parse our JWT token (if we have it). const verifyToken = (token) => { if (!token) return null; try { return jwt.verify(token, process.env.SECRET!); } catch { return null; } }; const apolloServer = new ApolloServer({ typeDefs, resolvers, context: ({ req, res }) => { const cookies = new Cookies(req, res); const token = cookies.get("auth-token"); const user = verifyToken(token); return { cookies, user, }; }, }); Now in our resolvers, we can set the cookie when a user signs up (and signs in, but I'll let you figure that out): const resolvers = { // ... Mutation: { async signup(_parent, {username, password}, context) { let hash = await bcrypt.hash(password, 10); // bring your own db logic let user = await db.createUser({username, password: hash}) let token = jwt.sign({ id: user.id }, process.env.SECRET!); context.cookies.set("auth-token", token, { httpOnly: true, sameSite: "lax", // here we put 6 hours, but you can put whatever you want (the shorter the safer, but also more annoying) maxAge: 6 * 60 * 60, secure: process.env.NODE_ENV === "production", }); return user; }, } } Now, whenever a request is made to check our auth status, it's easy! const resolvers = { Query: { me(_parent, _args, context) { // bring your own db logic context.user?.id ? db.findUser(context.user.id) : null }, }, } That should be enough to get you started 😄 Discussion (1) Thanks for the article I'm looking to start working on the dev challenges projects can please show us on how you handled this on the client with apollo client 3?
https://dev.to/cvr/graphql-http-only-jwt-authentication-with-next-js-3083
CC-MAIN-2022-05
refinedweb
421
57.06
I am using selenium and chrome-driver to scrap data from some pages and then run some additional tasks with that information (for example, type some comments on some pages) My program has a button. Every time it’s pressed it calls the thread_(self) (bellow), starting a new thread. The target function self.main has the code to run all the selenium work on a chrome-driver. def thread_(self): th = threading.Thread(target=self.main) th.start() My problem is that after the user press the first time. This th thread will open browser A and do some stuff. While browser A is doing some stuff, the user will press the button again and open browser B that runs the same self.main. I want each browser opened to run simultaneously. The problem I faced is that when I run that thread function, the first browser stops and the second browser is opened. I know my code can create threads infinitely. And I know that this will affect the pc performance but I am ok with that. I want to speed up the work done by self.main! Answer Threading for selenium speed up Consider the following functions to exemplify how threads with selenium give some speed-up compared to a single driver approach. The code bellow scraps the html title from a page opened by selenium using BeautifulSoup. The list of pages is links. import time from bs4 import BeautifulSoup from selenium import webdriver import threading def create_driver(): """returns a new chrome webdriver""" chromeOptions = webdriver.ChromeOptions() chromeOptions.add_argument("--headless") # make it not visible, just comment if you like seeing opened browsers return webdriver.Chrome(options=chromeOptions) def get_title(url, webdriver=None): """get the url html title using BeautifulSoup if driver is None uses a new chrome-driver and quit() after otherwise uses the driver provided and don't quit() after""" def print_title(driver): driver.get(url) soup = BeautifulSoup(driver.page_source,"lxml") item = soup.find('title') print(item.string.strip()) if webdriver: print_title(webdriver) else: webdriver = create_driver() print_title(webdriver) webdriver.quit() links = ["", "", "", "", "", "", "", "", ""] Calling now get_tile on the links above. Sequential approach A single chrome driver and passing all links sequentially. Takes 22.3 s my machine (note:windows). start_time = time.time() driver = create_driver() for link in links: # could be 'like' clicks get_title(link, driver) driver.quit() print("sequential took ", (time.time() - start_time), " seconds") Multiple threads approach Using a thread for each link. Results in 10.5 s > 2x faster. start_time = time.time() threads = [] for link in links: # each thread could be like a new 'click' th = threading.Thread(target=get_title, args=(link,)) th.start() # could `time.sleep` between 'clicks' to see whats'up without headless option threads.append(th) for th in threads: th.join() # Main thread wait for threads finish print("multiple threads took ", (time.time() - start_time), " seconds") This here and this better are some other working examples. The second uses a fixed number of threads on a ThreadPool. And suggests that storing the chrome-driver instance initialized on each thread is faster than creating-starting it every time. Still I’m not sure this is the optimal approach for selenium to have considerable speed-ups. Since threading on no IO bound code will end-up executed sequentially (one thread after another). Due the Python GIL (Global Interpreter Lock) a Python process cannot run threads in parallel (utilize multiple cpu-cores). Processes for selenium speed up To try to overcome the Python GIL limitation using the package multiprocessing and Processes class I wrote the following code and I ran multiple tests. I even added random page hyperlink clicks on the get_title function above. Additional code is here. start_time = time.time() processes = [] for link in links: # each thread a new 'click' ps = multiprocessing.Process(target=get_title, args=(link,)) ps.start() # could sleep 1 between 'clicks' with `time.sleep(1)`` processes.append(ps) for ps in processes: ps.join() # Main wait for processes finish return (time.time() - start_time) Contrary of what I would expect Python multiprocessing.Process based parallelism for selenium in average was around 8% slower than threading.Thread. But obviously booth were in average more than twice faster than the sequential approach. Apparently selenium chrome-driver calls somewhat releases the Python GIL indeed making it parallel in threads. Threading a good start for selenium speed up ** This is not a definitive answer as my tests were only a tiny example. Also I’m using Windows and multiprocessing have many limitations in this case. Each new Process is not a fork like in Linux meaning, among other downsides, a lot of memory is wasted. Taking all that in account: It seams that depending on the use case threads maybe as good or better than trying the heavier approach of process (specially for Windows users).
https://www.tutorialguruji.com/python/how-to-run-selenium-chromedriver-in-multiple-threads/
CC-MAIN-2021-43
refinedweb
796
58.99
Attributes¶ name¶ This is a string, with a minimun thid. This is a recommended, but not mandatory an user/channel assigned. For package recipes working in user space, there is no current user/channel. The properties self.user and self.channel will then look for environment variables CONAN_USERNAME and CONAN_CHANNEL respectively. If they are not defined, an error will be raised.") options, default]} There is an special value ANY to allow any value for a given option. The range of values for such an option will not be checked, and any value (as string) will be accepted: class MyPkg(ConanFile): ... options = {"shared": [True, False], "commit": "ANY"} When a package is installed, it will need all its options be defined a value. Those values can be defined in command line, profiles, but they can also (and they will be typically) defined in conan package recipes: class MyPkg(ConanFile): ... options = {"shared": [True, False], "fPIC": [True, False]} default_options = "shared=False", "fPIC=False" The options will typically affect the build() of the package in some way, for example: class MyPkg(ConanFile): ... options = {"shared": [True, False]} default_options = "shared=False" def build(self): shared = "-DBUILD_SHARED_LIBS=ON" if self.options.shared else "" cmake = CMake(self) self.run("cmake . %s %s" % (cmake.command_line, shared)) self.run("cmake --build . %s" % cmake.build_config) Note that you have to consider the option properly in your build scripts. In this case, we are using the CMake way. So if you had explicit STATIC linkage in the CMakeLists.txt file, you have to remove it. If you are using VS, you also need to change your code to correctly import/export symbols for the dll. This is only an example. Actually, the CMake helper already automates this, so it is enough to do: def build(self): cmake = CMake(self) # internally it will check self.options.shared self.run("cmake . %s" % cmake.command_line) # or cmake.configure() self.run("cmake --build . %s" % cmake.build_config) # or cmake.build() You can also specify default option values of the required dependencies: class OtherPkg(ConanFile): requires = "Pkg/0.1@user/channel" default_options = "Pkg:pkg_option=value" You can also specify default option values of the conditional required dependencies: class OtherPkg(ConanFile): default_options = "Pkg:pkg_option=value" def requirements(self): if self.settings.os != "Windows": self.requires("Pkg/0.1@user/channel") This will always work, on Windows the default_options for the Pkg/0.1@user/channel will be ignored, they will only be used on every other os. If you need to dynamically set some dependency options, you could do: class OtherPkg(ConanFile): requires = "Pkg/0.1@user/channel" def configure(self): self.options["Pkg"].pkg_option = "value" Option values can be given in command line, and they will have priority over the default values in the recipe: $ conan install -o Pkg:shared=True -o OtherPkg:option=value You can also defined them in consumer conanfile.txt, as described in this section [requires] Poco/1.9.0@pocoproject/stable [options] Poco:shared=True OpenSSL:shared=True And finally, you can define options in profiles too, with the same syntax: # file "myprofile" # use it as $ conan install -pr=myprofile [settings] setting=value [options] MyLib:shared=True You can inspect available package options, reading the package recipe, which is conveniently done with: $ conan get Pkg/0.1@user/channel requires¶ Specify package dependencies as a list")).A/0.2@user/testing", "ToolB/0.2@user/testing" Read more: Build requiremens." Check the full generators list. build_policy¶): build_policy = "always" # "missing" short_paths¶ If one of the packages you are creating hits the limit of 260 chars path length in Windows, add short_paths=True in your conanfile.py: from conans import ConanFile class ConanFileTest(ConanFile): ... short_paths = True This will automatically “link” the source and build directories of the package to the drive root, something like C:/.conan/tmpdir. All the folder layout in the conan cache is maintained. This attribute will not have any effect in other OS, it will be discarded. From Windows 10 (ver. 10.0.14393), it is possible to opt-in disabling the path limits. Check this link for more info. Latest python installers might offer to enable this while installing python. With this limit removed, the short_paths functionality is totally unnecessary. Please note that this only works with Python 3.6 and newer.ed This attribute is only defined inside package_info() method, being None elsewhere, so please use it only inside this method. The self.cpp_info object can be filled with the needed information for the consumers of the current package: See also Read package_info() method docs for more info. deps_cpp_info¶ Contains the cpp_info object of the requirements of the recipe. In addition of the above fields, there are also properties to obtain the absolute paths:@conan/stable", "OpenSSL/1.0.2l@conan/stable" ... accesed Used to clone/checkout a repository. It is a dictionary with the following possible values: from conans import ConanFile, CMake, tools class HelloConan(ConanFile): scm = { "type": "git", "subfolder": "hello", "url": "", "revision": "static_shared" } ... - type (Required): Currently only gitsupported. Others like svnwill be added eventually. - url (Required): URL of the remote or autoto capture the remote from the local directory. - revision (Required): - When type is git, it can be a string with a branch name, a commit or a tag. - subfolder (Optional, Defaulted to .): A subfolder where the repository will be cloned. - username (Optional, Defauted to None): When present, it will be used as the login to authenticate with the remote. - password (Optional, Defaut To know more about the usage of scm check:
https://docs.conan.io/en/1.5/reference/conanfile/attributes.html
CC-MAIN-2022-27
refinedweb
914
50.23
I tried this problem. There are boxes infinitely in a straight line. Each box is labeled from left side …,-2,-1,0,1,2,… to the right side. Now R red marbles are in the -100th box. In the same way, G green mables are in the 0th box and B blue mables are in the 100th box. There no other marbles in all boxes. All boxes should have one marble at most. Repeat below process and make the number of marbles of each each at most one. Calculate minimum required steps. I wrote below code. import java.util.ArrayList; import java.util.List; import java.util.Scanner; /** * Created by sasakiumi on 3/18/14. */ public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int r = sc.nextInt(); int g = sc.nextInt(); int b = sc.nextInt(); int max = Math.max(Math.max(r, g), b); List<Integer> steps = new ArrayList<Integer>(); steps.add(0); for (int i = 1; i <= max; i++) { Integer pre = steps.get(i - 1); steps.add(pre + (i / 2)); } Integer ans = steps.get(r) + steps.get(g) + steps.get(b); System.out.println(ans); } } OK. I understand this code does not put the case of 100 marbles that is same color into consideration. If there are 200 red marbles, this code does not work properly. But I have not found effective way to solve all cases. I will update this problem later. If you have any good idea, please let me know. Thank you.Written on March 18th, 2014 by Kai Sasaki
https://www.lewuathe.com/atcoder/memolization/marble-problem.html
CC-MAIN-2018-26
refinedweb
261
80.38
Re: Problem finding ntoskrnl.exe on boot. - From: "Robbie Hatley" <bogus.address@xxxxxxxxxxx> - Date: Wed, 21 Dec 2005 00:00:05 GMT "John John" <audetweld@xxxxxxxxxxx> wrote: > Question: When the pc boots on what you call N drive is it (the so > called "N" drive) identified as N: by Windows or is it identified as C:? That's a bit of a mis-quote. If you carefully read what I wrote, you will see that I said "drive N:", not "the so-called N drive". When I say "drive N:", I mean "drive N:". To be complete, and to avoid all further confusion of this nature: I refer to drive A: as "drive A:". I refer to drive B: as "drive B:". I refer to drive C: as "drive C:". I refer to drive D: as "drive D:". I refer to drive E: as "drive E:". I refer to drive F: as "drive F:". I refer to drive G: as "drive G:". I refer to drive H: as "drive H:". I refer to drive I: as "drive I:". I refer to drive J: as "drive J:". I refer to drive K: as "drive K:". I refer to drive L: as "drive L:". I refer to drive M: as "drive M:". I refer to drive N: as "drive N:". I refer to drive O: as "drive O:". I refer to drive P: as "drive P:". I refer to drive Q: as "drive Q:". I refer to drive R: as "drive R:". I refer to drive S: as "drive S:". I refer to drive T: as "drive T:". I refer to drive U: as "drive U:". I refer to drive V: as "drive V:". I refer to drive W: as "drive W:". I refer to drive X: as "drive X:". I refer to drive Y: as "drive Y:". I refer to drive Z: as "drive Z:". Or if you want it in C++: #include <iostream> #include <string> int main(void) { for (int i=0; i<26; ++i) { std::cout << std::string("I refer to drive ") + char(65+i) + std::string(": as \"drive ") + char(65+i) + std::string(":\".") << std::endl; } return 0; } I hope that clarifies things. But my original problems remain. To recap: =========== BEGIN RECAP ================================= I've got a messy problem. I was attempting to expand the hard-disk space on my mom's computer by adding a second hard disk. My sequence of actions was as follow: 1. I copied the bootable Windows 2000 partition (C:) from the old 80GB hard disk to the new 160GB hard disk, using Symantec Partition Magic 8. 2. I changed the drive letter of C: to N: 3. I gave the new partition drive letter C: 4. I swapped disks, so that the 160GB disk (containing the new partition, now labeled C:) is the first hard disk. 5. I made C: the active partition. System should now boot from C:, right? Wrong. If I leave both hard disks attached to the IDE cable, I get a menu allowing me to choose between "Windows 2000" and "Windows 2000 #1". If I choose "Windows 2000", the system boots from drive N: on the second hard disk! If I choose "Windows 2000 #1", I get "system cannot boot due to a hardware configuration error". If I remove the second hard disk (with bootable partition N: on it) from the IDE cable, I get "Cannot find ntoskrnl.exe. This file is missing or corrupt." However, the file is NOT missing or corrupt. If I boot from drive N: and do an FC between N:\WINNT\system32\ntoskrnl.exe and C:\WINNT\system32\ntoskrnl.exe , I get "no differences encountered". So the kernel is fine... but for some reason it's inaccessible on boot. I suspect that the registry on drive C: is corrupted somehow. Specifically, I very much suspect that Partition Magic's "Drive Mapper" program set the drive letters in the drive C: registry to something bogus. The bootloader is probably now looking for K:\WINNT\system32\ntoskrnl.exe or some damn such thing, and of course not finding it. So the question is, is there any way to edit the registry on drive C: ? Running regedit.exe won't help, because no matter which copy of regedit I run (the one on C: or the one on N:) it always edits the registry on drive N:. How can I edit a registry other than the currently-booted one? (Yes, the possibility has occurred to me that the problem lies elsewhere altogether, such as maybe the motherboard does not fully support 160GB HDs; many older MBs don't. However, I still need to know what is in the C: registry, and I don't know how to get at it.) ======================== END RECAP ========================= Since I wrote that, I've tried some other things, but still haven't got the 160GB disk to boot. In what follows, to avoid confusion, I define: "Disk80" = original 80GB hard disk, (second physical hard disk) (primary slave) (contains bootable drive N:) "Disk160" = new 160GB hard disk (first physical hard disk) (primary master) (contains should-be-bootable drive C:) 1. I shrank the extended partition on Disk160 so that the partitioned portion of the disk is completely under 120GB, which seems to be the limit the BIOS can understand. (Windows 2000, on the other hand, can be taught to understand much larger HDs, if you run the "make-windows-understand-large-LBA" utility from Samsung (the manufacturer of both of the hard disks I'm working with).) 2. I changed ALL "N:" references to "C:" in the registry on drive N: (on disk160 (second physical hard disk)). 3. I erased the drive C: partition (on Disk80 (first physical hard disk)). 4. I copied the N: partition from Disk 80 to Disk160. 5. I used Partition Magic to assign drive letter C: to the copy of N: on Disk80. 5. I removed Disk80 from the IDE cable, leaving Disk160 as the only HD in the system, first physical hard disk, primary master, jumpered accordingly. 6. I setup PowerQuest BootMagic so that the MBR launches BootMagic, which resides on 2nd primary partition (MS-DOS 6.22), and can boot any of 3 OSs: Linux (pri. part. 1), DOS (pri. part. 2), or Windows 2000 (pri. part. 3). Results: Partition 1 (Linux): OS not yet installed (though empty partitions of appropriate sizes, locations, and file-system types have been created for it). Partition 2 (MS-DOS 6.22): Boots fine, runs fine. Partition 3 (Windows 2000 Professional): "Cannot boot Windows due to a physical hard disk mis-configuration error". (Nature of error not specified.) This is not a 2GB or 1024cyl issue. (Partition 3 begins waaaaay below 2GB, and ends before reaching cylinder 1024. Also, this same partitioning and booting scheme works fine on Disk80.) I can see only three logical explanations for this situation: 1. The drive C: registry contains wrong disk geometry information? (It might think it's still on Disk80, from whence it was cloned). (Do windows registries actually deal with such low-level information, though?) 2. Maybe Windows 2000 is simply not capable of booting from a 160GB hard disk? (Is anyone here currently running a Windows 2000 system which boots from an HD larger than 120GB?) 3. Perhaps the Windows installation on Disk160 can't boot until I run the Samsung "teach windows to recognize large LBA" program. I can't run that program for drive C: until after I boot drive C:. But I can't boot drive C: until after I run that program. Catch 22 situation? One obvious work around is to repartition Disk80 to do the work I had intended Disk160 to do, then just use Disk160 as a data disk (entire disk taken-up by one huge extended partition; no primary partitions). That should work, seeing as how Windows recognizes all logical drives on both disks, ONCE IT'S BOOTED. It's only getting it booted that's the hard part. However, I don't want to do that If I don't have to, because it would involve a lot more data backups, repartitioning, and data restores. Hours of work. A second, even more time-wastey option is to try to overwrite the Windows installation on C: by running my Windows 2000 CD. This would likely require WEEKS of work, thought, because it would force me to re-do all OS customizations and re-install all programs. Also, thousands of spam filters (OE "mail rules") would be permanently lost, because Windows keeps those in it's registry, rather than as a user-editable plain-text (or XML) killfile, as it should. Obviously, this option is "LAST RESORT". So... does anyone here have any clues as to why Disk160 won't boot? Much thanks to anyone who can help me solve this mystery! -- Cheers, Robbie Hatley Tustin, CA, USA web: home dot pacbell dot net slant earnur slant . - Follow-Ups: - Re: Problem finding ntoskrnl.exe on boot. - From: John John - Re: Problem finding ntoskrnl.exe on boot. (corrections) - From: Robbie Hatley - References: - Problem finding ntoskrnl.exe on boot. - From: Robbie Hatley - Re: Problem finding ntoskrnl.exe on boot. - From: John John - Prev by Date: Re: do i need to convert old fat32 file data to ntfs upgrading to - Next by Date: Re: Problem finding ntoskrnl.exe on boot. (corrections) - Previous by thread: Re: Problem finding ntoskrnl.exe on boot. - Next by thread: Re: Problem finding ntoskrnl.exe on boot. (corrections) - Index(es):
http://www.tech-archive.net/Archive/Win2000/microsoft.public.win2000.general/2005-12/msg00774.html
crawl-002
refinedweb
1,584
75.91
Need to take a One Drive file and upload it to a FTP Hi. I have this repetitive task at work, download data from SAP and upload it to a ftp server. I have managed to script the steps making semiautomatic downloads trough a VBA script, the files are stored in a OneDrive folder, after that, I access that folder and run a Pythonista script to upload the files to the ftp server. Could somebody give me a hand to do it on a single step? Thanks. @Tito, do I understand correctly that you can access the OneDrive folder and file, but do not know what path to use in the Pythonista script that uploads it to the ftp server? If that is the case, probably simplest is to copy your script to the same folder, open it from there and run it. Then it has access to your file without any path. @mikael When I open external folder in Pythonista, OneDrive stays gray while it isn't in the Files app. @cvp, I think it is the same for me. But for this, it is enough to open the .py file, not a folder. And the file can be moved to OneDrive by sharing. @mikael so, would it be possible to make a script that select two files and upload them to the ftp? I have would take the data to the folder and then exec the script and upload the files in the same execution? Following the logic I only had to say the file name because the script would be in the same folder. I think this is it... fil = appex.get_file_path() if fil == None: print('no file passed') return I have to find the code that says the file names, now it shows the document picker but I want two fixed files. Thanks. @Tito I think that even a script located in your OneDrive folder would not access to other files while OneDrive is not open first as external folder IN Pythonista I've tried with import os print(os.listdir()) But that gives a permission error. And giving the link obtained trough files? shareddocuments:///private/var/mobile/Containers/Shared/AppGroup/... And giving the link obtained trough files? Keep from /private.. and try os.listdir('/private...') Now I’m open OneDrive app, go to the folder, I select a file, run Pythonista Script and repeat with the other file. I can use iOS to access the route give it to Pythonista and upload a file. It has to be a way for doing this with a fixed route. @Tito when you share an OneDrive file to send it to Pythonista, iOS creates a temporary copy and its path is not always the same @cvp I’ve found a post about the compatibility between OneDrive and Shortcuts but seems to be only for scan documents and related stuff nothing related to file routes. @Tito I had tried also a shortcut opening the url, without success. Another solution could be perhaps web scraping on the OneDrive site...but surely not easy. @Tito I think I have found a solution. You have to share (in OneDrive app or web page) your folder once and copy the generated link. Then, try this little script, where you have to replace my url with yours import ui url = '' w = ui.WebView() w.load_url(url) w.present() You will get a web page where we will still have to find a way to press the download button to get a zip with all files in the folder. @Tito Finally, easier that I thought. For each OneDrive file that you need to upload, in the OneDrive app, once, you share it, and 'copy the link'. In the little script here under, you store in the files dict, the file name name and it's pasted link. Even if the OneDrive file is modified, its link stays the same, at least during my tests. The script downloads the OneDrive file and copies it locally. The FTP unload part is another process, if you want help for it, ask me. Based on Generate OneDrive Direct-Download Link with C# or Python import requests import base64(): files = {'a.py':'', 'aa.txt':''} for nam_file in files: url_file = create_onedrive_directdownload(files[nam_file]) r = requests.get(url_file) with open(nam_file, mode='wb') as fil: fil.write(r.content) if __name__ == '__main__': main() import base64 import os import paramiko import requests import sys #(): path = sys.argv[0] i = path.rfind('/') path = path[:i+1] ip = 'my ip' user = 'user' pwd = 'password' try: sftp_port = 22 transport = paramiko.Transport((ip, sftp_port)) transport.connect(username=user, password=pwd) sftp = paramiko.SFTPClient.from_transport(transport) files = {'a.py':'', 'aa.txt':''} for nam_file in files: url_file = create_onedrive_directdownload(files[nam_file]) r = requests.get(url_file) with open(nam_file, mode='wb') as fil: fil.write(r.content) s(path + nam_file, nam_file) os.remove(nam_file) s transport.close() except Exception as e: print(str(e)) if __name__ == '__main__': main() You could even find automatically the file name from its link . . . for nam_file in files: r = requests.get(files[nam_file]) c = r.content.decode('utf-8') t = 'property="og:title" content="' i = c.find(t) if i >= 0: # <meta property="og:title" content="a.py"/> j = c.find('"/>',i) print(c[i+len(t):j]) url_file = create_onedrive_directdownload(files[nam_file]) . . .
https://forum.omz-software.com/topic/6791/need-to-take-a-one-drive-file-and-upload-it-to-a-ftp
CC-MAIN-2021-49
refinedweb
886
74.9
A friendly place for programming greenhorns! Big Moose Saloon Search | Java FAQ | Recent Topics Register / Login JavaRanch » Java Forums » Java » Java in General Author Design Question - Refreshing Singletons Annie McCall Greenhorn Joined: Apr 17, 2003 Posts: 21 posted May 18, 2007 12:19:00 0 Hi, The app I'm working on has a singleton class that needs to be refreshed every so often. Does anyone have any design ideas on how I can achieve this? The singleton contains a hashmap which reflect data that hardly gets changed in our database. But, if the data does change, we want to refresh hash map without redeploying app. Maybe a timer(??) not sure how to do this. Any one out there have any ideas... Examples would be great. Thanks. Annie McCall<br />SCJP 1.4<br />SCWCD Paul Clapham Bartender Joined: Oct 14, 2005 Posts: 16479 2 I like... posted May 18, 2007 12:46:00 0 Well, as far as the singleton class itself is concerned, a synchronized method that refreshes its data would take care of that. Either a method you call on the single instance itself, or a static method that just creates a new single instance. Depends on how the data refresh works. But your question seems to have hints of "How do I tell when data changes?" or something like that. Would you like to try expanding on that part of the question? Annie McCall Greenhorn Joined: Apr 17, 2003 Posts: 21 posted May 18, 2007 13:02:00 0 I guess I do not know how to handle the refresh itself. I know the appropriate code on how to refresh(ie., create new instance of singleton or synchronize on hash map and recreate it with new data). I would like to refresh like once a day...or even more often...but I do not know how to do this? I don't think there is a way to detect if the data changed in the db so I am opting on maybe refreshing every...hour, day. Is there a way to put a timer in singleton??? Example code is appreciated. Thanks. [ May 18, 2007: Message edited by: Annie McCall ] Paul Clapham Bartender Joined: Oct 14, 2005 Posts: 16479 2 I like... posted May 18, 2007 15:41:00 0 Something like this: public class Singleton { // When the class is loaded: private static instance = new Singleton(); static { Timer timer = new Timer(); timer.schedule(new TimerTask() { public void run() { synchronized(Singleton.class) { instance = new Singleton(); } } }, 60 * 60 * 1000L /* Once per hour */); } // To get the single instance: public static synchronized getInstance() { return instance; } // To create an instance: private Singleton() { // whatever you have to do: get data from the DB and so on } // Other methods... } That's java.util.Timer if you didn't already find it in the documentation. [ May 18, 2007: Message edited by: Paul Clapham ] Ravish Ahuja Greenhorn Joined: Nov 29, 2004 Posts: 13 posted May 21, 2007 01:04:00 0 We had the same problem in our app, one of the solution is to refresh HashMap periodically, say every day, or every week. But there may be a situation that no update happend for 2 months, so updating everyday doesnt make sense. To overcome this situation we provided a "Refresh Cache" Link to Admin/Infrastructure user who would first update DB and then log in to application and click on "Refresh Cache" in the application. That ways he is in full control of the situation. Stan James (instanceof Sidekick) Ranch Hand Joined: Jan 29, 2003 Posts: 8791 posted May 21, 2007 10:01:00 0 To keep your current Singleton, move whatever code loads up all the state in the Singleton from a constructor to an init() method. Then you can call the init() method any time you like. I'd expect it to create a new HashMap and populate it from scratch. During the brief time it's reloading, the map will be invalid for any clients. You may have to synchronize all access to the map. Can you build your cache to "lazy load" so it knows how to load data that it doesn't have? With this you only have to empty the HashMap and let it reload itself over time. It makes the window of invalid time very short. value = cache get key if value == null get value from the database cache put key, value return value Finally, Singleton may not be needed here. You can get by with all static methods. I made one like this: public class Cache { private static RealCache = null; public static void put( key, value ) { theRealCache.put(key value) } public static Object get( key ) { return theRealCache.get( key ); } public static void setTheRealCache( newCache ) { theRealCache = newCache; } } I called setTheRealCache in startup, avoided Singleton, gave clients the convenience of static methods, and allowed myself to plug in alternative RealCache implementations as needed. For example, one implementation has extra instrumentation, another has a different self cleaning algorithm. The timer is one way to trigger your refresh. There are several algorithms for self-cleaning, like least recently used and time to live, which might help avoid the timer thread. And I always make sure to have a dashboard or admin console so I can clear caches on demand any time. [ May 21, I agree. Here's the link: subject: Design Question - Refreshing Singletons Similar Threads Singleton / Factory decision BlackBerry Clone with SIngleton Caching in an EJB container Refactoring Exercise All times are in JavaRanch time: GMT-6 in summer, GMT-7 in winter JForum | Paul Wheaton
http://www.coderanch.com/t/382709/java/java/Design-Refreshing-Singletons
CC-MAIN-2013-20
refinedweb
926
71.75
Regarding my feature request below, I've hacked together a small piece of code to retrieve the raw python source, and the html result of that source. This code is heavily inspired by the PSP class of psp.py script from mod_python. It works for me, does not support forms and sessions (it is meant to produce html formatted e-mail bodies), does not support Windows (path names there use backslashes), and maybe more limitations. Maybe the developers are interested in adding (something like) this to the psp.py file? get_source produces the python source code, get_html compiles the psp input file to html code. Wouter. from mod_python import _psp import os import sys def get_source(filename): dir, fname = os.path.split(filename) dir += "/" pycode = _psp.parse(fname, dir).splitlines() pycode = [s.rstrip() for s in pycode] for line in pycode: left = line.replace("\t", " "*4) result += left+"\n" return result def get_html(filename, vars={}): code = get_source(filename) lines = code.splitlines() code = 'html = ""\n' for l in lines: l = l.replace("req.write(", "html +=").replace(",0)", "") code += l+"\n" global_scope = globals().copy() global_scope.update(vars) html = "" l = locals() try: exec code in global_scope, l except: et, ev, etb = sys.exc_info() raise et, ev, etb return l["html"] On Thu, 2005-05-19 at 10:58 +0800, Wouter van Marle wrote: > Hi > _______________________________________________ > Mod_python mailing list > Mod_python at modpython.org >
https://modpython.org/pipermail/mod_python/2005-May/018129.html
CC-MAIN-2022-21
refinedweb
229
66.64
RationalWiki:Saloon bar/Archive49 [edit] The Tonight Show Big news, I see about Conan O'Brien quitting The Tonight Show. So big, it's been making the press this side of the pond for the last week or so. What I don't get is what all the fuss is about for a show that gets broadcast at 11.35pm. I can't remember the last time I watched a show that even finished at 11.35 on a weeknight, the closest being True Blood, which finished at 11.15 or thereabouts. If my life depended on it, I couldn't even name a single UK TV show that is on at 11.35! So what gives? Do Americans really watch TV until gone midnight on a "school night?" Or are the tivo-ing it for the next day? Does the average American really watch over 8 hours of TV every day? Bondurant (talk) 11:57, 22 January 2010 (UTC) - I wouldn't know, I haven't watched TV in years. I would assume that non-on-demand TV will become pretty much irrelevant over the next decade or so anyhow, so pretty soon it won't matter. --Kels (talk) 13:54, 22 January 2010 (UTC) - Actually, it is The Tonight Show. And, as most people work a 9AM to 5PM shift (unlike me who starts at 7AM), staying up for the late show isn't terribly out of the realm of possibility. Aboriginal Noise with 4 M's and a silent Q 14:18, 22 January 2010 (UTC) - Even for a 7AM wake up I'm lucky to not be doing something after midnight. Is it one of those few things on US TV that doesn't suck? d hominem 14:47, 22 January 2010 (UTC) - Actually, yes. I was able to see a live taping of the show a couple of years ago (Ben Affleck was the guest, Jay Leno the host) and it was a blast. I watched it regularly on Monday nights when Leno would do his "Headlines" section of the show (strange news clippings). Aboriginal Noise with 4 M's and a silent Q 16:41, 22 January 2010 (UTC) Many Americans trace their conception to Johnny having a slow night. Basically merkin TV runs "prime time" shows from 7 or 8 to 11, these are the sitcoms, cop shows, reality things, whatever - the "original" "entertainment" on offer from the networks. Then at 11 is a half hour news show, local or network. Most grownups with 9-5 jobs can easily still be up for the news/sports highlights/weather forecast. Then comes the tonight show, first hosted by Jack Paar, then decades of Johnny Carson, then quite some time with Leno. It's a variety/chat show, nice light entertainment, easy to fall asleep to. Then NBC moved Leno to a 10-11 time slot (cheaper to do a chat show than a real TV show), and handed the tonight show over to Conan, who, while funny, I think is a bit quirky for that time slot/show. Anyway, I guess his ratings haven't been what they should be, so NBC was gonna hand 11:35 back over to Leno, and push the tonight show back an hour (dumb idea to move a show that has been at that time since TV was steam-powered!), which thoroughly spoiled Conan's gruntle. In the end he gets $40mil (I think) to walk away, and he's not allowed to say anything nasty about his former employer. The whole US world of "late night" television has changed a lot in the last few decades anyway, with at least a half dozen chat/variety shows running between 11:30 - 2 or so. ħuman 01:19, 23 January 2010 (UTC) - It has changed quite a bit. I think FOX is the only network that doesn't have a late night talk show now. Aboriginal Noise with 4 M's and a silent Q 01:23, 23 January 2010 (UTC) [edit] More Merkin TV, for the better I missed most of it, but there was a two-hour benefit for Haiti tonight - helpforhaitinow.org I think - damn, some good music at the end. ABC, NBC, and CBS all ran it (commercial free probably). FOX ignored it. PS, the little I caught was heartbreaking. Music and people who care at their best. I'm still trying to figure out how much I can afford to give without screwing up my cash-strangled life. ħuman 03:49, 23 January 2010 (UTC) - Correction, is the site. ħuman 03:53, 23 January 2010 (UTC) And quit changing the header, you prix! ħuman 06:01, 23 January 2010 (UTC)06:01, 23 January 2010 (UTC) I find the word "merkin" offensive, you weaselly little fuck. I don't mind explicit language. It's the sly smirking under-the-radar stuff that natives of your faggotty little island seem to take such passive-aggressive pride in, that reeks of elitist je ne sais quoi, that I don't think should have any place on a high-visibility page like this. There, does that make any better sense to you? I'll leave the header alone for now, but it basically craps all over the Haitian relief message underneath it. Douche. Sprocket J Cogswell (talk) 06:14, 23 January 2010 (UTC) - Jeepers criminy, M. Sprocket, who do you think invented the phrase "Merkin"? Merkins!!! It's an inside joke back against ourselves for having crappy prnusiashun! Sorry if it offended you relating to the comments under the header. PS, "douche" is Franglais for "to wash". Please wash your mouth out with soap! ħuman 06:22, 23 January 2010 (UTC) Look, if you want to change the header and top level it and call it "please give to Haiti" I'm ok with that. I'm still not sure where the money I gave came from, but as I said, they need it more than I do. ħuman 06:23, 23 January 2010 (UTC) - Wow Cogswill, I wouldn't have expected you to channel JPatt/Jinx with a small-minded, racist, homophobic rant. In case you hadn't noticed we also had the same benefit concert in Limeyland. As for usage of the word "Merkin", it's not something I've ever heard used in the UK and have only come across it on talk pages here. Lily Inspirate me. 13:17, 24 January 2010 (UTC) [edit] Fuck You, Habeas Corpus. I just WIGO:World'ed this story, but I'm still fuming mad about it. A de facto life sentence without a trial, forty-seven times over. Fuck Obama if he approves this. TheoryOfPractice (talk) 22:35, 22 January 2010 (UTC) - I agree, they should not be help indefinately. Military tribunal, sentance and execute. Hamster (talk) 23:22, 22 January 2010 (UTC) - It's shit like that which removes all sympathy I have when they complain about how soldiers are treated if they're captured in Iraq or Afghanistan (obviously this applies on the nationalistic level only). If the US want to try and claim to be the Good Guys, then they're Doing It Wrong. d hominem 23:36, 22 January 2010 (UTC) - once you take a military prisoner, they need to be tried by a military court and executed, imprisoned or released. Released during a conflict is simply returning an enemy soldier to combat status and therefore stupid. Since it seems unlikely there will ever be a peace treaty, since no nation state is involved, prisoner repatriation isnt a viable option even assuming the conflict has an end point. That leaves imprisonment or execution. Imprisonment of significant leaders simply is asking for terrorist acts as blackmail for their release. If the people in custody have commotted acts of war against the USA, or spied for the enemy, then they are valid candidates for an execution order by military tribunal. All perfectly legal and according to the rule books Hamster (talk) 00:26, 23 January 2010 (UTC) - "once you take a military prisoner" they a POW, governed by the Geneva Conventions and the signatories to them. This whole thing is wrong, fuck, send them home. Seriously. ħuman 05:05, 23 January 2010 (UTC) Then maybe the answer is to expand the scope of the Convention, instead of moving back to the time before the Magna Carta. TheoryOfPractice (talk) 05:22, 23 January 2010 (UTC) - Hamster, before I go to bed, I gotta point something out to you. Re-read the article, especially the part where the Americans admit that they don't have enough evidence on many of these prisoners to secure a conviction. And then tell me again how we should try them, sentence them, and execute them. Your little plan falls apart at stage one, given that the trials would produce not guilty verdicts. TheoryOfPractice (talk) 05:54, 23 January 2010 (UTC) - (EC)I agree with TOP. States run by "rule of law" need to agree on how to apply it. Also, in the situation of the Gitmo prisoners, we were the aggressor, not them (necessarily). We invaded their country and took them prisoner. What rules should apply? ħuman 05:56, 23 January 2010 (UTC) - Indeed, the entire thing about using Gitmo as a prison and creating an entirely new term for terrorist ("non-legal combatant", IIRC) was to avoid the Geneva Convention. Now, the thing is (and I certainly don't think this is a false dichotomy) are they military or not. If they're military, then they need a military trial, treated as POWs and treated under the Geneva Convention. If they're not, then they're civilian, and thus need to be trialled as such - not under the Geneva Convention per se, but under the laws and human rights afforded to all other civilian prisoners. There's no other option available if you want to be considered "good guys" - and especially if you want to feel vindicated and justified in executing Saddam Hussein and persecuting former Nazis. What has been happening there over the last decade is a War Crime and there is no other way around it. d hominem 18:18, 23 January 2010 (UTC) - Here's a thought, and I apologize for blowing Godwin's Law up already, but let's imagine something totally stupid for a moment. In Nazi Germany and occupied Poland (and elsewhere) people were imprisoned in camps and eventually killed (executed). Now, that was horrible, of course. And people were prosecuted for it. Now what if we, as the US is doing now, redefine every Jew living in Europe in the 40s as a "non legal potential combatant" or whatever. Magically, we've just invented a definition where the holocaust is justified and legal. Wow. And don't think this is stretching definitions too far, the US is practically using "any muslim living in Iraq or there abouts" as their definition. So why is one wrong and the other acceptable? So, as I said, you trial people as soldiers, you trial people as civilians or you're guilty of war crimes. That's the only options, end of fucking story. d hominem 18:30, 23 January 2010 (UTC) - Yeah, most of the people vacationing at Guantanamo were turned in for a reward by other Afghani's. Foolproof method of getting mostly innocent people that managed to piss off someone. As for the gut instinct of the military that they are "dangerous", well... some people known about that sort of thing. It's not like the DIA is going to admit "Oops we were wrong on most of them". Not while three of four other intelligence agencies are vying for a bigger part of the budget. — Pietrow ☏ 21:14, 23 January 2010 (UTC) - Why the thought experiment? German Jews were systematically disenfranchised from ~1933 onwards. Differing terminology aside, your hypothetical redefinition actually happened. And it's a Triple Godwin with Oak Leaf Clusterfucks to try and draw any parallels with that and what's happening in Iraq and Afghanistan. --Robledo (talk) 22:35, 23 January 2010 (UTC) When democracy and freedom of speech are threatened, they must be moved to safety. And when they are not present, you can do all kinds of things. --Swedmann (talk) 01:36, 25 January 2010 (UTC) [edit] update I'm pretty sure I have flu -- =w= 23:58, 22 January 2010 (UTC) - Sorry to hear that. We'll try to keep up the usefulness until you recover. Be sure to drink plenty of hot tea and eat only what you can stomach. Aboriginal Noise with 4 M's and a silent Q 00:00, 23 January 2010 (UTC) - In which case, I should remind everyone to update their anti-virus software in case it spreads. d hominem 00:07, 23 January 2010 (UTC) - Thanks. I will try not to cough on the screen so I think everyone will be alright. I will try to fight fire with tidying. -- =w= 01:13, 23 January 2010 (UTC) - I'm sorry I didn't say anything useful in the first "Mei hurts" section, but I thought everything was covered. Go to doctor if you can. ħuman 03:41, 23 January 2010 (UTC) - Thank you Human. I can see a doctor on Monday. You don't need to be sympathetic, Mei always has random aches. -- =w= 03:57, 23 January 2010 (UTC) - some hospitals have a clinic , if you have severe pain in the lower side/back try to go sooner. Hamster (talk) 04:42, 23 January 2010 (UTC) [edit] WikiSynergy lives? We can now go back and argue with Tom Butler, magicalician of dead people's voice and pictures! [1] ħuman 06:06, 23 January 2010 (UTC) - WikiSynergy? Really? Hmmmm, how did that happen? The Goonie 1 What's this button do? Uh oh.... 07:27, 23 January 2010 (UTC) [edit] Todo List Question Ok, I'm a little confused, and would like some explanation for how this works. I posted a suggestion today (the website Jew Watch), and every time I've gone back to look at the page it isn't listed. Then, I go to edit, and find it's still in the text, then I hit "submit" (having altered nothing in the text), and when the page comes back up again it's there. Does it need to get approval or something?--Mustex (talk) 06:40, 24 January 2010 (UTC) - Did you try hard refreshing the page at any point? I sometimes have the same issue with changes not appearing when I edit from college, but a hard refresh is all it takes. -Redbacknot Redneck 07:41, 24 January 2010 (UTC) - Did you click the RETURN TO THE MAIN LIST link at the top? That should purge you cache. The first random tech fact also deals with this issue. - π 10:23, 24 January 2010 (UTC) [edit] Dawkins on air On our local radio at 18h00 GMT, you'll be able to hear Satan's Right hand Man talking about his new book. You should be able to listen online here. --PsygremlinZungumza! 10:16, 24 January 2010 (UTC) [edit] Neat! Here's something different for a Sunday - Keseniya Simonova's lovely sand drawing. Apparently she won Ukraine's version of "We got talent" (ours on the other hand was won by a deaf breakdancer, with a human beatbox second). And the UK gets SuBo? --PsygremlinZungumza! 11:36, 24 January 2010 (UTC) - Yeah well our first series' runner up was a guy who played eucalyptus leaves[2]. Miss Simonova certainly is very skilled, why are all the people on our "Got Talent" show usually just a random collection of smacktards who think they can sing? -Redbacknot Redneck 13:19, 24 January 2010 (UTC) - Prolly 'cos Simon Cowell's involved and he wants to spin a quick gazillion bucks of the winner's CD. --PsygremlinSnakk! 13:26, 24 January 2010 (UTC) - We don't get Simon, we get Red who is also despicable, but in an endearing way. We also have Kylie Minogue's sister as a judge for some reason. -Redbacknot Redneck 13:51, 24 January 2010 (UTC) - We also get Ms. "Dannii" Minogue on Cowell's The X-Factor. Not that I what shitwatch it of course. Lily Inspirate me. 14:05, 24 January 2010 (UTC) [edit] Jesus sights Just for interest, WP's got an article on the company that put Bible verse refs on the rifle sights. I have just eaten & stiltontalk 15:15, 24 January 2010 (UTC) - The whole article is about the controversy. Although, now that I think about it more, it's kinda scary that a weapons manufacturing company is headed by a fundamentalist. Tetronian you're clueless 20:07, 24 January 2010 (UTC) - Yeah! Unfortunately it makes me think bad things about the US of A, and I don't suppose I'm alone. I know you're not all like that, but it's the face that's shown to the world. I have just eaten & stiltontalk 20:14, 24 January 2010 (UTC) - I'm not greatly surprised to see Christ's soldiers acting up. When you have a Commander in Chief allegedly recruiting allies for war based on the threat of Gog and Magog then it's hardly surprising that the hardware suppliers would get in on the act. I am baffled though by their use of a verse from the sermon on the mount. How on earth would any sane Christian read Jesus's words and somehow think that they belong on rifle sights? It'd be like watching The Shining and believing it to be the story of a young boy who does funny voices. -- Ask me about your mother 20:48, 24 January 2010 (UTC) - isn't it obvious? Jesus was obviously the most militant military leader ever. He just didn't pick up a gun because G-d hadn't decided to invent them yet. I'm sure if the Jesus character were on earth today, he'd be elated to jump on a battlefield against religious heretics. It's really too bad that there on no Bible verses on how Jesus might deal with people of a different religious opinion than he</sarcasm>. δij 21:01, 24 January 2010 (UTC) - Jesus behaved like a dick in other places, but using the quote they did would be like citing Leviticus as proof of God being a happy go lucky type of deity. -- Ask me about your mother 21:10, 24 January 2010 (UTC) - The most I ever read that Jesus fought with was words. I'm perfectly ok with people being total assholes, provided they don't kill anyone in the process (which is why Bushy-boy and I have some problems). δij 21:12, 24 January 2010 (UTC) - I'm fine with people being arseholes so long as they're the kind of people who'd balance a TV on the edge of the bath. -- Ask me about your mother 22:30, 24 January 2010 (UTC) - didnt Jesus smote the tax collectors at the temple ? Hamster (talk) 22:56, 24 January 2010 (UTC) - Yeah, and he picked a fight with a fig tree. -- Ask me about your mother 23:10, 24 January 2010 (UTC) - All the quotes have to do with light, mostly the 'Light of God', possibly as a mention to the tritium glow that the sight uses to help in low-light conditions. And I can just imagine Jesus 'tossing' the money changers from the temple using a judo arm-throw or rolling leg throw. -- CodyH (talk) 11:38, 25 January 2010 (UTC) (unDent) A few comments: - From the pictures I've seen, the serial numbers are like pretty much every other serial number on anything -- small and unobtrusive. That doesn't mean the company is behaving appropriately, but its not like blatantly proseletyzing. - As a progressive Christian, I find the idea of scriptural references on something designed to aid in the killing of fellow human beings really perverse. While I'd still find it inappropriate, I think a "comfort in times of trouble" reference like the 23rd Psalm would be better. - I also find the "don't the Muslims yell 'Allahu Akbar' as they attack us?" argument perverse. It's "do unto others as you would have them do unto you", folks, not "do unto others as they do unto you". MDB (talk) 12:36, 25 January 2010 (UTC) - I spent 15 months looking at various peoples, places, and armed insurgents through the ACOG. Let me tell you, that is one fucking fantastic sight! You can zero your weapon in six rounds or less without having to get up and check the target because you can see where your round lands as soon as you pull the trigger. The iridium (I think) filament gives you "red-dot" precision without the tell-tale give away of a laser sight, and (even though your depth perception gets all jacked up,) you can bull's-eye targets while using a night vision device. Granted, it's been almost two years now, but I can't for the life of me remember seeing any colons in the serial numbers. Oh well... If it was proselytizing, it was totally lost on my entire squadron, because something like that would have spread like wildfire amongst the Jesus freaks. The Foxhole Atheist (talk) 16:02, 25 January 2010 (UTC) - I use a red-dot sight on my weapon, and i've seen some people issued the ACOG and a few who bought the holo sights from their own pocket. Though i'd rather have a pistol in my line of work I'm not going to knock a sight if it works, even if they've already sent out kits to remove the verses. And so far the only complaint i've heard about the ACOG is from some people who say it isn't good while clearing buildings. -- CodyH (talk) 06:26, 26 January 2010 (UTC) - To each his own, I always say. War doesn't decide who's right, only who's left. To be fair, the ACOG did kind of suck ass for building clearing. Luckily, I was in the Mahmudiyah - Lutufia - Yusufia "Triangle of Death", so most of my work was OPs and IED team kill sites. Big open areas aren't really a scout's friend, I know, but it gives you some time to line up shots if the mortars jacked up the call for fire. For room clearing, I used a SureFire™ tactical flashlight with a pressure switch on the right rail with the beam dialed in as tight as I could get it at night and I used the Recondo method of pointing my left finger along the rail in line with the barrel during the day, since we were rarely ever shooting at ranges exceeding 5 meters inside. The Foxhole Atheist (talk) 06:54, 26 January 2010 (UTC) [edit] Red Hot Chili Peppers... ...aren't conductive to revising for a test, but that's some damn good music. EddyP (talk) 22:28, 24 January 2010 (UTC) - I just finished my end of Semester tests. The same rule follows for the Clash. I'm a white man in Hammersmith Palais... SJ Debaser 22:31, 24 January 2010 (UTC) - Personally, I find Senser really good for my own project work. But I guess it's not quite the same as what you're dealing with. --Kels (talk) 23:01, 24 January 2010 (UTC) - That song half reminds me of this one by Goldie Lookin' Chain, spoof Welsh rap band. This song got me through Semester A, however. SJ Debaser 11:00, 25 January 2010 (UTC) - The Chili Peppers used to be kinda edgy, at least through the mid 90's. That edge has dulled significantly in my eyes. Aboriginal Noise with 4 M's and a silent Q 11:52, 25 January 2010 (UTC) - Josh, what about Your missis is a nutter and Your mother's got a penis though? CrundyTalk nerdy to me 12:06, 25 January 2010 (UTC) - "Last week she ended up on a binge, she got off her tits and showed the bouncers her minge." Top quality. Bands like that are so much better than the fuckin' love/suicide songs you get by crappy emo bands. Arctic Monkeys, Goldie Lookin' Chain, Oasis, and other stuff which related to youth culture in Britain is the best. SJ Debaser 12:16, 25 January 2010 (UTC) - I've always liked the Chillies from at artistic point of view for their rhyming. They have an Ian Dury-esque approach to some songs that I really like for some reason : "Can I smell your gasoline/Can I pet your wolverine" and "Can't stop the spirits when they need you/This life is more than just a read thru" --Worm(t | c) 12:49, 25 January 2010 (UTC) - Soap Bar's always been me and me mates' favourite GLC track. Describes our teenage years pretty much bang on. :) --Robledo (talk) 19:53, 25 January 2010 (UTC) [edit] Movies and the Law Dunno if this has been posted before but it is quite funny, especially the picture captions. CrundyTalk nerdy to me 12:59, 25 January 2010 (UTC) - Holy fuck, I was seriously just reading that... are you a computer virus? -Redbacknot Redneck 13:09, 25 January 2010 (UTC) - Yes, please send me your credit card details to clean me. CrundyTalk nerdy to me 13:12, 25 January 2010 (UTC) - That's quite good. I can also recommend Homicide by David Simon. Even though it's 20 years old, it does a good job of exploding the myths about police work, but also why it's so hard to get a 1st degree murder conviction because juries in the US actually believe the myths, and that every murder case has to be water-tight and without any ambiguity. Bondurant (talk) 13:17, 25 January 2010 (UTC) One of my five favourite books of all time. TheoryOfPractice (talk) 13:20, 25 January 2010 (UTC) [edit] Atheist Goat I thought the community would like this. Have fun ĴάΛäšςǍ₰ no hell below him 14:24, 25 January 2010 (UTC) - It comes from "Objective Ministries". ₩€₳$€£ΘĪÐ Methinks it is a Weasel 19:51, 25 January 2010 (UTC) - The "Creation Science" section there is ascribed to a Dr. Richard Paley. The same one mentioned in the Lenski dialog, perhaps? ListenerXTalkerX 20:19, 25 January 2010 (UTC) [edit] You'd think moot learned from last time... Moot brought back /new/ on 4chan. I was on about an hour in to see how bad it would get, and it's already turned into Stormfront 2.0 again. I give it a week before he closes it again. ENorman (talk) 18:18, 25 January 2010 (UTC) [edit] Only Connect Does anyone watch this on BBC4? A few friends of mine are on tonight - although I'm not going to say which team, but it may be fairly obvious. d hominem 19:21, 25 January 2010 (UTC) - I'm having a mosey on iPlayer. Are yours the Oxford postgrads or the Gay singers? Or is it not up yet? SJ Debaser 19:24, 25 January 2010 (UTC) - Neither as it's the episode that's on now, not last weeks. But there was a scientific method question on it. Although I'm not entirely sure that the "method" is formalised enough to make that sort of question out of it. d hominem 20:50, 25 January 2010 (UTC) [edit] Liberal CBS is at it again Well, CBS is showing itself to be a part of the liberal media again. They wouldn't air ads from moveon.org. They wouldn't air ads from the United Church of Christ. They will, however, air ads from Focus on the Fambly. Gosh darn those liberals! MDB (talk) [edit] A recap of how you have treated me thus far Moved to Forum:This_is_how_you've_treated_me,_MarcusCicero,_so_far.--Tom Moorefiat justitia 05:31, 27 January 2010 (UTC)q [edit] How pointless is ...figure skating. I've been watching it (because my life is a rich, full oyster) for all of 5 minutes now and I'm going crazy. Wow...you can dance...on ice. You want a fucking medal? δij 04:54, 25 January 2010 (UTC) - Well someone is going to get one. - π 05:03, 25 January 2010 (UTC) - Watch "Dancing on Ice" instead. It's awesome to watch celebrities dropping their pro partners and breaking their legs, especially David Seaman who dropped his partner twice and also dropped his stand-in replacement while his partner was injured. CrundyTalk nerdy to me 09:28, 25 January 2010 (UTC) - Typical of today's world, a 5 minute attention span. Where are we headed to, I wonder. Editor at CPmały książe 10:46, 25 January 2010 (UTC) - I agree totally, the way that people today don't... don't... oooh look, shiny objects! -Redbacknot Redneck 11:20, 25 January 2010 (UTC) - My parents told me I had ADHD when I was a kid, but the term hadn't been ksemflknm weflknwelfknwlekfnlwekfnwelfn - Sorry, I got bored of that story part way through. CrundyTalk nerdy to me 11:25, 25 January 2010 (UTC) - "Crundy" (welcome and hello, but abide by our rules or else your account will be blocked), ADHD is so prevalent among atheists that that the insight is clearly self-evident. I looked at your contributions and have noticed numerous insertions of the acronym 'welf' in your insubstantial addition. Your subliminal liberal tricks are more suited to Wikipedia, which is where I suggest you go. And you refuse to accept that getting bored mid-sentence is the direct result of excessive masturbation. Believe what you like, but you have free will to deny logic. Work with the lights on creates more wealth and alleviates more hardship than laziness with the lights off does. Go back to watching Comedy Central with the other public schoolers.--Andy Schlafly 11:31, 25 January 2010 (UTC) - Let's see you dance on ice then. Vulpius (talk) 11:26, 25 January 2010 (UTC) - Watch this and tell me they didn't deserve a medal. Even 25 years on, it still amazes me. Bondurant (talk) 12:00, 25 January 2010 (UTC) - @Vulp, I can't, so I won't pretend to. @Bon, yeah, still looks awesome. CrundyTalk nerdy to me 12:04, 25 January 2010 (UTC) - Well, Torvill & Dean were 'Ice Dancing' as opposed to "Figure Skating", a different competition. They had been consistently raising the bar in international competition prior to these Olympics. The most notable aspects of this performance were Torvills costume (higher cut pants with a longer skirt than normal) and the steady, slow tempo. Competition conditions specified something like "no more than 3 tempo changes" but T&D had no tempo changes. It was ground breaking stuff. And, I agree, it still looks awesome. I'd rather watch Ice skating in any form than synchronised swimming! RagTopGone sailing 12:34, 25 January 2010 (UTC) - Watch some of the properly impressive showdance lifts. You'll be wondering how they hell they haven't died horrible deaths already. d hominem 14:46, 25 January 2010 (UTC) - and all done on slippery ice , with razor sharp blades on the feet. You can wait for falls with broken limbs, consussions, amputations, mutilations, spurting arterial blood. All the excitement of auto racing with girls in short skirts going mostly backwards with their butts sticking out. Hamster (talk) 14:57, 25 January 2010 (UTC) - That reminds me of the Why Men Love Ballet ad. Lily Inspirate me. 15:26, 25 January 2010 (UTC) How pointless is any hobby or sport? I have just eaten & stiltontalk 15:44, 25 January 2010 (UTC) - It atracks teh laydeez. — Sincerely, Neveruse / Talk / Block 15:50, 25 January 2010 (UTC) - How pointless is life? And don't go giving me any of that god/heaven gobshite because people never actually say what the point of heaven is either. Lily Inspirate me. 15:54, 25 January 2010 (UTC) - Heaven is where you spend an eternity singing praises to God. They may have a Hymnal for new arrivals and I assume you just follow along to learn the tumes. It is unknown at this time if God is into Gospel Rap tunes so "I'd bust a cap for Jesus" and "Yo Mary, shake that ass" are on hold. Hamster (talk) 16:08, 25 January 2010 (UTC) "a grain of truth in every pile" - I always liked Bill & Ted's take on heaven Bondurant (talk) 16:13, 25 January 2010 (UTC) The point of life is to survive and reproduce. Anyone who disagrees or bemoans this fundamental truth is civilized to the point of obsolescence. Me!Sheesh!Mine! 16:18, 25 January 2010 (UTC) - Or, to put it more precisely, genetic survival. Bob Soles (talk) 16:35, 25 January 2010 (UTC) - I'll be impressed with ice skating when a couple successfully performs the Iron Lotus without decapitation. CrundyTalk nerdy to me 08:20, 26 January 2010 (UTC) [edit] Time for the Conservapedia Dictionary Project - haha...Andy's personal goto dictionary. — Sincerely, Neveruse / Talk / Block 17:59, 25 January 2010 (UTC) - Marvelous thing, democracy; one person makes a complaint, the school board befouls their pants from fear of backlash at the polls and promptly does what the complainer demands. ListenerXTalkerX 18:01, 25 January 2010 (UTC) - Pathetic. "We'll be looking to find other things of a graphic nature". Idiots. ₩€₳$€£ΘĪÐ Methinks it is a Weasel 18:12, 25 January 2010 (UTC) - At least Jason Rogers brought some common sense to the argument. Looking up "dirty words" in the dictionary is an essential part of growing up. It also means that you learn the correct meaning. I'm sure many kids have used swear words without knowing what they mean by just copying the language of their elders. Lily Inspirate me. 20:10, 25 January 2010 (UTC) - Rubbish, I often ejaculate words into sentences without knowing what they mean. CrundyTalk nerdy to me 08:22, 26 January 2010 (UTC) - That's just love ;) ħuman 08:29, 26 January 2010 (UTC) - You know, the word ejaculate appears in the last harry potter book. Isn't this just another example of reality being too real for certain people? Next we'll be told that because having oral sex isn't child friendly, we're not allowed to do it. Or talk about it. Or think about it. And the numbers 8, 5 and 0 will be removed from calculators worldwide to stop the filth that is the number 80085. -Redbacknot Redneck 08:41, 26 January 2010 (UTC) Hang on, it might actually be the sixth book that has such child unfriendly language. I dunno. - That's just tits, though, what about 7734??? ħuman 08:44, 26 January 2010 (UTC) - Right, from now on we use a base 2 system. All numbers will be written in binary. In addition, binary will no longer be represented with 0 and 1. Due to the phallic nature of the number 1, and the clear reference to female sex organs which is the number 0, they will now be represented as ☺ and ☻. -Redbacknot Redneck 08:56, 26 January 2010 (UTC) - I thought oral sex was just talking about it, like the oral contraceptive is just saying "no". Silly twit (talk) 10:54, 26 January 2010 (UTC) [edit] My rant... So I was dicking around on Facebook when I saw the status of one of my wife's friends from college. It read thus: Shame on you America: the only country where we have homeless without shelter, children going to bed without eating, elderly going without needed meds, and mentally ill without treatment - yet we have a benefit for the people of Haiti on over 15 TV stations. CHARITY BEGINS AT HOME!!-can you name JUST ONE country that's... helped us, after, I donno, Katrina? Twin Towers? The list goes on & on. Feel free copy/paste. So I fired up Teh Google and looked. I posted this reply about the "name one country" bit: Hurricane Katrina: Canada, Britain, Greece, and Israel, among others, most turned down by the US. A list of International Aid (post-Katrina) can be found here:. Post-9/11: United Kingdom, United Arab Emirates, Canada, Mexico, most of the European Union, etc. (Source 9/11 commission, Google answers, etc.). Then I wrote this screed in another comment: At any rate, yes, poverty is bad here, but there are charities that deal with those issues. They may not garner the media attention that a natural disaster like Haiti can, but they are there, all year long, for anyone to donate time or money to. I think that not many people understand the abject poeverty that the third and developing worlds are plagued with, where homes are constructed out of earth or refuse and even the "well-off" have extremely limited access to such basic resources as running water or garbage collection (not to mention doctors, clinics, transportation, or hygenic food sources, all provided by charities in the US for those willing to ask for assistance.) If one truly wishes to make a difference here at home, one should volunteer time to a cause that they feel strongly about, rather than complain that countries in far worse shape than most can imagine are not extending aid to countries that, on their worst day, are better off than themselves on their best. I have lived in the rural areas of South Korea. I have lived with the locals in rural Iraq. Both of those places had it WAY better than what Haiti had BEFORE the quake. I have SEEN poverty, starvation, and desperation. The suffering here in the US, while very real and very tragic, is NOTHING compared to what the VAST MAJORITY of citizens in Third World and Developing World countries call their normal day-to-day lives. And THIS is what pisses me off about my fellow Americans. All too often, they're so quick to play the trump card about "We help everyone, why don't they help us?", never once comprehending the MAGNITUDE of squalor and sheer destitution that MOST of the world exists in, every day. Damn... We suck. The Foxhole Atheist (talk) 21:25, 25 January 2010 (UTC) - Nice rant. — Sincerely, Neveruse / Talk / Block 21:28, 25 January 2010 (UTC) - While I'd be one of the first to agree that America needs to get its act together regarding the situations of many of its own people, I'm totally with you that the sheer magnitude of the problem in other countries outstrips the US by far. Even so, you'd expect the self declared "greatest country on earth" could actually handle itself after Katrina (clearly it can't) whereas you wouldn't expect a place like Haiti to be able to. I mean, look at their Presidential Palace, it's fucking wrecked beyond help. For the US to experience something comparable to what has happened in Haiti (scaled for how much you'd expect the country to be able to deal with it), it'd have to see 9/11 repeated for practically every skyscraper in the country and then some. d hominem 21:31, 25 January 2010 (UTC) This is just from TVTropes, and it may be an urban legend, but supposedly, after Katrina, some ladies in one of the slums of Uganda spent some time breaking apart rocks and selling them, raising $1000, and offered it to the US Embassy to help the people affected by Katrina. I mean, day-umn -- a thousand dollars could have been a life-changing fortune to them, and they were willing to give it to American refugees. MDB (talk) 12:17, 26 January 2010 (UTC) - It sounds to me like someone just got her panties in a twist because they preempted Supernanny for that Haiti benefit. DickTurpis (talk) 14:13, 26 January 2010 (UTC) - Ha! Could be true, but it's been popping up on other friend's statuses (statii?) as well, so I have been copy/pasting a modified version of the above screed (as the other version only mentions 12 TV stations and omits the "Charity begins at home" part). The funny thing is, to a tee (and this has been on 5 accounts at this point, mind you) their status changes to something TOTALLY BENIGN ("I hate Mondays!" kind of crap) within 15 minutes of me posting my comment without so much as a word uttered in defense of the utter tripe they just got called out on. It seems to me that they think this kind of shit uttered about is patriotic or something until someone slaps them in the face with some reality and shows them what an absolutely shameful twat they're being. I perceive this as a much needed dose of reality and as I despise willful ignorance, am happy, nay I say PROUD, to be the provider. The Foxhole Atheist (talk) 14:54, 26 January 2010 (UTC) [edit] Set aside 70 minutes of your life for this awesomeness An insane man reviews The Phantom Menace. Don't be put off by his creepy serial killer persona & voice, cuz his insights are... amazing. He manages to bash TPM for 70 minutes without spending more than about a minute on Jar Jar or midichlorians. That's kind of a tour de force. If you make it to "Prota Gonnist" you will not be able to stop. I was like "I'm not watching 70 minutes of Youtube" and then BAM there I was an hour and a half later, more entertained and satisfied than I was by the entire prequel trilogy. If you don't have time to watch the whole thing, this is the best part (watch all the way to 10:00!!!!!). WodewickWelease Wodewick! 23:07, 25 January 2010 (UTC) - This was brilliant. Watched it twice over the weekend. Love it. TheoryOfPractice (talk) 23:08, 25 January 2010 (UTC) - To me the best part of the review is that he doesn't resort to simple nitpicking. He points some very real problems that the movie has. I can't wait to see his take on Episode II.Ryantherebel (talk) 23:19, 25 January 2010 (UTC) - Wow, that 4 minutes would have made me watch them all if I'd seen any but the 1st SW movies. Nice work! ħuman 00:04, 26 January 2010 (UTC) - Seen it before. I wanted to watch his review of ROTS and AOTC, but then I realized that there would be nothing to review, because only three Star Wars movies even exist. --User:Theautocrat/Sig 02:20, 26 January 2010 (UTC) What's a "Phantom menace"? I have just eaten & stiltontalk 21:18, 26 January 2010 (UTC) - I saw this a while ago, and was totally impressed. The voice is weird, and the presentation is bedroom quality, but the commentary is dead-on, and he comprehensively says what a gagillion Star Wars fans have been feeling (ans saying) for a long time. I would love to see more of his work. --Worm(t | c) 21:27, 26 January 2010 (UTC) [edit] Youtube Generally speaking, every youtuber video I've ever seen linked from here (excluding Goonie's music stuff) has been one of two things: - Some crazy idiot discussing about how Jesus wants all gays to be raped or how Obama is a fascist negro or whatever. - A British guy who explains with contempt how stupid everyone else is, with accompanying pictures and graphs and charts and fossils. This video was neither. It was also funny and awesome. Bravo!--Tom Moorefiat justitia 01:44, 26 January 2010 (UTC) - This guy is a lot like Thunderfoot: he has a funny accent, lots of time, very good editing skills, and he knows to go after the easy targets (George Lucas is kinda the Kent Hovind of filmmakers, no?) WodewickWelease Wodewick! 02:13, 26 January 2010 (UTC) - So can I be forgiven for my harshness is judging our local fumblemouthed Utuber? Because I expect this level of production values? Images that fit the talk, and talk that is "audible" not just beatless mumbles? ħuman 08:36, 26 January 2010 (UTC) - But... this American guy is hardly an idiot, and has valid points about the limits of human compassion. [3] Javasca₧ is out of his mind 13:32, 26 January 2010 (UTC) - Genius. Pure genius. It's like Cliff Yablonski from SomethingAwful started doing movie reviews. Part two had me doubled over in such laughter that I was in actual physical pain and dry-heaving into the kitchen sink. The wife thought I needed and ambulance because I couldn't get enough air in to tell her I was actually OK. The Foxhole Atheist (talk) 16:31, 26 January 2010 (UTC) [edit] Milkman Awesome. I noticed that there's a milkman who does a round on my road so I asked him for details of the service and was given a nice flyer to 'Milk and More' including a £5 off voucher for first order. So after creating an account and ordering a couple of pints and some bacon every Friday (mmm, bacon) along with a direct debit, I left with a warm fuzzy glow. Then I realised I hadn't used my voucher, so the next day at about 8pm I logged on and said I wanted a loaf of bread the next day. I came downstairs this morning at 06:30 and there was a fresh loaf of bread on my doorstep :) It's funny, you spend so much time getting hooked on the supermarkets that you forget how brilliant the simpler services are. CrundyTalk nerdy to me 08:46, 26 January 2010 (UTC) - Fuck, we don't have milkrounds in merka. I miss 'em. Can I get a coupon where I live? ħuman 09:17, 26 January 2010 (UTC) - No milkrounds at all in the US? CrundyTalk nerdy to me 09:23, 26 January 2010 (UTC) - (EC/none at all, no) You bastid, what, do you live in "civilization" or something? Teh Brits have been running this pit for like 400 years and we still have no milk'n'more service. [sob] ħuman 09:24, 26 January 2010 (UTC) - Pretty impressive. I do like the fact that if I need something (check the site, they sell fucking EVERYTHING, including fertiliser and compost!) then as long as I log on before 9pm I can have it the next morning. Free delivery as well, and the prices aren't much over what you pay in the supermarket. CrundyTalk nerdy to me 09:28, 26 January 2010 (UTC) - What a great service. We get newspapers, and a bit of milk & bread delivery, but it costs heaps. RagTopGone sailing 12:03, 26 January 2010 (UTC) - Did someone say Milkman? Vulpius (talk) 14:17, 26 January 2010 (UTC) - 404. Did you mean this? CrundyTalk nerdy to me 14:25, 26 January 2010 (UTC) - Whoops, my DNS server was playing up. Got it now. CrundyTalk nerdy to me 15:06, 26 January 2010 (UTC) - Bloody DairyCrest and the Milk Marketing Board. They almost killed off small-scale British cheese making and then had the effrontery to produce 'Lymeswold', which wasn't bad at first, but because they couldn't keep up with demand started shipping immature versions. Also, they don't deliver in my postal area. ГенгисOur ignorance is God; what we know is science. 16:39, 26 January 2010 (UTC) - So, you're saying "its awful, and they don't deliver to me anyway." Why does that sounds like "this restaurant's food is awful!" "yes, and the portions are so small!" MDB (talk) 19:54, 26 January 2010 (UTC) - There are some people who say that Americans don't get irony. I'm not one of those. ГенгисOur ignorance is God; what we know is science. 10:00, 27 January 2010 (UTC) - The milkman is long gone from NZ. Haven't been able to steal anyones milk money since I was 11. I remember when the garbage men used to come up the path, around the house and empty your bin for you. No we have put it out on the curb like a common troll. Did we lose a war our something? That's not NZ, thats not even Mexico. Acei9 19:57, 26 January 2010 (UTC) - At £1 for 2.272 litres from t'supermarket it's a no-brainer. No idea what milkmen charge nowadays but I'll wager it's a whole lot more. I have just eaten & stiltontalk 20:59, 26 January 2010 (UTC) - What supermarket do you go to? A 4-pinter own-brand in tesco is £1.53. The milky is £2.10 for "Country life" equivalent, but they do deliver it to your door. Tesco charge £4 for doing that. CrundyTalk nerdy to me 21:05, 26 January 2010 (UTC) BejamIceland. I have just eaten & stiltontalk 21:08, 26 January 2010 (UTC) - Do you stock up on party snacks and pile them onto a huge table and then make an arse out of yourself on chat shows and then fade fom the public eye? CrundyTalk nerdy to me 21:12, 26 January 2010 (UTC) [edit] Secularism or bigotry? Interesting one on the Beeb News website this morning (3rd paragraph of article): 'A French parliamentary committee ... recommends that anyone showing visible signs of "radical religious practice" should be refused residence cards and citizenship.' I somehow don't think they mean, "Hey Cardinal, take off those purple togs and that funny hat!"... The Real James Brown (talk) 12:17, 26 January 2010 (UTC) - That's dangerous thinking, especially in these times when anyone who utters the Takbir is instantly perceived by many as some kind of radical (if not a terrorist). On the other hand, if it keeps the scientologists away... Personally, I think anyone whose religious practices involve coming to my house (always with small children so you can't swear at them) and trying to convert me should be refused citizenship. -Redbacknot Redneck 12:34, 26 January 2010 (UTC) - Hmm... Keeping the Thetans away - maybe not such a bad idea. But I'm guessing that Jewish yarmulkes, Sikh turbans and nuns' outfits aren't going to be covered by this legislation either... The Real James Brown (talk) 13:05, 26 January 2010 (UTC) - Catholic cardinals tend not to be political radicals; neither do Orthodox Jews. I would argue that citizenship should only be refused people who, on account of their beliefs, are not able to exercise the duties of citizens in a conscientious manner, viz., those who are opposed to the entire law of the land, the very thing that defines citizenship. (To put it another way, if they think so poorly of citizenship, they ought not to be given it.) ListenerXTalkerX 18:48, 26 January 2010 (UTC) [edit] Industrial grade stupid Just found this new site, just brimming to the top with natural health woo, along with a spattering of other crazy beliefs (including 9/11 truther among them). Check it out; natural news - I'm sure some of you have seen it already, but if not, it's worth the laugh. My favorite is their main contributor, who calls himself the "Health Ranger". I wonder if that's like a park ranger, or an Aragorn ranger? Z3rotalk 15:40, 26 January 2010 (UTC) - Hehe "One such skeptic accused me of being a quack because he said that I believe "water is magical." Was that supposed to be an insult? I do think water is magical!" - well, can't argue with that! CrundyTalk nerdy to me 15:55, 26 January 2010 (UTC) - Of course it is, it goes in clear and comes out yellow! If that's not magic then I don't know what is. -Redbacknot Redneck 15:59, 26 January 2010 (UTC) [edit] Upcoming Interview with Sarah Palin Sarah Palin has finally found someone to interview her that's not smarter than she is. MDB (talk) 15:53, 26 January 2010 (UTC) - Love one comment: "Of course, Sarah leaving Alaska for Fox did improve the IQ of both areas." I have just eaten & stiltontalk 15:58, 26 January 2010 (UTC) [edit] If you were the interviewer And got an interview with Sarah Plain, what would you ask? Just to keep it organized, I'll split it up... [edit] Serious Questions - If you were elected President, would you base Middle Eastern policy upon your church's interpretation of end-times prophecy? - If you were elected President, how would you deal with the growing outcry in the scientific community regarding Intelligent Design? - Despite your decision to step down as governor of Alaska before the end of your first term, some people consider you the Republican candidate for 2012. Do you think that you have the right qualities to vie for the presidency? And if so, what are those qualities?--Thanatos (talk) 19:32, 26 January 2010 (UTC) [edit] Snarky Questions - Do you expect to be able to see Canada from the White House? - So... How'd it taste? - Did we ever find out who 'adopted' that Turkey from your interview? [edit] In Between/Uncategorizable MDB (talk) 16:05, 26 January 2010 (UTC) Will you allow rationalwiki to effectively ban vandal bin 15,000 people (14, 999 of whom have shown no interest in the site) because of the incredibly infantile and annoying actions of one person, self-admitted troll who has not made a positive contribution in monthsSarah? How do you propose curbing idiocy on the internet one pissant little website that reaches about two dozen regulars at most? - MarcusCicero - (Fixed that for you MC) - (Bloody hilarious on so many levels - but I doubt on the levels that MC intended.) Bondurant (talk) 16:20, 26 January 2010 (UTC) - Shouldn't that be 14998? Or are you giving up the Edmund Burke thing? — Pietrow ☏ 20:43, 26 January 2010 (UTC) [edit] Free holiday I just had to give money to sponsor a guy at my work to do a sponsored walk (yes, walk, not run or bike ride) in order to raise funds so his girlfriend can fly to China to do a sponsored walk along the great wall for charity. Is this how people get free holidays these days? CrundyTalk nerdy to me 16:26, 26 January 2010 (UTC) - Those charity treks usually involve paying quite a large deposit yourself, e.g. about a grand, & making a commitment to raise at least two or three times that in sponsorship. I've thought about doing them, but I doubt I have enough contacts to raise that kind of money. Sponsored walks to sponsor somebody else's sponsored event seems somewhat convoluted though. ₩€₳$€£ΘĪÐ Methinks it is a Weasel 19:13, 26 January 2010 (UTC) - Damn, and here I was organising a sponsored "Lying on a sunbed-a-thon" in Hawaii. CrundyTalk nerdy to me 20:00, 26 January 2010 (UTC) - There is enough volunteer work to be done in the local area that one does not need to take trips to China in service of charity. ListenerXTalkerX 20:54, 26 January 2010 (UTC) - This isn't even for a charity in China. It's for something like heart disease or breast cancer. UK charity. But apparently you have to go to China to raise money for it :\ CrundyTalk nerdy to me 21:07, 26 January 2010 (UTC) [edit] Obama spending freeze "deficit reduction" Gee why bother having a Democratic primary if no matter which candidate wins we get Clintonite "Third Way" leadership. WodewickWelease Wodewick! 19:36, 26 January 2010 (UTC) - Welcome to politics! Nothing ever changes. EddyP (talk) 19:58, 26 January 2010 (UTC) - I blame Stalin. ħuman 23:38, 26 January 2010 (UTC) - Guy has completely lost touch with who put him in office. He keeps chasing Republicans, what's the allure here, is it like a Hard To Get romance? They're just not that into you Barack. He cedes intellectual ground to the retard teabaggers again and again and it never wins over a single Republican Senator. He cuts chunks out of his own stimulus and healthcare reform bills to please "moderate" Republicans who then... vote no again & again. - Owell, count me out in 2012. I didn't fucking vote for Hillary. WodewickWelease Wodewick! 23:42, 26 January 2010 (UTC) [edit] Fox burned by own poll In this poll done by Fox, Americans prefer Obama to Tea party protests and Palin! They instead choose to discuss how many people were against Barry (no surprise)--Thanatos (talk) 20:40, 26 January 2010 (UTC) - For some reason I can't resolve that link, Than. I have just eaten & stiltontalk 21:02, 26 January 2010 (UTC) - Here's a link to the PDF: fox news survey. It's at the top of page 2. -- Ask me about your mother 22:52, 26 January 2010 (UTC) - Hahaha, and who the hell would trust Fox Noise or Sarah Palin? Oh, right. I forgot some people are foolish enough to listen to them. Gooniepunk2010 Oi! Oi! Oi! 23:04, 26 January 2010 (UTC) [edit] RationalWiki:Year in review I have posted a blog entry at the tech blog reviewing what I consider "statistics of interest" for 2009. People might be interested in checking it out. tmtoulouse 00:13, 27 January 2010 (UTC) [edit] Quick question I'm hoping some nice person can help me with Okay, I have a random question that I'm hoping someone can help me out with, and I require the help of an American (or learned person who knows a bit about America) who plays Civilization. Q: What is the name of the music that plays throughout the mid and later stages of the game when you are negotiating with Teddy Roosevelt? The file can be found in the \Assets\Sounds\Diplomacy directory with the filename Roosevelt_Late.mp3. Ta in advance. -Redbacknot Redneck 02:03, 27 January 2010 (UTC) - Not a gamer, but good @ music trivia. Get me an online MP3. TheoryOfPractice (talk) 02:04, 27 January 2010 (UTC) - This may help.--Tom Moorefiat justitia 02:08, 27 January 2010 (UTC) - Indeed it does, I now know that's it's called Marines' Hymn. I never noticed that article before, I'm off to have a good read through it. Thanks Tommy, and thanks to ToP as well. -Redbacknot Redneck 02:12, 27 January 2010 (UTC) [edit] Local news A friend of a friend was attacked a while back by a 13-year old and raped (news article). As the boy was only 13 at the time he was convicted to 3 years. Pretty standard, but as you can imagine most of the backlash would have initially been about how the judge "got it wrong" and he should have got a lot longer / life. However, let's note that the youth's name was "Balal Khan". Can you imagine what slant the user comments on the above news story have taken? Have a look, pay particular attention to the comment part way down from "Mellissa, Chell". CrundyTalk nerdy to me 10:26, 27 January 2010 (UTC) - Fucking stupid woman. Britain is a multicultural society, that is one of the things that makes Britain Britain. To hell with the racists. SJ Debaser 12:01, 27 January 2010 (UTC) - "We are dealing with a very immature young man," said the mitigator. Fucking understatement, YOU'RE DEALING WITH A RAPIST! An immature young man, you slap him on the wrist and send him on his way. What a stupid comment. SJ Debaser 12:04, 27 January 2010 (UTC) - Stoke on Trent, it was in in nearby Hanley where they had that racist EDL demo last week. Lily Inspirate me. 13:10, 27 January 2010 (UTC) - Yes, which is why I think it was a piss-poor decision by the judge to allow the press to publish the guy's name. It will just cause more racial tension. CrundyTalk nerdy to me 13:18, 27 January 2010 (UTC) [edit] I think someone just attempted to scam me So, I was on facebook a little while ago, and a chat popped up from a guy I used to work with. He said he was in London, and had been mugged at gunpoint, taking all his credit cards, cash and phone, and needed me to wire him money so he could settle his hotel accounts. I asked if he had contacted the US Embassy. He said they said they couldn't get him a flight till the 30th, and needed to get home sooner than that. I was suspicious, so I asked him to tell me the company we used to work for, and the name of the project we were on. He got the company name right (but then, that's on my Facebook page), but couldn't remember the project name. I was also thinking "you have no family who can help you? Surely, the US Embassy would let you call the States to reach them. No friends closer than me? I've not seen you in over three years, and we weren't that close then." And in retrospect, "you run a travel agency as a side business -- surely you know better ways then this to deal with travel emergencies!" I told him that I realize that if he really is who he says he is, he may hate me forever, but I'd need some more verification he is who he claims to be. I suggested he call someone at the company we both worked for, since at least they would recognize his voice. I also think "mugged at gunpoint in London" seems odd... doesn't the UK have very strict gun laws and very little gun crime? MDB (talk) 16:48, 27 January 2010 (UTC) - Yeah, gun laws are very strict over here, although it's not too hard to get them if you know where to go. Knives are a hell of a lot common, due to the fact you can buy them with ease at any old shop. SJ Debaser 16:51, 27 January 2010 (UTC) - No, more common in Manchester. Almost 1 per year, I believe. I have just eaten & stiltontalk 17:05, 27 January 2010 (UTC) - What Toast said. Knife crime is more common in London than gun crime, though gun crime's more prominent in northern cities like Manchester. I know people who've been robbed at knife point, including a family member, but never gunpoint. SJ Debaser 17:09, 27 January 2010 (UTC) - That one gun crime a year in Manchester probably wouldn't happen if the people could defend themselves with guns. — Sincerely, Neveruse / Talk / Block 17:18, 27 January 2010 (UTC) - Nottingham was reputedly the gun crime capital of the UK for a while, but we've not had a single incident I can think of for over 5 years. The police really clamped down, and anyone suspected of being in possession of a gun would find themselves under seige by an full armed response unit. Bondurant (talk) 17:23, 27 January 2010 (UTC) (unDent) I called the phone number for his travel agency, and spoke to his wife. I wasn't the first person to call, and yes, its a scam. She planned to change his facebook password. MDB (talk) 17:33, 27 January 2010 (UTC) - Now it's your duty to fuck with the scammer. — Sincerely, Neveruse / Talk / Block 17:38, 27 January 2010 (UTC) - My Hotmail account got hacked by a spambot recently. Fortunately, all it did was send an email to all my contacts promoting this dubious website in broken English. Still, pretty embarrassing. ₩€₳$€£ΘĪÐ Methinks it is a Weasel 19:17, 27 January 2010 (UTC) - Definitely a scam, happened to a NZ girl recently. Had her account hacked and a message went to everyone in her contacts with the same message about being mugged. AVOID!. Acei9 19:50, 27 January 2010 (UTC) - I did wonder why I was getting a lot of facebook phishing emails. I thought "Why the fuck would a spammer want someone's facebook details?". CrundyTalk nerdy to me 20:24, 27 January 2010 (UTC) - It's a very interesting idea of how to abuse FB. People might think they're safe by doing the sensible thing and keeping their private data off the site and controlling who sees what (those "privacy concerns" are so overhyped it's stopped being funny) but that'll just make them more lax with their passwording. d hominem 20:26, 27 January 2010 (UTC) - I remember my last action on a windows machine. A friend had their facebook account hacked and was sending out messages to look at a jpeg that had some overflow hack. I was about at the end of my rope with windows anyway and I wanted to see how easy it was if you were actually that stupid. Turns out it's really easy. Computer was fucked. — Sincerely, Neveruse / Talk / Block 20:30, 27 January 2010 (UTC) [edit] It continues... So another one of them popped up, and I guess the guy is AFK or something because it's been dragging on now. One of the other posters threw this up: ok well what about katrina?? did hati,, japan,, china and africa have a benefit to help america?? i didnt think so.. To which I responded with this: Haiti, no. But they didn't have anything to offer anyway. The People's Republic of China gave $5 million and disaster relief supplies. Japan offered $200K and $300k in emergency supplies, but one businessman donated $1 million of his own personal money. As far as Africa, that's a continent. There's more than one country there; Djibouti, Yemen, Kenya, Malta, Nigeria, and Egypt all offered aid. Actually, the international community responded fairly overwhelmingly. Over 120 countries pledged support, relief teams, supplies, and/or money. See a list here: For the most part, it was our own government's failings that made Katrina as bad is it was. Most of the aid was turned down by the US, though. See here: You see, when you want the rest of the world to perceive your country as the most powerful country and greatest nation in existence, it doesn't help your reputation to accept assistance from countries who have nothing, like Azerbaijan, Yemen, et. al. Which was immediately followed by this: I think the point is that did America have a benefit for Katrina? Sure they did but was it as big or aired on every major network the way the benefit for Haiti was? Nope. Thanks for posting this <REDACTED>, happy to see you had the guts to. So I followed up with this: Furthermore, why does anyone need a celebrity to "raise awareness" to tell that person to go out and help their neighbor? These are DOMESTIC issues we are dealing with. The homeless and hungry people, abused children and mentally ill... They are IN OUR NEIGHBORHOODS ALREADY. Step out the door and HELP. One shouldn't need to be told to do that; it's the very essence of civic duty. Also, the charities that do address these issues don't need money so much as they need volunteers. They need people to collect and hand out blankets and coats to the needy. They need people with able bodies to build houses for the homeless. They need folks willing to serve stew at the soup kitchens. They will not turn any offer of assistance away and time is more valuable than money in most cases. If one happens to be so busy that they cannot volunteer, then they should whip out the checkbook. Why are people so fucking DUMB? *HEADDESKHEADDESKHEADDESKHEADDESK* The Foxhole Atheist (talk) 21:09, 26 January 2010 (UTC) - One thing I find interesting is that even though I knew of the awful events in Haiti, it was the (expensive to put on?) benefit concert - actually, the beautiful music I caught at the end of it - that prompted me to part with some cash. Odd, that. ħuman 22:38, 26 January 2010 (UTC) - I thought it'd be worth letting you know that I'm seeing the same sort of thing. Assholes. d hominem 16:55, 28 January 2010 (UTC) [edit] Westboro Baptist Church picketing twitter WTF? Sterile ramen noodle 02:34, 27 January 2010 (UTC) - I don't get it, what exactly do they want? For twitter to start sending tweets to every user at five-minute intervals stating christian truths such as "Remember children, god gave you free will so that you may never use it" and ammending every tweet with the message "ps god hates fags"? -Redbacknot Redneck 03:40, 27 January 2010 (UTC) - They want attention and money. It's a business for them; they've won millions in claims against people they provoke into violating their rights or attacking them, plus they get the bonus of spewing Phelps' hate.--Tom Moorefiat justitia 10:38, 27 January 2010 (UTC) - It's definitely attention seeking. Their latest is to go after Lady Gaga for some less than clear reason. Surely there are far more active "enablers" out there, although they're not so famous. Wonder why the Phelps clan doesn't go after those, then... d hominem 14:46, 27 January 2010 (UTC) - "Remember children, god gave you free will..." Phelps and crew are Calvinists and do not believe in free will. ListenerXTalkerX 23:44, 27 January 2010 (UTC) [edit] Lab rant What part of "do not use this or I will tie you down and make you watch 2 Girls 1 Cup" is so hard to understand? d hominem 16:16, 27 January 2010 (UTC) - What did they use? CrundyTalk nerdy to me 16:19, 27 January 2010 (UTC) - About £300 worth of high purity d8-THF that I was earmarking for photolysis. d hominem 16:22, 27 January 2010 (UTC) - Should have wired the desk up to the mains. CrundyTalk nerdy to me 16:24, 27 January 2010 (UTC) - You have to make good on your promises/threats or no one will take you seriously, A. SJ Debaser 16:26, 27 January 2010 (UTC) - Trouble is, I'm not 100% sure who it was. Probably one of the first-year meatsacks. d hominem 20:27, 27 January 2010 (UTC) - Prolly like most of us here I had no idea what d8-THF was. I've been googling it for ages now & everyone's agreed it's EXPENSIVE (10 x 0.75 ml: $593.23 so you had about 6ml?) I have just eaten & stiltontalk 23:29, 27 January 2010 (UTC) - So wait is it just Tetrahydrofuran but with deuterium instead of hydrogen attached to each carbon atom? CrundyTalk nerdy to me 08:29, 28 January 2010 (UTC) - Yes, it's an NMR solvent. If you used proteo solvents, the signal would be insane. Although since I record my kinetic spectra on the 31P channel, it shouldn't be too much of a problem. But the deuterium (because it resonates completely separately to protons) can be used to lock the sample too. So it's sort of essential. d hominem 16:45, 28 January 2010 (UTC) - So it has to be manufactured with pure heavy water only? No wonder it costs a fucking fortune. CrundyTalk nerdy to me 20:32, 28 January 2010 (UTC) - Wow, that was music to my ears. I haven't heard chemistry talk for a while. The job I have now has me melting metals into a sample plug and using optical emission spectroscopy to analyze. Very cut and dry, no wet chems, just melt and spark. Aboriginal Noise with 4 M's and a silent Q 22:01, 28 January 2010 (UTC) [edit] Wikileaks (bump) Gone? I have just eaten & stiltontalk 16:41, 27 January 2010 (UTC) - Mindless cubic Hoover! 19:47, 27 January 2010 (UTC) - Damn. Anyway, I may as well copy/paste the WP entry on its recent activity: On 24 December 2009 Wikileaks announced that it was experiencing a shortage of funds ( at 1.24am 24 Dec 2009) and suspended all access to its website except for a form to submit new material. Whilst it was initially hoped that funds could be secured by 6 January 2010, ( at 7:42am 5 Jan 2010) as of 27 January 2010 the website is still closed. There is no precise indication of when Wikileaks will be able to resume normal operations. On 22 January 2010, PayPal suspended Wikileaks' donation account and froze its assets. Wikileaks claimed that this had happened before, and was done for "no obvious reason". The account was restored on 25 January 2010. [edit] Women drivers Alright, so I'm not going to get into a "Men are better / safer drivers than women" argument, because I know that isn't true. What I'd like to talk about is Women's complete inability to recognise when someone is allowing them to pull out in front of them. You know the situation, it goes like this: - Driving along, you notice that you have a good gap between you and the car in front. A car in the opposite direction is waiting to turn right (or left if you're not a UKian) and is blocking the traffic behind them - You flash your lights a couple of times to indicate that you are letting the driver turn into the side road in front of you - The driver still hasn't moved. You slow down and flash your lights again - The driver STILL hasn't moved. You slow right down and flash again - Still nothing. You come to a complete standstill. You flash your lights over and over, jump up and down, and wave your hands around trying to convince them to move - After looking at the glares of extreme anger in your rear view mirror, you look back to see the woman (yes, it's always a woman) suddenly SNAP into reality (from thinking about kittens or knitting or whatever) and then do that odd thing where they try and frantically turn their wheels full lock and try to wave thank you in the middle (turn-turn-turn-QUICKTHANKS-turn-turn move) rather than having their wheels already at full lock and waving thanks when they first note you letting them go (see (1)). I mean what should I do? Not be nice anymore and just block all junctions? I got to the point the other day where I'd been at a complete standstill for about 10 seconds (count it in your head) and nothing, so I just drove on. Can someone explain this one to me? CrundyTalk nerdy to me 22:36, 27 January 2010 (UTC) - I don't about that but driving with my other half is an exercise in anger control. - "Watch out for that pedestrian!" - "The speed limit is 50 in this zone" - "There is a give way sign coming up" - etc etc. I go crazy, "I know there is fucking pedestrain ahead because the car has stopped which is why the pedestrian is able to cross the road safely". Acei9 22:41, 27 January 2010 (UTC) - God, I miss driving. I got my licence when I was seventeen (yeah, passed first time, fuckin' A) and haven't driven since. I'm too poor to run a car, especially given I don't have a job, and every single insurance company I try and get a quote from is a pile of absolute bollocks that asks me to waste about 10 minutes of my life filling in my info only to tell me, "due to the information you've given us, we are unable to provide you with a quote at this time." - Crundy, I feel your pain. When I was learning to drive I remember women driving 4x4s (in suburban London) with no concept of how much of the road they were taking up. Extremely annoying. My instructor was even shouting at them. SJ Debaser 22:49, 27 January 2010 (UTC) - 'kinell. I'm starting to feel really unloved. What with Ace on Brits (OK exception noted, Ace) and now this. I suspect it's the frequent driver versus the occasional driver. I've been driving for well over 45 years now & reckon I'm not bad. The ones who enrage me are generally men who see a woman driving and have to cut them up as a matter of principle. Way back I was a delivery driver in London & the home counties and it wasn't so bad then (of course a 22 year old female's more likely to be allowed for than a 65 year old) More rant available if required. I have just eaten & stiltontalk 23:43, 27 January 2010 (UTC) - So you don't want to talk about men being better drivers than women, Crundy, but you're still going to generalize about an entire gender's driving skills? I don't usually call out many "ism"s, but attributing poor skill in an ability to a gender is the definition of sexism, Crundy. And I imagine your confirmation bias is playing a not-insignificant part here.--Tom Moorefiat justitia 00:35, 28 January 2010 (UTC) - Yup. Seems quite easy to get Tom on his extra-high horse these days. I'm surprised you can even see me eating my meat from up there. I know you wouldn't ever generalise about people so I'll take it all back. Oh, and thanks for condescendingly linking me to confirmation bias. Where would I be without you helping me out with such things? CrundyTalk nerdy to me 08:49, 28 January 2010 (UTC) - Prison? The Foxhole Atheist (talk) 13:00, 28 January 2010 (UTC) - Are you seriously so stupid as to think I was serious with that thing about the British, Crundy? I painstakingly even pointed out later in that discussion that I was joking, although one would think the Canada thing should have tipped off anyone. - I'm not sure it's so "high horse" to point out that "women are bad drivers" is sexist. That one's not exactly rocket science to figure out, ethically speaking.--Tom Moorefiat justitia 18:29, 28 January 2010 (UTC) - Which is why I made the point of stating that I wasn't saying "women are bad drivers", you fucking twat. CrundyTalk nerdy to me 19:26, 28 January 2010 (UTC) - It's a truism. Women are bad drivers. Most black women shouldn't even be let behind the wheel. Asians follow closely in complete lack of skill, then the elderly. — Sincerely, Neveruse / Talk / Block 19:41, 28 January 2010 (UTC) - Huh, so MarcusCicero has done a mind-transfer into Neveruse now? CrundyTalk nerdy to me 20:15, 28 January 2010 (UTC) - I guess me and my friends are the only ones who play "woman, black or both?" when you get stuck behind someone... — Sincerely, Neveruse / Talk / Block 20:24, 28 January 2010 (UTC) - These guys probably do. CrundyTalk nerdy to me 20:26, 28 January 2010 (UTC) - Oh, get off it. It's just an observation. You ever notice how younger blacks usually don't thank you for holding the door open? — Sincerely, Neveruse / Talk / Block 20:28, 28 January 2010 (UTC) - Please to stop tweaking Crundy. Funny, like, but it's gonna end in tears. --Robledo (talk) 20:34, 28 January 2010 (UTC) - "White people drive like this - de de de de de. Black people drive like this - doo doo doo doo." - "It's true, it's true. We're so lame." — Sincerely, Neveruse / Talk / Block 20:51, 28 January 2010 (UTC) - "Which is why I made the point of stating that I wasn't saying "women are bad drivers", you fucking twat." - You can't declare something and suddenly it's true. Just because you claim you're not saying that "women are bad drivers," that doesn't mean you can then speak about how all the frustrating bad drivers on the road are women and not be sexist, especially with such as this: - "Women's complete inability to recognize someone is pulling out in front of them". - "After looking at the glares of extreme anger in your rear view mirror, you look back to see the woman (yes, it's always a woman)" - It's not a big deal, I just thought it merited pointing out that you were being rather sexist by generalizing about how such bad drivers are always women. If it really bothers you, then shucks, I'll take it back. - By the by, I don't want to generalize and I'm not saying all black people are bad drivers...--Tom Moorefiat justitia 20:56, 28 January 2010 (UTC) - You'd be a bad driver too if you were constantly looking out for the cops. — Sincerely, Neveruse / Talk / Block 21:00, 28 January 2010 (UTC) - Well, in Ace's case... --Kels (talk) 21:04, 28 January 2010 (UTC) [edit] Because I need to show it someone The article title alone made me slightly nauseous, but read on. -- Lauttydauttywe likes to party 01:50, 28 January 2010 (UTC) - ya cant expect a groundhog to be happy being lifted up and shown off for 30 minutes a year , thats barbaric, bring on the robot. I see it now. A round tunnel , with a nice round door and a brass knocker in the center, a small stone path leading down the bank to the pond. Out comes the robot , holding his sunglasses and a brew. He puts the glasses on , squints, waves the finger at the crowd, downs the brew and goes back inside , while a chorus of "its a small world after all" plays in the background (darn secondhand Disney stuff) Hamster (talk) 04:29, 28 January 2010 (UTC) - I'd prefer 'I'm coming home', the Superjail theme, instead of the Disney crap. It'd fit better with the drunk Johnny 5 routine, methinks. -- CodyH (talk) 05:20, 28 January 2010 (UTC) - Whether the groundhog comes out or not, it's just superstitious nonsense. Would the robot have a rand function to decide whether he comes out? I want to get paid to program a groundhog heuristic. Pay me, bitches. 05:25, 28 January 2010 (UTC) - Shit man, put a woolly sock on a vibrator. No one will know. Acei9 05:27, 28 January 2010 (UTC) - he has to stick his head out and look for his shadow. Its all about does he see his shadow . This is science ! Hamster (talk) 18:30, 28 January 2010 (UTC) - Maybe I'm a little partial to the little guy because Phil is practically my neighbor (Punxsutawney is about an hour away), but what the hell? PETA has gone totally weird. Ain't no way no animatronic groundhog be replacing no real thing. Aboriginal Noise with 4 M's and a silent Q 22:11, 28 January 2010 (UTC) - It's just for attention for their cause. Although it is actually in keeping with their mission, since they don't want animals to be exploited in any way - including in circuses or as amusements. This makes sense for them to get up in people's faces about, because it costs them almost nothing and gets them a lot of publicity, which brings in money to pay for the real work like undercover ops.--Tom Moorefiat justitia 02:30, 29 January 2010 (UTC) [edit] New Javascript thingy I have added some new code to MediaWiki:Common.js that will allow you to edit the three boxes down the side (actually all four but editing the support would look funny). Basically by adding function CustomizeModificationsOfSidebar() { ModifySidebar("add", "toolbox", "Statistics", ""); } addOnloadHook(CustomizeModificationsOfSidebar); to your monobook javascript you can have a link to the site statistics page in the toolbox. If you don't like a link: function CustomizeModificationsOfSidebar() { ModifySidebar("remove", "navigation", "Best of RationalWiki", ""); } addOnloadHook(CustomizeModificationsOfSidebar); and it is gone. If you want to do both: function CustomizeModificationsOfSidebar() { ModifySidebar("remove", "navigation", "Best of RationalWiki", ""); ModifySidebar("add", "toolbox", "Statistics", ""); } addOnloadHook(CustomizeModificationsOfSidebar); My next idea is to take this a step further and have a box called bookmarks. If you don't have a subpage called Bookmarks you would not see it, but if you have one such as mine, you can have links to all your favourite pages right there in the side bar. So does the mob like this idea? - π 06:37, 28 January 2010 (UTC) - If you make this solid it should be added to help pages, and maybe even the welcome message? Because here it will just get archived by some irrational robot... ħuman 08:08, 28 January 2010 (UTC) - You can't make a portlet in MediaWiki:Sidebar then hide it with javascript. Not everyone has javascript, and it can be ugly if the js loads slowly. Instead, the javascript should create the portlet if the user wants bookmarks, and it should be a gadget, so that if the user doesn't want bookmarks you don't slow them down by loading the bookmarks subpage of their userpage with every page load (see my monobook for how the server status widget creates a portlet). In fact the bookmarks subpage idea isn't good because you need to load another page with every refresh. Better to just create a gadget and then let the user fill in an array in their monobook with their bookmarks. Or better yet, just skip the whole gadget stuff (one unnecessary request slowing down page loading - try enabling a lot of gadgets and see how slow page loads become, then look at firebug or webkit's inspector to see how much time is spent loading those), create a function that allows the user to inject a new portlet, put that into common.js beside modifysidebar, then just tell the user to run that function first in their monobook.js if they want to create a new portlet, e.g.: function CustomizeModificationsOfSidebar() { AddPortlet("bookmarks",probably some parameter to determine insertion point); ModifySidebar("add", "bookmarks", "Statistics", ""); } addOnloadHook(CustomizeModificationsOfSidebar); - It's not as simple as creating a bookmarks subpage, but it's faster. - Also, your instructions are unclear. I foresee people creating multiple "CustomizeModificationsOfSidebar" functions, which of course won't work. All additions, removals, etc. have to be in one function, i.e.: //Don't copy the <source lang=javascript> line if you are copying from the edit window function CustomizeModificationsOfSidebar() { //Don't change this //Start here, replace the examples with your own ModifySidebar("remove", "navigation", "Best of RationalWiki", ""); ModifySidebar("add", "toolbox", "Statistics", ""); ModifySidebar("remove", "the name of the portlet, i.e. navigation, community, toolbox, etc.", "the name of the link", "the url (is this needed for remove?)"); ModifySidebar("add", "the name of the portlet", "the name of the link", "the url"); // Add more here //Stop here, don't change anything below this } addOnloadHook(CustomizeModificationsOfSidebar); //Don't copy the source tag [edit] Why not do something really useful? Loading RW, and only RW, on my mobile/cell phone takes forever. Nx says it's not because of the volume of text in monobook.css & js so I assume it's the work involved in processing them for every page. How about creating a mobile friendly skin that auto detects when you're on a mobile & loads itself? I have just eaten & stiltontalk 13:41, 28 January 2010 (UTC) - I second that. And a "top" bookmark link because my mobile doesn't have scrollbars and I have to swish for ages and ages to get back up to the leftbar links. CrundyTalk nerdy to me 20:30, 28 January 2010 (UTC) - Thirded, if this is technically possible. I like to look at RW on my Kindle sometimes, and it takes forever.--Tom Moorefiat justitia - @ Crundy, I'm actually surprised that MW doesn't automatically put a "top" link next to every section "edit" link. I've always put them on any page I've written that is gonna be more than one or two screens. CTRL-Home doesn't always work on wiki pages. ħuman 23:47, 28 January 2010 (UTC) - There is not a lot I think I can do about that, at least without server access. It probably is much more difficult than mealy a skin issue. I would take it up here. - π 00:59, 29 January 2010 (UTC) [edit] Barry wrote me after his speech, and I replied "This is the Spam Firewall at smtp.barackobama.com. I'm sorry to inform you that the message below could not be delivered. When delivery was attempted, the following error was returned." I wrote, in response to his request for MY FUCKING MONEY "Move to the left, not the "center"/right. Call for a single-payer national health care plan. Repeal the Bush *and* Reagan tax cuts on the rich. Get out of Iraq NOW. Close G-Bay NOW. Stop being a chicken, stop this silly "bipartisan" thing. No money for the dems from me until I see you fighting for what I supported you for. Sincerely yours, Huw Powell" Fuck you if I can't even reply to your email. Fuck you and learn how the web works - both ways. ħuman 08:05, 28 January 2010 (UTC) - From here: admin@barackobama.com. Ask them to forward it on for you :) CrundyTalk nerdy to me 09:16, 28 January 2010 (UTC) - He says a large problem with Washington is "every day is Election Day," yet he sends fundraising emails. And he's still talking as if he expects people to re-elect him because of what he's FOR not what he's DONE (or not done). - There is no bipartisanship, there is no center, right wing nutbags will call you a Muslim Maoist Kenyan no matter what you, Blue Dogs will find any excuse to defer your agenda no matter what you do, Republicans will threaten to filibuster no matter what you do. So crack down, find out which legislators are interested in legislating, and get them to pass whatever can be passed in a 51 vote environment. That's how Cheney did it, that's how the GOP does it, and it's worked out pretty well so far for them. WodewickWelease Wodewick! 13:46, 28 January 2010 (UTC) Might I suggest: Dear Mister President, There are too many states nowadays. Please eliminate three. I am not a crackpot. Yours, etc. MDB (talk) 13:56, 28 January 2010 (UTC) - I was actually looking at a map of the Caribbean the other day and thinking, "hey, there are easily a half dozen new states there if we just tried". Number depends on whether Cuba has natural internal divisions making it 2 or 3 states not just one. ħuman 23:52, 28 January 2010 (UTC) - That will put it up to 57 like he said, right? Aboriginal Noise with 4 M's and a silent Q 03:02, 29 January 2010 (UTC) [edit] Limbaugh gets really weird Okay, this borders on the creepy. Rush Limbaugh has offered to be the father Obama never had. Though the first comment wins the internetz for the day: Sounds like a pick-up line he'd use in the Dominican Republic. MDB (talk) 19:21, 28 January 2010 (UTC) I hate Limbaugh so much...--130.160.187.16 (talk) 21:55, 28 January 2010 (UTC) [edit] New Scientist - horizontal gene transfer [edit] T. Boone Pickens and Natural Gas Ok, I initially put Natural Gas on the To Do list mainly because of Jon Stewart's interview with T. Boone Pickens, because I'm curious how valid his arguments are (he thinks that hydrogen cars are a good idea, but doesn't think they could run 18-wheelers, and thus wants to use natural gas for shipping purposes). Could someone please analyze his arguments and put the results in the article: --Mustex (talk) 00:19, 29 January 2010 (UTC) - He doesn't make many arguments, and I haven't read the book. I addressed what I could. I'll check out the book and add more this week - sooner if I can find a copy online.--Tom Moorefiat justitia 00:41, 29 January 2010 (UTC) - As I understand it, the problem with hydrogen power is that is isn't really a power source in itself, it's just way of storing and using electricity that is probably produced using coal or another "dirty" energy source. Tetronian you're clueless 00:47, 29 January 2010 (UTC) - Liquified natural gas or propane works fine as a replacement fuel in cars or light trucks. You burn more of it for the same milage and the filling station is a bit more complex. No idea how it would convert for deisel engines. Hydrogen also works but LNG or propane are easier to get. Hamster (talk) 01:16, 29 January 2010 (UTC) [edit] I am smiling right now and its because the reports are that Obama will call for an end to "Don't Ask Don't Tell" in the State of the Union address tonight. In four words: It's. About. Fucking. Time. MDB (talk) - Gee, that and clean coal, more nukes, offshore drilling, nothing interesting about health care... but at least the gays can die in Iraq! Nice work. Rant over. Fucker sent me an email after the speech (asking for MONEY!!!!), I tole him what I wanted before his party gets dime one from me. ħuman 05:51, 28 January 2010 (UTC) - Huw, he was talking about nuclear power plants which I, for one, am for. Given the advances that nuclear technology has made over the last few decades, nuclear energy is cleaner, safer, and more efficient than ever, not to mention the jobs constructing and maintaining new reactors will create. Split, baby, split! The Foxhole Atheist (talk) 18:42, 28 January 2010 (UTC) - What pisses me off is that he wants to slough it off onto congress. He could make that shit go away with the stroke of a pen, right? I can't wait for the first Faux News interview with some patriot who's just not patriotic enough to go to war alongside a homo. — Sincerely, Neveruse / Talk / Block 18:50, 28 January 2010 (UTC) - If you're talking about the DADT, the way I understand it is that it was legislation proposed by Bill Clinton and enacted by congress, which was then incorporated into the Uniform Code of Military Justice, which meant that appropriate statements had to be inserted in the appropriate Army regulations (and the other branches, as well) which takes an act of Congress to modify. So, Congress has to do it. The end. The Foxhole Atheist (talk) 19:02, 28 January 2010 (UTC) - And the fact that it originally was only a fairly minor change that was a half-arsed compromise is probably the only reason it got through Congress. The US should just give up Congress entirely, what exactly does it do apart from hamper the leadership of the country from making needed changes and preventing them doing anything positive with international relations? d hominem 19:05, 28 January 2010 (UTC) - What's really going to be interesting is seeing the conniption fits the officers and senior NCOs have when they have to rewrite AR 600-20 The Army Equal Opportunity Program. We already have to document quarterly training on race relations, Don't Ask Don't Tell, and sexual harrassment but this, the whole gay thing, is going to be a fucking hoot. If they rescind Don't Ask Don't Tell, I'm going to be sitting in an auditorium every 3 months listening to a freaking Command Sergeant Major have to go through the hows and whys of sexual orientation discrimination. The hardest part will be having to suffer all of the bad, muttered, dick, gay, and cornhole jokes, that I am sure you can all imagine coming from a bunch of Army scouts. This is going to be a bumpy ride! The Foxhole Atheist (talk) 19:56, 28 January 2010 (UTC) - Bahahaha. Nuclear power. I find nuclear power fucking hilarious. The means of power generation have not changed one bit since the Industrial Revolution! A nuclear reactor is little more than a fancier and more dangerous steam engine. All the nuclear power does is head water, to spin a turbine, to rotate a giant magnet in copper coils. It's literally no different than the power generation methods a century ago. That said, I'm all for it, provided we can find a nice spot to dispose of the waste beyond "dump it in a hole somewhere and hope for the best". --User:Theautocrat/Sig 03:21, 30 January 2010 (UTC) [edit] Shameless exageration — Sincerely, Neveruse / Talk / Block 18:54, 28 January 2010 (UTC) - Where did they even get that number?--Tom Moorefiat justitia 20:58, 28 January 2010 (UTC) - Another good one for a laugh is the [solutions.gop.gov Republican] health care site. At first look, they offer up a good deal. But nowhere do you find any details as to how they pull off their numbers, or what they would change to get the desired results. The childish name-calling and 'something for nothing' message also made me laugh. -- CodyH (talk) 05:48, 29 January 2010 (UTC) - If they really cared about saving money and not just using it as an anti-government wedge issue, we could stop occupying Middle Eastern countries, stop spending more on the military than the next nine nations combined, stop giving people a tax cut they don't need every three years, do something about social security and health care costs, and maybe we could actually regulate banks so we don't have to pay their debt off again. TKEtoolshedFrag Out! 01:23, 30 January 2010 (UTC) [edit] Atheists going to far I know its Faux but never mind the source. I think this is going to far personally. Its just a fucking stamp with Mother Teresa on it. Get over it, why care? It makes atheist look like bigots. Acei9 19:12, 28 January 2010 (UTC) - I don't think "too far" is the right way to describe it, because it implies that you could do something similar to this that isn't too far. It's just stupid in all ways. Though I do think they may have a point when they hint that they want to raise awareness of her "darker side". It's certainly true that, despite the title they rushed on her (for publicity, IMHO), like fuck was she a saint. And yeah, it's probably just Freedom From Religion trying to gather some publicity, but whining about this isn't the right way to do it. d hominem 19:22, 28 January 2010 (UTC) - My only real objection is that only a tiny number of people who were never US citizens have been honored on US Postage Stamps, and it's people like Winston Churchill (who was granted an honorary citizenship, anyway) and Columbus (who, of course, died before there was an America.) - The Postage Stamp criteria include these policies I think are relevant. - * It is a general policy that U.S. postage stamps and stationery primarily will feature American or American-related subjects. - * Stamps or stationery items shall not be issued to honor religious institutions or individuals whose principal achievements are associated with religious undertakings or beliefs. - So, Mother Teresa fails on the first category, since she was not an American, and her work was not primarily in America. That's just a "general policy", though, so that means its not a strict rule. The second one is tougher, since she's being honored for her good works, but those works were absolutely inspired by her religious beliefs. You could raise similar objections to Martin Luther King. - As for her darker side, if we eliminated everyone who had a darker side from consideration for stamps, the only stamps we'd have would feature the flag of the Liberty Bell. Heck, the one of the biggest selling stamps ever, if not the biggest, featured a guy who died of a drug overdose while sitting on the toilet. - And you probably couldn't find a stamp subject that someone wouldn't object to. - Yeah, this is probably the FFRF trying to get PR, like PETA's numerous stunts that they know will get no where, but gets them in the media. MDB (talk) 19:38, 28 January 2010 (UTC) - I think the issue with Teresa's "dark side" is that the vast majority of people don't know it exists - they genuinely think she "helped" people, when in reality her charity did no such thing, and even actively denied them help in the form of medicine, food or even social contact. All she did was let them die in squalor indoors rather than outdoors. Whereas on the other hand, we all know that Elvis was on a fuck load of pills and we know that politicians that appear on them would have started wars. - However, at least it's not as hilariously trivial as the complaints about Freddie Mercury when he was put on a stamp. UK stamp guidelines require that people featuring on stamps (apart from the Queen, obviously) are dead, and this photo of Freddie had the tiniest glimpse of Rodger Taylor's head poking out over the drum kit - the whole thing must have been less than a millimetre wide, but there was a minor outcry from stamp enthusiasts. d hominem 19:49, 28 January 2010 (UTC) - I heard such accusations about Mother Theresa on that absurd Penn and Teller's Bullshit show, but couldn't find much to back it up beyond some specious claims from Hitchens. Is there any real evidence for these claims?--Tom Moorefiat justitia 02:32, 29 January 2010 (UTC) - One yummy & honey(or marmalade) 02:57, 29 January 2010 (UTC) - Just reading around the web, MT's m.o. seems to have been to get as much money (what happened to the cash after she died?) as possible and then do nothing with it. The people she "saved" often died without any of the money being spent to cure or alleviate their symptoms, see here. She was self serving in that she apparently cared more for her own "salvation" than for the temporal care of those she "rescued". Whether she was good or bad in her own mind, she did little actual good for the slumdwellers of Calcutta. yummy & honey(or marmalade) 15:53, 29 January 2010 (UTC) [edit] A guy accused me of "heresy" because I know the bible better than him He was handing out tracts on my college campus. I decided to try to have a discussion with him. I pointed out, politely enough, that Jesus never personally condemned homosexuality, but did personally condemn charging interest, which means that his bank account is a sin. The fact that I had to get to class was the only thing that kept me from following him around the campus yelling "THIS MAN THINKS JESUS IS A HERETIC!"--Mustex (talk) 20:08, 28 January 2010 (UTC) - High five.--Thanatos (talk) 21:16, 28 January 2010 (UTC) - Well played. You should have continue to Luke 6:35 and asked the guy to loan you his wallet and car keys. -- Ask me about your mother 00:10, 29 January 2010 (UTC) - I wouldn't try that because I actually am a red letter christian (not associated with any organizations, but that's the best term for the way I view the bible), so I wasn't so much mocking him as saying what I actually believe. Granted, I do have an interest-yielding account, but I do believe that on some level it's wrong, but I think that relates to the imperfection of the world (personal view: if we were all perfect Christians we'd live in a socialist paradise, but since we're imperfect, we need capitalism to get by). That's the main reason I didn't ask him to sell me his daughter. (btw, I'm not trying to convert anyone, but I bring up the fact that I'm a Christian because it's relevant here, please don't bash me)--Mustex (talk) 00:14, 29 January 2010 (UTC) - As long as you don't push it on us. I'm proudly protestant but I am not a missionary. (personally, I hate those guys)--Thanatos (talk) 04:05, 29 January 2010 (UTC) - A little earlier in Christian history, people actually tried to follow Jesus's Red teachings a little more, which meant that — surprise, surprise! — it fell to the Jews, as the only non-Christians around, to keep the economy going. We all know what came of that. - Also, I believe that the provisions for daughter-sale were in the Mosaic civil law, which is not held to be binding today. ListenerXTalkerX 04:20, 29 January 2010 (UTC) - "A little earlier in Christian history, people actually tried to follow Jesus's Red teachings a little more" *Cough-bullshit-ahem*. A little earlier in Christian history, people did what they were told to do either by a tyrannical church or tyrannical land owners. A little earlier in Christian history, it was a feudal paradise (for those that had position and power) and the little people had no recourse to fight back. After all, there were no socialist / Christian-type laws to protect their rights. They lived the way they did because they already had no freedom. Bondurant (talk) 06:56, 29 January 2010 (UTC) - You're exaggerating almost to hyperbole, Lx. Can you support such a claim about Jews keeping the economy going? Because I think it's ludicrous.--Tom Moorefiat justitia 07:03, 29 January 2010 (UTC) - I'm not surprised. Most strong atheists from Arabic countries that have banned Bibles would know more about the actual contents of the book than most street preachers - who probably stick at "Evolution and gays are bad, Jeezus sez so". It's why stuff like the Conservative Bible Project exists, so they can change the content into what they think it says. d hominem 10:00, 29 January 2010 (UTC) - There were times and places where only Jews were allowed to lend money for interest. Non-Jews wanting to invest money had to do things like buying looms and renting them out to get round the ban on usury.-- Kriss AkabusiAAAWOOOGAAAR!!1 12:10, 29 January 2010 (UTC) - But those were times when economies were more land-based than capital-based. The Jewish bankers & traders were practising the only professions they weren't barred from. Some of them became very wealthy & influential, especially as money gradually came to be more important than land, but by that time any restrictions on Christians practising usury had largely been forgotten anyway. ₩€₳$€£ΘĪÐ Methinks it is a Weasel 19:28, 29 January 2010 (UTC) - But the anti-usury restrictions started them in that business, which gave rise the later stereotypes. Also, even at that time capital was needed for many things, financing buildings, etc. (the Protestant Reformation was sparked off by a need to raise capital for the building of a cathedral). ListenerXTalkerX 19:35, 29 January 2010 (UTC) - This actually ties back into what I was saying about people being imperfect. In a perfect world, we wouldn't need interest as a motivator to loan money to people who needed it (btw, once again, I'm trying to clarify my beliefs because it's relevant to the discussion, not convert people).--Mustex (talk) 15:19, 29 January 2010 (UTC) - If you feel interest accounts are wrong somehow (I can certainly understand that) you could switch to one of the microloan/ethical banks. I only know Triodos well, but wikipedia tells me there are others in the US. — Pietrow ☏ 17:19, 29 January 2010 (UTC) - I actually had a talk with a friend last night who convinced me that since bank interest is lower than inflation, it isn't actually true "interest," since I'm not really making a profit.--Mustex (talk) 19:12, 29 January 2010 (UTC) - You also need to take into account the risk you're taking of losing your principle entirely. This place had been advertising on TV recently, and they claim a 98% repayment rate, so you would need to make 2% on each loan just to break even over time (before inflation and taxes). --Mustex (talk) 03:30, 30 January 2010 (UTC) [edit] How to report the news Most of you might have seen this already, but it's funny: — Sincerely, Neveruse / Talk / Block 20:26, 28 January 2010 (UTC) - His name's Charlie Brooker, not Chris Booker. CrundyTalk nerdy to me 20:29, 28 January 2010 (UTC) - Keep in mind that the people who run break.com are complete idiots. — Sincerely, Neveruse / Talk / Block 20:31, 28 January 2010 (UTC) - It's worth checking out Brass Eye and The Day Today. It's along the same lines as that short. -- Ask me about your mother 23:57, 28 January 2010 (UTC) - Charlie Brooker isn't a 'BBC Reporter' either - he's a comedy writer and broadcaster basically - his mainstay is TV and Game reviews, albeit in a very hard-edged way. He's a bit of a Clarkson - he can be very funny, but he can also be an opinionated ass. He's pretty reliably funny though. --Worm(t | c) 00:42, 29 January 2010 (UTC) - He also wrote the excellent Jan Moir takedown after her "unnatural death" column. --Arcan ¡ollǝɥ 09:36, 29 January 2010 (UTC) - This one Jack Hughes (talk) 09:45, 29 January 2010 (UTC) - I liked his program about computer games as well. Esp. the bit about the new Wolfenstein game: "Most of the game you spend back tracing your steps, running around a horrible, broken down town looking for jobs to do. It's like living in Stoke." CrundyTalk nerdy to me 00:33, 30 January 2010 (UTC) [edit] Only Connect (Bump) Does anyone watch this on BBC4? A few friends of mine are on tonight - although I'm not going to say which team, but it may be fairly obvious. ArmondikoV...I'll jostle your chisel! 19:21, 25 January 2010 (UTC) - I hope it wasn't the "Philosophers" - anyone who can't identify the Spanish Inquisition sketch is not worthy of bein called a friend. yummy & honey(or marmalade) 02:48, 29 January 2010 (UTC) - I love the "Philosophers," although my all-time favorite is the "Four Yorkshiremen." Tetronian you're clueless 02:59, 29 January 2010 (UTC) - Remember - the Four Yorkshiremen is not python. Jack Hughes (talk) 09:49, 29 January 2010 (UTC) - Are you sure? I recently watched "Live at the Hollywood Bowl" and they did it there. Tetronian you're clueless 03:33, 30 January 2010 (UTC) - Well, the other team were nerds. Apparently Tom had it at "fear", but then again, he did dress as the Spanish Inquisition to a Good v. Evil themed party. d hominem 09:50, 29 January 2010 (UTC) [edit] Scare Tactics? This was passed by my inbox by a friend of mine. Interesting find, with some definite impact in today's political climate. It gives us something to watch for, at any rate. -- CodyH (talk) 06:15, 29 January 2010 (UTC) - I remember that popping up on WIGO World a while back. It seems to explain everything. Although I'm not sure if they've identified cause and effect. I.e., are the more jumpy likely to be conservative or does being conservative make you more jumpy? d hominem 09:52, 29 January 2010 (UTC) - They definitely act more jumpy: scared of terrorists, scared of poor Mexicans, scared of bureaucrats, scared of ACORN, scared of everything that isn't the embodiment of Reagan TKEtoolshedFrag Out! 01:11, 30 January 2010 (UTC) [edit] So.... more teleprompter jokes? Or maybe not since Obama took questions parliamentary-style from the House GOP Caucus for more than an hour and, hm, won the debate according to most accounts. Debating a law prof, not a good idea... WodewickWelease Wodewick! 01:16, 30 January 2010 (UTC) - Hearing his responses to them, I upgrade him from C+/B- to a solid B+. The man is playing chess, after all. Now to take it to the national stage. ħuman 03:59, 30 January 2010 (UTC) [edit] BSG/CGS joint abstracts Anyone want to submit an abstract to the Baraminology Study Group-Creation Geology Society joint conference. [4] It might be a good time! Georgia in July.... Šţěŗĭļė ramen noodle 03:15, 30 January 2010 (UTC) [edit] The Daily Show (UK) For British viewers - The Daily Show with Jon Stewart is now availble on MORE4 at 20:30. Lily Inspirate me. 20:10, 29 January 2010 (UTC) - Err.. it has been for ages. yummy & honey(or marmalade) 20:12, 29 January 2010 (UTC) - Crikes, what a silly bunt. I'm getting confused with The Colbert Report. Lily Inspirate me. 10:17, 30 January 2010 (UTC) [edit] Nobu Holy fuck! It was tehmizzus' solicitor qualification day in that London today at the Law Society. Afterwards we'd thought we'd have a nice Japanese meal at Nobu. Now don't get me wrong, excellent meal, nice setting, and I got to walk past the broom cupboard where Boris Becker fucked a waitress and got her up the duff, but what the FUCK? £160 for a meal for two? Holy fucking shit. CrundyTalk nerdy to me 23:18, 29 January 2010 (UTC) - That is really steep. I once paid $180US for a meal for 2 at a steakhouse in Indiana. Best damn steak I ever had, but damn! Aboriginal Noise with 4 M's and a silent Q 23:27, 29 January 2010 (UTC) - Took a picture. CrundyTalk nerdy to me 23:29, 29 January 2010 (UTC) - Has anyone ever told you that you vaguely resemble a vampire? Mindless cubic Hoover! 00:07, 30 January 2010 (UTC) - I do look remarkably like an anaemic vampire when I stand next to the wife. CrundyTalk nerdy to me 00:13, 30 January 2010 (UTC) - (A chubby anaemic vampire) CrundyTalk nerdy to me 00:14, 30 January 2010 (UTC) - You could be a young Grandpa Munster. ₩€₳$€£ΘĪÐ Methinks it is a Weasel 01:06, 30 January 2010 (UTC) - George Costanza.--Tom Moorefiat justitia 01:07, 30 January 2010 (UTC) Wow, I've had a couple of $100/two meals (washed one down with a $20 shot of Scotch... mmmmmm), hard to imagine how to get even better food. Although Japanese does imply what can be very expensive raw fish, right? Oh, and were cocktails and wine included in that figure? Glad you enjoyed it, anyway! ħuman 01:32, 30 January 2010 (UTC) - What scotch are you buying at $20 a shot? Better be damn good. Ardbeg 25 y.o.? Actually, that's probably more then 20. DickTurpis (talk) 05:13, 30 January 2010 (UTC) - MacCallan (?) 18. Very good. I asked, after dinner was mostly over, if they had a "Scotch list". They did. ħuman 05:19, 30 January 2010 (UTC) - That's odd, that picture makes me look at more bald than I actually am. I'm gonna find a better picture. CrundyTalk nerdy to me 18:43, 30 January 2010 (UTC) - Hmm, not much better. But at least it'll fuck up RWW's claim that I'm a shortarse. CrundyTalk nerdy to me 20:48, 30 January 2010 (UTC) [edit] Block everyone permanently! It would certainly clear up some strife. ħuman 04:08, 30 January 2010 (UTC) - You're just trying to evade your own comeuppance, sinner! --Kels (talk) 05:02, 30 January 2010 (UTC) - I was just trying to spread the love, is all. ħuman 11:33, 30 January 2010 (UTC) - Maybe just for a month or so. ₩€₳$€£ΘĪÐ Methinks it is a Weasel 15:48, 30 January 2010 (UTC) [edit] Mars rover I might be a soppy old fart, but somehow the story of the little Mars rover finally coming to rest after 6 years really touched me. I loved how it managed to cover a whole 12 miles during that time. As always XKCD delivers. --PsygremlinPrata! 08:47, 30 January 2010 (UTC) - Oh no, really? Love that little robot that could. I don't think they were going to stop it after 3 months, I don't think they were expecting it to keep working any longer than that. Wasn't part of it busted that is why it could not travel very fast? - π 09:02, 30 January 2010 (UTC) - Aw, that was a really sweet xkcd. Nice robot, we'll send you a friend soon ;) ħuman 09:10, 30 January 2010 (UTC) - Didn't have a friend that never worked? Whilst robot exploration maybe cheaper, humans have the distinct advantage that they can fix thing when they break. - π 09:18, 30 January 2010 (UTC) - Or they die... they can only fix things if they have the tools, the spare parts, and the skills and time (and oxygen, water, and food). The little robot that could, on the other hand, far "outlived" its expectancy. And those rovers hooked a whole new generation of kids and adults on the heroin that is pictures from Mars. ħuman 09:37, 30 January 2010 (UTC) - True, if they are serious about doing a round trip to Mars with humans, they are going to have to consider what to do if anyone dies out there. Up until now we have never gone more than a week away from Earth, but a trip to Mars and back is going to take over 6 months. I suspect nobody will mention the fact that they would be taking body bags with them. - π 10:06, 30 January 2010 (UTC) - Mars? Schmars! It's Phobos we should be going to. Totnesmartin (talk) 11:02, 30 January 2010 (UTC) - I thought a Mars trip would run two years - at a minimum round trip, Pi. I might be wrong of course. ħuman 11:26, 30 January 2010 (UTC) - Two years = over 6 months. No? yummy & honey(or marmalade) 13:18, 30 January 2010 (UTC) - Having checked it takes about 214 days to get there, so it will probably be closer to 3 years the mission. Having a very quick read they have to do all this fancy stuff of aiming for when the planets are closest, 1 Mars year being about 1.8 Earth years. - π 13:34, 30 January 2010 (UTC) - So more like 3 yearish, yeah. Tough part is both launch windows are constrained by the orbits - meaning the "visit" length can't just be picked for convenience. I imagine someone has a nice table somewhere of all the "possible" sets of journey dates with the total elapsed time and visit lengths... somewhere? ħuman 00:48, 31 January 2010 (UTC) - Fuck the rovers, lets send an ape. Acei9 00:49, 31 January 2010 (UTC) - Cats, lots of cats. Send all of them up there. -- Ask me about your mother 02:02, 31 January 2010 (UTC) - I say send 'em a "life bomb" - a bunch of bacteria that thrive in anaerobic, arid, iron-rich environments, and as many virii as we can find that parasitise them. I, for one, will welcome our Martian overlords when they evolve and develop spacecraft in 3 billion years. ħuman 05:10, 31 January 2010 (UTC) [edit] PZ Is coming to UK. Where & when? Anyone know? yummy & honey(or marmalade) 13:33, 30 January 2010 (UTC) - I refuse to read the article on scholarly grounds. Mindless cubic Hoover! 14:05, 30 January 2010 (UTC) [edit] An Attempt at Humor -- Li'l Andy Schlafly in Elementary School I was contemplating this on the way to work this morning... Li'l Andy Schlafly in Elementary School [edit] Li'l Andy Gets His Arithmetic Homework Back Li'l Andy: Miss Hoover, you said I got this answer wrong. Teacher (with the exasperated patience of someone who knows what's coming): Well, Andy, you said two times three is twenty three, but the correct answer is six. Li'l Andy: You're a liberal dis... dess... dis-see... liar! Liar liar pants on fire! Teacher: Andy, this is math. There's only right or wrong answers. Liberal has nothing to do with this. If you talk to your friends (sotto voce if you have any) they'll all tell you that the answer is six. Li'l Andy: The girls won't. Teacher: Excuse me? Li'l Andy: Everybody knows girls can't do as well in math as boys! Teacher: Children! Time for recess! I have a headache and I'm going to the lounge to lie down. [edit] Li'l Andy on the Playground Teacher: Children, we don't have enough balls for everyone, so you'll have to take turns and share. Li'l Andy: No! That's naughty! Teacher: Andy, sharing with other people is the nice thing to do. It's not naughty! Li'l Andy: Sharing is socialism! Teacher resigned and exasperated: Fine, Andy. Here's a ball. Go play there in the corner by yourself (sotto voce like always...) [edit] Li'l Andy Asks his Teacher a Personal Question Li'l Andy: Miss Hoover, what's it like where you come from? Teacher: I live near here, Andy. You know what its like. Li'l Andy: That's not what Mommy said before she left for her speaking tour. Teacher (wary): Oh, really? Li'l Andy: She said that you're a Lebanese. Teacher (completely befuddled): What... why... how did she get that idea? I have blonde hair and blue eyes. Li'l Andy: Mommy said that any woman your age who doesn't have a husband has to be a Lebanese. Something like that, at least. Teacher: Class! Starting tomorrow, you'll have a new teacher. I'm going back to school to learn to do something else. Anything else. — Unsigned, by: MDB / talk / contribs Fun Page created: --Mustex (talk) 02:37, 1 February 2010 (UTC) [edit] Howard Zinn, 1922-2010 Unfortunately, my favorite historian, Howard Zinn, died today as a result of a heart attack. If nobody is familiar with his work, he is the author of The Peoples' History of the Unites States, as well as other historical works where he tries to present history from points of view "other than that of dead, rich, white guys." He was also a radical, non-violent activist, being active in political movements since he was 17. He will be sorely missed. Gooniepunk2010 Oi! Oi! Oi! 22:42, 29 January 2010 (UTC) - I read People's History some years ago, and the graphic novel version not long after it was released. I can't say I'm in agreement with Zinn on all his points, but he was certainly thought provoking. MDB (talk) 23:46, 29 January 2010 (UTC) - RED!!1 RED!!1!! REDREDREDREDREDREDREDREDREDRED!!!11!!1 TheoryOfPractice (talk) 23:46, 29 January 2010 (UTC) - Hahahaha, LX, you're funny :) ħuman 01:26, 30 January 2010 (UTC) No, LX, history is not about "chronicling facts." That would be remarkably boring. History--good history, at least--is about interpreting and finding meaning in those "facts." TheoryOfPractice (talk) 14:47, 30 January 2010 (UTC) - Says Karl Marx. Me, I prefer facts to what some historian or other plucks out of the air. But, I am a scientist rather than an historian, so I am probably badly biased in that respect. ListenerXTalkerX 01:40, 31 January 2010 (UTC) - You should prolly stick to the lab, in that case. It's pretty obvious that your average Honours undergrad at any decent History department understands the discipline much better than you do. The first question one is typically asked after reading a monograph or article is: "What was the author's argument?" i.e. given the historical facts that the author is interpreting, what conclusions does she come to/what meaning does she find in them/what broader claims about the world does she make? To give an example from a project I just finished: We all know that Haiti gained its independence in 1804. not a lot more "fact chronicling" to do there--but what can the events that we've known about for decades tell us about such things as the universalization of Enlightenment discourses about human rights (especially if we think about how slave/colinized labour played a crucial role in underwriting the enlightenment) or how elites managed the shift from slave labour to free labour--what did "freedom" mean to both the former slaves in a time of changing ideas about the state and citizenship? That's not chronicling facts, it's looking at the same old facts with new ideas/insights/conceptual apparatuses. That's what historians do. TheoryOfPractice (talk) 01:48, 31 January 2010 (UTC) - Thank you for the explanation, but this discipline sounds to me like a whole lot of speculation. Which, especially when it is made in conformance with rigidly held dogmas, gives rise to historical revisionism when inconvenient facts pop up to contradict the speculations. - Question. Why is it that when I took a university class in history, it was all about the interpretation with facts playing second fiddle, but when I attend lectures in local history (a hobby of mine) it is barely any interpretation and all facts? ListenerXTalkerX 02:22, 31 January 2010 (UTC) - 1. It IS a lot of speculation. INFORMED speculation.But it's not just Marxist/leftist historians who do this--it's the standard appraoch for any decent practitioner, regardless of their politics. Don't believe me? Read someone like Niall Ferguson or Gertrude Himmelfarb. 2. Maybe you're just going to talks by people who don't do exciting work--or maybe you're so focused on the narrative/the "facts" that you're not listening for the argument as it's being developed. Some people are less explicit than others with their arguments. And there's nothing wrong with revisionism--I mean, new knowledge is created in labs alla time, right? Revising our understanding about the physical world, right? The past is no different in that regard. Where history is different is that meaning is subjective, even if the "facts" are indisputable. One event can have multiple meanings--historians these days are about finding the meanings and contexts that were less likely to make it into the official record because the official record was kept by certain types of people. TheoryOfPractice (talk) 02:31, 31 January 2010 (UTC) - I did not say it was just the left-wingers who do it, but is Marx not the one who came up with that whole idea of a specific common theme or narrative underlying the whole of history? - "Maybe you're just going to talks by people who don't do exciting work..." They do tend to work for the Historical Society rather than the University, which is a different kettle of fish. I find their work very exciting, despite the comparative lack of arguments (there is little room to make arguments when you are trying to, for example, chronicle the history of locks-and-dams in the MNRRA). - "And there's nothing wrong with revisionism..." I beg to differ. The equivalent of revisionism in science is creationism: denying facts that fail to fit the mold and making up entirely new ones. ListenerXTalkerX 03:59, 31 January 2010 (UTC) 1.The idea of a common theme unifying history goes way further back than Marx--the Whig idea of history as an inexorable march toward progress and enlightenment finding its greatest expression in Britain's history dated to the early 18th century. A talk about locks and dams might have really important arguments lurking in it--for whose benefit were the dams built? Who got to decide where the canals went and where got left out of the trade the canals facilitated? 3. That's not what historical revisionism is. Nobody--at least nobody with any intellectual honesty--is denying facts that don't fit the mold or "making up new ones." What we're doing is interrogating sources in new ways to see how they can help us understand the people who didn't/couldn't leave the same wealth of records behind, and then asking how the new understandings and contexts that we get from that can help us understand the past in more complex ways. TheoryOfPractice (talk) 04:13, 31 January 2010 (UTC) - (1) But was that just Whig politicians speechifying, or was it historians doing Exciting Work? - (2) Both those questions were answered in the talk — with facts. - (3) I was using the colloquial definition, covering stuff like Holocaust and Holodomor denial. As to the other definition, I have no problem with that, so long as one is only dealing on newly revealed facts and not regarding mythology as historically accurate. ListenerXTalkerX 06:31, 31 January 2010 (UTC) - 1. That was historians--or what passed as "historians," as the discipline wasn't really professionalized until Ranke--understanding how history had and was unfolding--as part of a unified, teleological movement. 2. Facts is how we answer questions, no doubt. But someone else may look at the same facts and find different meaning. We're talking about human experience, not physics. 3. TL/DR. Will read the article in the morning and talk more then. TheoryOfPractice (talk) 06:41, 31 January 2010 (UTC) - (1) "...the discipline wasn't really professionalized until Ranke..." Huh? - (2) As in (gross simplification here) "These locks were a great leap forward as they opened up the Mississippi to navigation above St. Anthony Falls" vs. "These locks were a foolhardy move as they caused ecological disruption"? ListenerXTalkerX 07:06, 31 January 2010 (UTC) [edit] O'Keefe's case Think his latest actions will affect his current lawsuit with ACORN? Personally, I do not like this guy. He does these stunts (no one ever mentions his planned parenting videos) and gets heralded as a hero by the conservatives. There are ethics in journalism and this douchebag disregards them to attack his enemies.--Thanatos (talk) 02:30, 31 January 2010 (UTC) - On the other hand, the people who exposed COINTELPRO were drooled over by the other side. Sometimes muckrakers of whatever political persuasion have to stretch the rules. ListenerXTalkerX 03:30, 31 January 2010 (UTC) - Thanks for pointing that out, really having a hard time trying to differentiate the two. I just see this guy making a career out this, but really hard to go after him with my previous zeal after reading that. Would "It was a different era" be adequate?--Thanatos (talk) 03:50, 31 January 2010 (UTC) - My position is that the truth usually hurts no one except wrongdoers. If the people in Mr. O'Keefe's videos are doing nothing wrong and the videos portray them accurately (i.e., no creative editing), there is little issue to speak of. ListenerXTalkerX 04:12, 31 January 2010 (UTC) - Part of me thinks that he is now the villain because he got caught this time, like Watergate. If he hadn't, he would have again the pubs golden boy. He did break the law with the ACORN videos, which they claim were edited. They are now asking questions about his tactics --Thanatos (talk) 23:17, 31 January 2010 (UTC) - That is absolutely why they're the villains and what makes them different from the people who broke into the FBI. Neither action is right, but the latter is a lot more justifiable because it actually uncovered and stopped other injustices. Just like shooting someone committing a crime is still wrong, but it's less wrong than shooting someone who is innocent.-- (talk) 02:49, 1 February 2010 (UTC) - I go with the rules of being an undercover cop. They are there to witness the crime, but they cannot commit a crime or the investigation is thrown out. For example, cop infiltrating a biker gang is told to do drugs to prove his loyalty. That was from the guy who infiltrated the Mongols :)--Thanatos (talk) 03:40, 1 February 2010 (UTC) [edit] Generating tables for side-by-side articles I'm fairly lazy, so I've been looking at a way to generate side by side tables by just feeding in the text and letting the process of table generation be automated. Has anyone done this thing before? So far I just have a rough prototype working in Excel, but if it's useful I can knock together a PHP or C version of it. In theory I could add a script that'll convert an existing table in to regular text for importing in to this script. Might make it easier to make large scale changes to side-by-side content. -- Ask me about your mother 12:50, 31 January 2010 (UTC) - There's a template here, I think Template:sbs. If I remember right, there are other related ones, too. Šţěŗĭļė ramen noodle 12:52, 31 January 2010 (UTC) - (EC)I did it once in perl and it took a long time. You do know about Template:sbs? - π 12:54, 31 January 2010 (UTC) - Well obviously you do now. - π 12:55, 31 January 2010 (UTC) - Ta, I'd forgotten about that template. That makes life a bit easier. -- Ask me about your mother 13:00, 31 January 2010 (UTC) - There's also this. Dunno how well it works. yummy & honey(or marmalade) 13:32, 31 January 2010 (UTC) [edit] Expression error: Unrecognised word "expression" That's what it says on Recent Changes where the Holydaze is supposed to go. TheoryOfPractice (talk) 15:02, 31 January 2010 (UTC) I see it too. Anyone know how to fix it? Tetronian you're clueless 15:03, 31 January 2010 (UTC)Thanks Nx! Tetronian you're clueless 15:05, 31 January 2010 (UTC) [edit] Voting against your own interests I think this piece is an interesting read. Tetronian you're clueless 03:31, 30 January 2010 (UTC) - The reason that people vote "against their own interests" is because they are too stupid to realize that they think exactly how, oh, say, a journalist in a country 1,000+ miles away believes they should think. ListenerXTalkerX 04:21, 30 January 2010 (UTC) - Come on, Listener, accept it. You're against this article because state healthcare is Red. Mindless cubic Hoover! 09:01, 30 January 2010 (UTC) - I was going to link people to that :( EddyP (talk) 10:59, 30 January 2010 (UTC) - I do not think public health care is a communist idea at all. On the other hand, I think that telling the masses what exactly their interests are, particularly when said interests conform to the teller's favored political program, is at heart a communist idea. ListenerXTalkerX 01:30, 31 January 2010 (UTC) - Because REAL Conservatives, like say, Ronald Reagan, would NEVER try to coerce people into behaving "for their own good" in some stupid way, like jailing them for taking unapproved drugs, right? --Gulik (talk) 08:40, 1 February 2010 (UTC) - Actually, LX, a true Communist society wouldn't have to tell people what their best interest is. The people would realize that they all contribute something valuable and nobody would have to be in charge. SirChuckBCall the FBI 08:42, 1 February 2010 (UTC) [edit] Cause & Effect Do animals (cats actually) understand cause and effect? During the recent cold weather our cats would spontaneously (apparently) both move to positions on, or nearly on, top of a CH radiator. It was some time before we realised that they were doing this after the boiler in the kitchen struck up but before the warm water reached the particular radiator. Do the cats understand cause & effect? Must ask Mr Pavlov. yummy & honey(or marmalade) 13:11, 30 January 2010 (UTC) - I would assume they would. Cause and effect refers to learned behaviour, no? Most, if not all mammals learn, so my guess would be they should. SJ Debaser 13:13, 30 January 2010 (UTC) - Yes and no. Your cat obviously realise that after boiler struck up warmth would soon becoming out the radiator, but it probably does assume one causes the other, only the chronological list of events it expects. 13:26, 30 January 2010 (UTC) - Premuse you meant "... does not assume ...", Pi. yummy & honey(or marmalade) 13:33, 30 January 2010 (UTC) - I'd imagine it's like Pavlov's dogs - they will learn to associate the noise of the boiler (or the gurgling in the pipes) with the radiators heating up. CS Miller (talk) 22:42, 1 February 2010 (UTC) [edit] Nutters came across this on Flickr. People are mad. yummy & honey(or marmalade) 14:31, 31 January 2010 (UTC) - Getting hot women in bikinis to jump into cold water to extend their Bruce Lee's is mad? CrundyTalk nerdy to me 21:41, 31 January 2010 (UTC) - Being a (hot) woman, getting into a bikini and jumping into cold water is mad. yummy & honey(or marmalade) 14:10, 1 February 2010 (UTC) - Way to disempower the sisterhood, Crundy.-- Kriss AkabusiAAAWOOOGAAAR!!1 15:40, 1 February 2010 (UTC) - How so, by pointing out the awesomeness of women in bikinis, or by using the cockney slang term "Bruce Lee"? CrundyTalk nerdy to me 15:43, 1 February 2010 (UTC) [edit] Vindaloo Mmm. I've discovered a great new way to make a classic Portugese-Goan Vindaloo. You marinade pork (shoulder & a little belly) in spices, chillis, garlic, ginger and white wine vinegar for a few hours (obviously days if you want to make it authentic). Fry a chopped onion, add the marinated mix, and then cover and simmmer for about 40 mins (msg me for recipe). The trouble is, the juices from the meat need to be retained, but they tend to boil off. Traditionally people would put a plate of water on top of the pan to cool the steam back (refluxing) and add a bit of extra water if it runs dry. I've found a better way. You put ice cubes into into a ziplock back and put it on the pan lid (fig 1). A bag of ice lasts about 30 mins and then you need to boil off the excess liquid anyway (fig 2). Don't ask me where I learnt this little reflux trick! CrundyTalk nerdy to me 21:40, 31 January 2010 (UTC) - Hope you've not bought the ice at M&S (made from Irish water! yummy & honey(or marmalade) 21:45, 31 January 2010 (UTC) - What? No! I have an American style fridge that makes my ice for me :) CrundyTalk nerdy to me 21:46, 31 January 2010 (UTC) - Write a recipe!--Tom Moorefiat justitia 21:50, 31 January 2010 (UTC) - Erm, it's meat, Tom. I don't think it would work with any veggie alternatives because the amount of fat and juices would be too low. Oh, speaking of which, about to post something on yr talk page. CrundyTalk nerdy to me 21:57, 31 January 2010 (UTC) - Well, yeah, but other people might like the recipe. I love that namespace is all.--Tom Moorefiat justitia 22:01, 31 January 2010 (UTC) - Do we still have the namespace? Is it "Food"? CrundyTalk nerdy to me 22:02, 31 January 2010 (UTC) - It's Recipe. Like this!--Tom Moorefiat justitia 22:17, 31 January 2010 (UTC) - Page creator is here.--Tom Moorefiat justitia 22:18, 31 January 2010 (UTC) - Crundy, that is a damn clever idea. -- Ask me about your mother 22:20, 31 January 2010 (UTC) - Recipe here CrundyTalk nerdy to me 15:20, 1 February 2010 (UTC) [edit] Rock and Chips... ...any UKians see it? It was the hour and a half prequel to Only Fools and Horses that aired last week. I watched it this evening avec ma famille. It was pretty shit, they labelled it as a drama rather than a comedy which is what we all know and love Only Fools for, but it was interesting to watch nonetheless. SJ Debaser 00:15, 1 February 2010 (UTC) - I've given up watching any of the spinoffs / specials of OFAH, they're always fucking shit. CrundyTalk nerdy to me 10:31, 1 February 2010 (UTC)
http://rationalwiki.org/wiki/RationalWiki:Saloon_bar/Archive49
CC-MAIN-2013-20
refinedweb
23,474
70.63
Chatlog 2010-04-15 From RDFa Working Group Wiki See CommonScribe Control Panel, original RRSAgent log and preview nicely formatted version. 13:50:28 <RRSAgent> RRSAgent has joined #rdfa 13:50:28 <RRSAgent> logging to 13:50:43 <manu> trackbot, start meeting 13:50:46 <trackbot> RRSAgent, make logs world 13:50:48 <trackbot> Zakim, this will be 7332 13:50:48 <Zakim> ok, trackbot; I see SW_RDFa()10:00AM scheduled to start in 10 minutes 13:50:49 <trackbot> Meeting: RDFa Working Group Teleconference 13:50:49 <trackbot> Date: 15 April 2010 13:51:35 <manu> Present: Ivan, Steven, MarkB, Manu, Benjamin, Knud, Shane 13:51:41 <manu> Regrets: BenA, Toby 13:51:43 <manu> Chair: Manu 13:52:12 <manu> rrsagent, make logs public 13:53:24 <markbirbeck> markbirbeck has joined #rdfa 13:58:54 <Zakim> SW_RDFa()10:00AM has now started 13:59:01 <Zakim> +Benjamin 13:59:38 <Zakim> +??P9 13:59:48 <manu> zakim, I am ??P9 13:59:48 <Zakim> +manu; got it 14:00:17 <ivan> zakim, dial ivan-voip 14:00:17 <Zakim> ok, ivan; the call is being made 14:00:18 <Zakim> +Ivan 14:00:37 <ShaneM> ShaneM has joined #rdfa 14:01:15 <markbirbeck> zakim, code? 14:01:16 <Zakim> the conference code is 7332 (tel:+1.617.761.6200 tel:+33.4.89.06.34.99 tel:+44.117.370.6152), markbirbeck 14:01:27 <Knud> Knud has joined #rdfa 14:01:49 <Zakim> +knud 14:01:56 <Zakim> +markbirbeck 14:02:21 <Steven> zakim, dial steven-617 14:02:21 <Zakim> ok, Steven; the call is being made 14:02:22 <Zakim> +Steven 14:03:15 <manu> Agenda: 14:03:31 <Zakim> +ShaneM 14:04:08 <manu> scribenick: ivan 14:04:42 <ivan> Topic: Resolutions on FPWD Items 14:04:56 <ivan> manu: a couple of resolutions should be on records, 14:05:02 <ivan> ... get the issues closed 14:05:12 <ivan> ... and have a resolution on getting fpwd-s 14:05:27 <manu> 14:05:28 <ivan> manu: we had a poll that we did not record 14:05:41 <Knud> zakim, mute me 14:05:41 <Zakim> knud should now be muted 14:05:44 <ivan> manu: this covered the four items that had a wide agreement 14:05:53 <ivan> ... first: supporting of @profiles 14:06:13 <ivan> ... looking at it there were 2 against, we covered their reasons 14:06:21 <ivan> ... we should not rehash that 14:06:36 <manu> PROPOSAL: Support the general concept of RDFa Profiles - an external document that specifies keywords for CURIEs. 14:07:29 <ivan> ivan: +1 14:07:38 <manu> +1 14:07:38 <Benjamin> +1 14:07:41 <Knud> +1 14:07:47 <Steven> +1 14:07:50 <markbirbeck> +1 14:07:56 <Steven> This is not a vote - it's a straw poll that demonstrates rough consensus among the RDFa WG. 14:07:57 <ShaneM> +1 14:08:09 <manu> RESOLVED: Support the general concept of RDFa Profiles - an external document that specifies keywords for CURIEs. 14:08:38 <manu> PROPOSAL: Support the concept of having a default prefix mechanism without RDFS resolution. 14:08:41 <ivan> ivan: +1 14:08:50 <manu> +1 14:08:50 <Benjamin> +1 14:08:51 <Knud> +1 14:08:55 <Steven> +1 14:08:59 <markbirbeck> +1 14:09:16 <ShaneM> +1 14:09:26 <manu> RESOLVED: Support the concept of having a default prefix mechanism without RDFS resolution. 14:10:09 <manu> PROPOSAL: Support expressing the RDFa Profile document in RDFa (for example: rdfa:prefix/rdfa:keyword, or rdfa:alias) 14:10:16 <ivan> ivan: +1 14:10:18 <Steven> +1 14:10:19 <manu> +1 14:10:23 <Benjamin> +1 14:10:32 <Knud> +1 14:11:12 <ShaneM> +1 14:11:13 <markbirbeck> -1 14:12:19 <ivan> steven: mark, do you oppose this proposal? 14:12:37 <ivan> mark: I would be fine if we changed it to 'one of the possible mechanism would be rdfa' 14:12:49 <ivan> ... I think we can still have that discussion 14:13:10 <ivan> manu: we had a bit of discussions with that wording and we had a general discussion based on that - we don't want to change the proposal at this point because there is wide agreement to this wording and it could impact FPWD. 14:13:22 <ivan> ... looking at the proposal and the +1-s I would resolve it and we can have a discussion at a later stage 14:13:25 <manu> RESOLVED: Support expressing the RDFa Profile document in RDFa (for example: rdfa:prefix/rdfa:keyword, or rdfa:alias) 14:14:12 <manu> PROPOSAL: Provide an alternate mechanism to express mappings that does not depend on xmlns: (for example: @token, @vocab or @map) 14:14:20 <ivan> ivan: +1 14:14:25 <manu> +1 14:14:26 <Benjamin> +1 14:14:29 <Knud> +1 14:14:32 <Steven> -1 14:14:32 <markbirbeck> +1 14:14:50 <ivan> ivan: same question to steven... does he oppose or can live with it? 14:15:18 <ivan> steven: I was not sure whether I should say -1 or 0, an alternate means 'as well as' 14:15:27 <ShaneM> +1 14:15:27 <ivan> manu: this is really for languages without @xmlns: 14:15:52 <ivan> ... and whether or not namespaces exist in html5 at the conceptual level is debatable, but the WHATWG folks are claiming so 14:16:03 <ivan> ... the vast majority of our arguments over namespaces and @xmlns: (RDFa doesn't require either) revolved around that 14:16:14 <ivan> ... we want RDFa to be used in languages that do not have @xmlns: or namespaced elements 14:16:20 <ivan> ... for those languages, @prefix makes more sense than @xmlns: 14:16:21 <ShaneM> Moreover using xmlns pollutes the namespaces of a parser unnecessarily. 14:16:40 <ivan> Steven: I do not agree that html5 does not fall into this category 14:16:43 <ivan> q+ 14:16:48 <manu> ack ivan 14:17:58 <manu> RESOLVED: Provide an alternate mechanism to express mappings that does not depend on xmlns: (for example: @token, @vocab or @map) 14:18:12 <ivan> ivan: What about deprecating @xmlns:? 14:18:19 <manu> Topic: Deprecation of @xmlns: in RDFa 1.1 14:18:21 <ivan> ... it is in the current version of RDFa Core 14:18:42 <manu> +1 for deprecation of xmlns: 14:18:49 <Steven> -1 for deprecation 14:18:50 <manu> Ivan: I can live with deprecation of xmlns: 14:19:08 <manu> Ivan: we need a resolution for this if we are going to have it in RDFa Core 1.1 FPWD 14:19:16 <ivan> shane: I did this offline, asked Manu, he agreed and we added the text in there 14:19:32 <ivan> ... I agree that this should be discussed by the WG 14:19:38 <ivan> ... since having two is confusing 14:19:53 <ivan> manu: the reason I thought we would be going this direction is because we've had this discussion before in RDFa WG - Whether or not to deprecate xmlns: 14:20:02 <ivan> ... the issue is confusing - having two equal prefixing mechanisms 14:20:09 <ivan> ... we've also talked about the namespace issues - how RDFa doesn't need namespaces and how using xmlns: confuses a great number of people. 14:20:10 <Steven> I disagree more strongly on this one than the last 14:20:20 <ivan> ... If we had known what we know now about the confusion xmlns: creates in regular web developers. Some people still think that RDFa requires namespaces (even though RDFa doesn't require namespaces). Back in RDFa 1.0, when we re-used xmlns:, we would have probably defined a new attribute instead of re-using @xmlns: if we know what we know now (which is impossible)... looks like we'll need to discuss this in much more depth, then. 14:20:30 <ivan> steven: I am against deprecating it 14:20:30 <markbirbeck> q+ 14:20:44 <ivan> ... I do not like breaking backward compatibility 14:20:48 <ivan> manu: it does not break backward compatibility 14:21:01 <ivan> ... deprecation means a strong a signal not to use 14:21:15 <ivan> shane: technically it means it is not removed yet but it can be 14:21:31 <manu> ack mark 14:21:36 <ivan> ... steven, if it said 'prefix is preferred, is that fine'? 14:21:38 <ivan> steven: yes 14:21:46 <ivan> mark: 'deprecated' means there is a decision to remove it in the future 14:21:56 <ivan> ... we have to send a strong signal 14:22:48 <ivan> ... I do not agree that we would have not used xmlns: - done it differently 14:23:01 <manu> q+ to clarify "we'd do it differently" 14:23:10 <ivan> ... at the time we used what w3c had an emphasis on at the time - xmlns: - now things have changed, not as much of an emphasis on namespaces and xmlns: - we made the right decision in the context of what was going on at the time. 14:23:20 <ShaneM> +1 to marks concern 14:23:54 <ivan> ack manu 14:23:54 <Zakim> manu, you wanted to clarify "we'd do it differently" 14:23:54 <Steven> +1 to Mark 14:24:59 <Knud> "xmlns is discouraged"? 14:25:09 <markbirbeck> +1 to Knud 14:25:46 <Zakim> -ShaneM 14:25:47 <Zakim> +ShaneM 14:26:06 <ivan> PROPOSAL: the FPWD should say something like "prefix is preferred" but not explicitly deprecate xmlns 14:26:20 <ShaneM> +1 14:26:21 <manu> +1 14:26:22 <ivan> ivan: +1 14:26:28 <Knud> +1 14:26:31 <Benjamin> +1 14:26:31 <Steven> I can live with that 14:28:31 <markbirbeck> 0 14:28:35 <ivan> markbirbeck: That doesn't send a very strong message, does it? 14:29:52 <manu> PROPOSAL: Remove mention of "xmlns: is deprecated" from the RDFa Core 1.1 FPWD 14:30:08 <manu> +1 14:30:08 <ivan> ivan: +1 14:30:10 <markbirbeck> +1 14:30:23 <Knud> +1 14:30:23 <Benjamin> +1 14:30:24 <Steven> +1 14:30:35 <ShaneM> +1 14:30:36 <ivan> RESOLVED: Remove mention of "xmlns: is deprecated" from the RDFa Core 1.1 FPWD 14:30:45 <ivan> manu: We will have to discuss this in more depth and reach some kind of consensus about deprecating xmlns: after the FPWDs are out there. 14:31:03 <manu> Topic: Resolve to Publish RDFa Core 1.1 and XHTML+RDFa 1.1 FPWD 14:31:16 <ivan> manu: shane, an overview? 14:31:46 <ivan> shane: as far as can see, modulo pubrules, the document is in agreement with the resolutions of the group 14:31:56 <ivan> ... fpwd does not have to be perfect 14:32:17 <ivan> ... xhtml did not have the same review as core, but that is all right, not much changed there since XHTML+RDFa 1.0 :-) 14:32:26 <ivan> Ivan: I have concerns about the core and not publishing RDFa DOM API at the same time 14:32:42 <ivan> ... as soon as we put it out to the public, we will have the public reacting negatively to not publishing RDFa DOM API with the other two documents. 14:32:40 <ivan> manu: Shane, got a link to the RDFa Core 1.1 and XHTML+RDFa 1.1 documents? 14:32:55 <ShaneM> 14:33:11 <ShaneM> 14:33:20 <ShaneM> 14:33:25 <ivan> q+ 14:33:34 <manu> ack ivan 14:34:08 <manu> PROPOSAL: Publish RDFa Core 1.1 as First Public Working Draft 14:34:53 <manu> Ivan: Are we going to publish RDFa DOM API now as well? 14:35:37 <manu> Ivan: I think people might misunderstand the publishing RDFa DOM API at a later date as something negative. 14:35:46 <manu> q+ to discuss RDFa DOM API publication 14:35:50 <markbirbeck> q+ 14:36:19 <manu> Ivan: I'm concerned that people may think we're not concerned about the RDFa DOM API - we do care about it, very much. 14:36:23 <manu> ack markbirbeck 14:36:30 <ivan> mark: I can understand your concern, Ivan 14:36:33 <ivan> ... but I disagree 14:36:52 <ivan> ...the audience to this spec is very different 14:37:12 <ivan> .. my feeling is that the rdfa core and the xhtml will go unnoticed by general web developers. 14:37:21 <ivan> ... but RDFa itself is the story and it's evolved 14:37:30 <ivan> ... however the dom api is a different audience, different story - audience is parser developers 14:37:41 <ivan> ... RDFa DOM API is really aimed at web developers and we really think we should aim it at the html authors 14:37:42 <ivan> q+ 14:37:46 <manu> ack manu 14:37:46 <Zakim> manu, you wanted to discuss RDFa DOM API publication 14:37:51 <ivan> manu: I agree with mark 14:38:13 <ivan> ... i do not want us to get into mind set where we think that all of these specs must be published at the same time. 14:38:23 <ivan> ... We shouldn't create artificial ties between the documents that do not exist. 14:38:33 <ivan> ... but, let's suppose that all of Ivan's fears come true - bad community backlash due to a misunderstanding of where our priorities are 14:38:41 <ivan> ... we have to have courage, and take the heat if that happens 14:38:54 <ivan> ... we are not talking about pushing the dom api by a couple of months, we are talking about slipping publication by two weeks. 14:39:07 <ivan> ... if slipping the date by two weeks ends up resulting in nasty remarks about the RDFa WG 14:39:19 <ivan> ... those nasty remarks will be invalidated after two weeks time - when we publish the RDFa DOM API document 14:39:22 <manu> ack ivan 14:40:15 <markbirbeck> Fair point Ivan. I was bending the stick too far. :) 14:41:35 <manu> Ivan: I hope I'm being paranoid - and I wouldn't object to FPWD. 14:41:52 <manu> Ivan: I think these are the same audiences - we've changed some pretty major stuff. 14:42:10 <Zakim> +knud 14:42:16 <manu> PROPOSAL: Publish RDFa Core 1.1 as First Public Working Draft 14:43:05 <manu> +1 14:43:05 <ivan> ivan: +0.5 14:43:06 <markbirbeck> +1 14:43:07 <Benjamin> +1 14:43:10 <Knud> +1 14:43:11 <ShaneM> +1 14:43:11 <markbirbeck> :) 14:43:22 <Steven> +1 14:43:36 <manu> RESOLVED: Publish RDFa Core 1.1 as First Public Working Draft 14:44:00 <manu> PROPOSAL: Publish XHTML+RDFa 1.1 as First Public Working Draft 14:44:04 <manu> +1 14:44:04 <Steven> +1 14:44:06 <Benjamin> +1 14:44:07 <markbirbeck> +1 14:44:09 <Knud> +1 14:44:13 <ivan> ivan: +0.5 (just to be consistent) 14:44:23 <markbirbeck> I was wondering what you'd do. :) 14:44:24 <ShaneM> +1 14:44:29 <manu> RESOLVED: Publish XHTML+RDFa 1.1 as First Public Working Draft 14:45:14 <ivan> manu: Great job guys on these FPWD! Many thanks to Shane who worked tirelessly to get these documents into shape over the past several weeks! 14:46:45 <ivan> clap clap clap 14:46:50 <ivan> wohooo 14:46:52 <ivan> etc 14:46:56 <markbirbeck> Nice work Shane! 14:47:08 <ivan> Topic: RDFa DOM API 14:47:25 <ivan> manu: I have not put the API on the focus on the agendas for the past two months and I'm afraid that has put us in this situation of not being able to publish RDFa DOM API FPWD along with RDFa Core and XHTML+RDFa - so let's put all of our focus on RDFa DOM API now... get it to FPWD quickly. 14:47:48 <ivan> ... Benjamin, Mark and and I had discussion on how to improve it 14:47:54 <markbirbeck> q+ To apologise for causing delay on DOM API. 14:48:02 <ivan> ... what we want to do is to focus solely on the dom api for the coming 2 weeks 14:48:21 <Benjamin> Current version of the RDFa DOM API document: 14:48:29 <ivan> mark: apologize for causing delay, I was away with no internet connection... 14:48:44 <Benjamin> And the latest version of the Javascript prototype: 14:48:55 <ivan> ... the key issue I am trying to push this towards 14:49:18 <ivan> ... we should give people an api to select the elements of the dom that resulted in a triple in the triple store 14:49:32 <ivan> ... I put something up today for us to discuss 14:49:47 <ivan> manu: the concern I had is that I cannot implement element tracking in Firefox using the librdfa parser 14:50:04 <ivan> ... i know we are talking about an rdfa api 14:50:22 <ivan> ... but it will be very difficult to implement that for implementers that don't have access to the core DOM document object 14:50:31 <ivan> ... i do not know how to implement that in c and c++ in Firefox. 14:50:38 <ivan> mark: i think it is pretty easy 14:50:46 <ivan> manu: i would like to see some code 14:50:58 <ivan> ... if we can implement it in the c and c++ in Firefox, then we should have the feature. 14:51:11 <ivan> mark: this raises the question what we want to achieve with this api 14:51:26 <ivan> ... just querying triples is not really useful 14:51:54 <ivan> manu: that is not what i mean; if we want people to write Firefox extensions that modify the dom and give them extra methods - if we can't do that in a Firefox extension, we have a problem. 14:52:12 <ivan> ... this is usually done is c and c++, and we especially have this issue with the new @profile attribute. 14:52:34 <ivan> ... I do not think you can do it in pure javascript - dereference external @profile documents. 14:52:41 <ivan> ... this is not about implementing it in Redland, you can do that easily. 14:52:57 <ivan> ... it is about the restrictions that Firefox and Chrome put on their extension writers 14:53:15 <ivan> mark: if we want to do something for the in-browser developers, we have to see what is useful to those developers - tying to elements is very useful. 14:53:18 <manu> +1 to what Mark just said. 14:53:28 <ivan> ... we may need an additional thing in the api 14:53:44 <ivan> ... maybe we need some events that get passed 14:53:54 <ivan> ... we have to try to solve this rather than drop it 14:54:30 <ivan> manu: with that said, do you have examples of extending the Document object in Firefox? Not using Javascript - but with C/C++? 14:55:02 <ivan> markbirbeck: we had all kinds of things experimented with in our xforms work, there are lots of stuff we looked at 14:55:18 <ivan> manu: are you opposed getting just triples in javascript? 14:55:44 <ivan> markbirbeck: i do not have a problem with some kind of layering 14:55:55 <ivan> ... eg in sparql you have the notion of projection 14:56:08 <ivan> ... the result is the set of results with all kinds of properties 14:56:16 <ivan> ... you get back objects 14:56:32 <ivan> ... that is natural for js programmers 14:56:34 <ivan> q+ 14:56:37 <Benjamin> The current API version may be easily extended to query DOM nodes with certain RDFa content. 14:56:37 <ivan> ack markbirbeck 14:56:37 <Zakim> markbirbeck, you wanted to apologise for causing delay on DOM API. 14:56:38 <manu> ack mark 14:57:07 <ivan> markbirbeck: i have not looked at other languages, we may have a language specific holes where objects can be used 14:57:22 <ivan> ... and languages should fill that in - use whatever makes sense natively - objects in object-oriented languages. 14:57:36 <ivan> ... but all objects should have a pointer at that element where the triple comes from 14:57:59 <Benjamin> q+ 14:58:23 <ivan> ... we get both the semantics and the element that produced that 14:58:26 <manu> ack ivan 14:59:38 <manu> q+ to discuss triples-as-objects 14:59:41 <Benjamin> -1 to Ivans proposal 14:59:48 <manu> ack benjamin 15:00:04 <manu> Ivan: We don't have to provide every feature when doing a FPWD - do we really need this in there. 15:00:13 <ivan> Benjamin: The RDFa DOM API is not in a publish-able state right now - we cannot publish it today 15:00:26 <ivan> ... I think we should reach a concensus about the general style of the document 15:00:49 <ivan> ... we should get a feeling for what the api would look like 15:00:51 <manu> q- 15:00:55 <manu> q+ to end the telecon 15:01:04 <ivan> manu: we can add mark's proposal to this and see how it works together with the stuff that's already in there. 15:01:10 <ShaneM> Remember that published documents have their own momentum... Once it starts rolling in a certain direction it is hard to change. The faster it rolls the harder it is to redirect. 15:01:40 <ivan> manu: mark, what would help us most is to give us examples 15:01:47 <ivan> ... see how we can have this happen 15:01:53 <ivan> meeting adjourned 15:02:10 <Zakim> -markbirbeck 15:02:12 <Zakim> -Steven 15:02:14 <Zakim> -knud 15:02:20 <Zakim> -Benjamin 15:02:31 <Knud> +1 to what Shane just said 15:02:50 <markbirbeck> +1.5 15:03:00 <markbirbeck> (I'm using up the bits that Ivan didn't use. :)) # SPECIAL MARKER FOR CHATSYNC. DO NOT EDIT THIS LINE OR BELOW. SRCLINESUSED=00000315
http://www.w3.org/2010/02/rdfa/wiki/index.php?title=Chatlog_2010-04-15&oldid=163
CC-MAIN-2014-52
refinedweb
3,745
74.63
I have a sample .NET application that runs fine on windows, and my Ubuntu environment using mono. I am trying to use Mkbundle to create a single native assembly so I can docker containerize it using busybox and keep the size small instead of the usua We have a Qt application that uses a video plugin I developed for i.MX53. This plugin allows "CSI0Video" and "CSI1Video" objects to be created in QML, e.g. CSI0Video { id: csi0 displayRect: "30, 0, 320x480" channel: 1 rotatio This is an assignment for my class. I am supposed to have two classes--salaried and hourly-- which both need to inherit from another class employee. When I compile my code I get no errors but when I run my program, only the header and the netpay func I need to read a .h file and store all the values. For example, .h files contain lines like so: #define mbbh 5 #define gbnn 90 #define mkoll I wrote some code to read this .h file (where I use string array, search for #define and get the value of the Hi I'm am new to programming and I am trying to create a C# grade calculator using WPF for users to enter their grades and for it to remove 2 of their lowest grades and then tell them their overall grade, I have got that part working but I would like I'm having a small problem passing a string to gnuplot from c++ I can pass integers easily enough, but when I try a string (user defined as "title" earlier in the code): fprintf(gnuplotPipe, "set title %s\n", title); I get the error: e I created a LinkedList class with a function delete to remove a certain node from the list if found, however it's not working: public class LinkedList { public Node head; <...> public void delete(string n) { Node x = search(n); //returns the node to Basically I have a form and am trying to "dim" areas of it to draw focus to a certain part of the form. To do this I'm using a Form with no border and 50% opacity, aligned with the actual form. The area I am trying to mask is the dark gray area, I am in the process of implementing a Ray Tracing but I have found a problem with my refraction. This are the two relevant methods, Color Scene::traceRefractionRay(Ray &newRay, Ray r) { double tmin = INFINITE; Instance *obj = NULL; HitRecord hitrec; I am stuck in my project. I am actually finding the average of multiple values. I have ten values to average. The sum is giving the correct result for some time that is I am adding the negative numbers and the result is also negative numbers, but whe It seems this is a pretty common issue, but I've tried everything and can't see any issues. It seems as if this issue just started today. Full error message: "The foreign key component 'AllocationID' is not a declared property on type 'PortfolioSecti I have multiple custom cells stored in .xib files that I use to populate a table with. I tried thinking of a way to implement cell reuse in this case, but the fact that each custom cell contains different fields (the data bound to it), I don't know h I have been trying to figure out how to bind an ObservableCollection<FrameworkElements> to an ItemsControl. I have an existing project which relies heavily on code behind and canvas's without binding which I am trying to update to use mvvm and prism In C++!!I am making a binary application!!But I want to accept only 0 and 1 in my Text Box in which the user will type binary numbers while typing on it.I tried many codes from Google but I didn't find the answer. --------------Solutions------------- I'm never used C++ before, and I used OpenCV background subtraction MOG (Mixture of Gaussian) function in Python and I need to understand how the program works, the OpenCV program line 123 there's command bgmodel.create( 1, frameSize.height*frameSize I have a TLC generated mexfunction with 2 inputs and 0 output. input 1 is unsigned char and input 2 is unsigned int. When I try to get input values with: unsigned char *u1 = ssGetInputPortSignal(S,0); (uint8) unsigned int *u2 = ssGetInputPortSignal(S I have an application that seems to encode some data (a long text) as a compressed binary blob using zlib. I would like to know how I can possibly decode the compressed binary blob. I guess I can use the zlib library itself or a command line tool but I have an XML-document that I'm trying to extract data from. <folder> <list index="1"> <item index="1" > <field type="IMAGE"> <url></url> </field> </it I am new to C++. And I want to develop a dll of a function applying Monte Carlo Simulation using VS C++ 2013. I want to enhance the monte carlo capacity. So I want to use Microsoft MS-MPI and HPC 2008 to do parallel computing within this dll. Then, I
http://www.dskims.com/category/c/5/
CC-MAIN-2019-13
refinedweb
862
65.15
Get the Most Out of IBM Cloudant with Cross-Region Replication 1 min read How to achieve full two-way replication between two data centre regions with IBM Cloudant. If you run applications with customers in multiple regions of the world or run apps that are required to be resilient to the failure of whole data centre regions, you should consider IBM Cloudant for your data store. IBM Cloudant has unique cross-region replication capabilities that allow you to maintain identical datasets that are always in sync in different parts of the world. That way, your users can be served faster by retrieving data from the dataset closest to them, and you can seamlessly failover between regions in the case of disaster or loss of connectivity. Additionally, replicated datasets allow you to handle more traffic. If one region is configured to handle 500 queries per second, replicating to an identical second Cloudant service would add another 500 queries per second. The ease of use and reliability of IBM Cloudant replication sets it apart from most other managed database services. And because of Cloudant's conflict-handling capabilities, you can rest assured that data is never lost, even if the same document is updated simultaneously from two different regions into replicated databases. Obviously, a replicated service will increase your infrastructure costs (because you are provisioning double the capacity), but if these kinds of benefits are valuable to you, then the cost-benefit analysis will still be in your favour. Two-way replication between two data centre regions In this article, we will take you through the simple steps required to achieve full two-way replication between two data centre regions. These principles can be extended to replicate between three or more regions as well (see more details about complex replication topologies in this article). We will also introduce a basic script to monitor replication and check that things are running smoothly. This script will be hosted on the IBM Code Engine service and run on a regular (cron) basis. The following is what you will build: This tutorial should take you less than an hour to complete. It will not be entirely cost-free because you can only set up one Cloudant service on the free tier and you will need two of them. If you deprovision the services after completing the tutorial, however, you should not have to pay more than a few dollars. What you will need - An IBM Cloud pay-as-you-go account. - The IBM Cloud CLI (you also need to make sure that it is logged into your account). - Git. - Node.js and npm. - Terraform: We will be using Terraform to deploy all the required infrastructure. - Docker: We will be using Docker to create the images that will run your code in Code Engine — make sure you are logged into your Docker account. - jq: This is a command-line utility to manipulate JSON data files. - ccurl (or CouchDB curl) a command line utility to access couch-compatible services. - Access to a Mac or Linux terminal. To get the most out of this tutorial, you will need to be familiar with the basics of NodeJS, Terraform and Docker. But there is no deep expertise required of any of them. Tutorial steps - Create two instances of IBM Cloudant in separate geographical regions. - Create secure replication access between them using an IAM ServiceID. - Create one database in each Cloudant instance. - Create a simple NodeJS script that sets up replication between these databases and then monitors the replication. This will be deployed to Code Engine, where it will run every minute. - Change the data in the databases and watch it replicate. Step 1: Obtain an API key to deploy infrastructure to your account You will need some credentials to be able to deploy infrastructure programatically using Terraform. Follow the steps in this document to create an API key and make a note of it for Step 2. Step 2: Clone the repo and cd into the Terraform directory Now you are ready to create all the necessary parameters to run the infrastructure creation process from your machine. In a terminal, type the following: This will copy all the project files into your local machine inside a directory called cloudant-replication-in-a-box. Now create a document called terraform.tfvars with the following fields: The terraform.tfvars document contains variables that you may want to keep secret so it is ignored by the GitHub repository. Step 3: Create the infrastructure In this step, you will create the required infrastructure inside your IBM Cloud account. TL;DR — Run the Terraform script: In a bit more detail: The Terraform folder contains a number of simple scripts: main.tftells Terraform to use the IBM Cloud. variables.tfcontains the variable definitions whose values will be populated from terraform.tfvars. cloudant.tfcreates the Cloudant DB instances in two different regions and some credentials that we will use later to access them registry.tfcreates the Container Registry that will hold your container images for running in Code Engine. iam.tfcreates the access key that is needed to interact with the Container Registry and the key that will be used to read and write between the Cloudant databases. It will take several minutes for the databases and other resources to be ready, but you should now have two Cloudant database instances, a Container Registry namespace for your container images and some Identity and Access Management (IAM) credentials. You can check by visiting the Resources section of your IBM Cloud account. Step 4: Create Cloudant databases and deploy monitoring scripts to Code Engine Another thing the Terraform script does is output a bunch of configuration variables that we will now use. We will run a bash script ( build.sh) that takes some of that output and uses it to create a database called users in both of your Cloudant instances. It will also deploy a replication monitoring script ( monitor.js) to Code Engine that will run every minute and make sure that replication is working correctly. Run the build script — but before you do, are you logged into the IBM Cloud CLI and Docker? Go into the root of the project and type the following: How replication works in Cloudant Replication happens between databases (in our case between the users databases in the Dallas and London regions). Every Cloudant instance has a special database in it called _replicator that contains documents with replication instructions for each database you want to replicate. Each of these documents has a source database (where you are replicating from) and a target database (where you are replicating to). It also contains any necessary credentials that allow replication to occur between these databases. Here's an example of one such document: The monitoring script monitor.js is a simple NodeJS script. It builds up a replication document like the one above with data passed in as environment variables. Then it checks whether the _replicator database already contains this document (from its _id). If it does not, it uploads the document to the _replicator database. So the first time your script runs on Code Engine, the document will not exist and will get uploaded, thereby kicking off the replication process. After that, the document will exist, but every time the script retrieves it, it will check what state it is in. If it is in any kind of error state, it will attempt to upload the document again, thereby trying to re-start the replication process. Error states can be caused by things like temporary loses of connectivity, expired credentials or other factors. This script is very simple, but it could be made more clever by, for example, generating alerts when it finds error states. The script is running twice, once using London as the source and Dallas as the target and once using Dallas as the source and London as the target. Replication is happening both ways. Note here that both documents could be uploaded to the same Cloudant instance; that is, the system knows that it needs to "push" to some other database and also "pull" from it. The best-practice recommendation is to have your replication documents in the instance that is the least active one. So if, for example, your London Cloudant is taking most of the application traffic, then put your replication documents in the Dallas instance. In this case, for simplicity, we have placed one document in each database. Step 5: Watch your data replicate The easiest way to your data replicate is in the Cloudant User interface. From your resources list, click on the Launch Dashboard link of your cloudantDallas and cloudantLondon instances (open them in separate tabs so you can move between them): From one of them (it doesn't matter which), click on the users database and then on the Create Document button. In the editor, add a few fields and save the document. For example: Now go to the other Cloudant instance, click into the users database, and you should see the above document in there already. It's that quick. Summary In this tutorial we have demonstrated how easy it is to set up two-way replication between IBM Cloudant instances in two regions of the world. We have also implemented a basic monitoring script that ensures replication is working. If high availability, whole-region disaster recovery and customer satisfaction are important factors in your application design, then you should be considering IBM Cloudant as your database. Remember to decommission your resources so that you don't get charged additional fees. In the Terraform directory, type the following: To remove the IBM Cloud Code Engine project, type the following: If you want to get started with IBM Cloud Databases, check out all our current promotions here. Follow IBM Cloud Be the first to hear about news, product updates, and innovation from IBM Cloud.Email subscribeRSS
https://www.ibm.com/cloud/blog/get-the-most-out-of-ibm-cloudant-with-cross-region-replication
CC-MAIN-2022-21
refinedweb
1,651
60.65
Microsoft has recently been heavily investing in .NET Core, which you can think of as the next generation of the .NET Framework. There are various benefits to .NET Core, the biggest one being that it is cross-platform; thus compliant code can run on Windows, Linux and Mac (and probably others in future). In this article, we’re going to take one of my smaller projects – Dandago.Finance – and port it to .NET Core. Dandago.Finance is ideal to demonstrate a first migration because it is very small, consisting of a main project (3 classes) and a unit test project (2 classes) – both class libraries. Before we start, make sure you are using the latest tools (such as the recently released Visual Studio 2017). .NET Core tools have undergone a lot of radical changes (e.g. project.json is dead) so you don’t want to be learning based on something that’s already obsolete. If you’re using VS2017, make sure you have the .NET Core cross-platform development workload installed. Migrating the main library We’re going to start a fresh new class library targeting .NET Core and move our code there. Actually, that statement is not entirely correct: if you open Visual Studio 2017, you’ll see that there are at least 3 different kinds of class library you can create (or more depending on additional tooling you may have installed): - Class Library (.NET Framework) - Class Library (.NET Core) - Class Library (.NET Standard) This is very confusing and I’ve asked a question about this on Stack Overflow yesterday that attracted some pretty detailed answers. In short, if you want your class libraries to be as portable as possible, you need to target .NET Standard. .NET Standard is a specification detailing APIs that need to be available in compatible frameworks. .NET Core, and certain versions of the full .NET Framework, implement .NET Standard. However, they each also incorporate a lot of other runtime-related stuff, so targeting .NET Core specifically means you can’t use your code under the full .NET Framework. So let’s create a project of type Class Library (.NET Standard). As always, this will create a solution with the same name as the project. Next, we’ll delete the automatically created Class1 class, and copy the class files from the old Dandago.Finance library to the new project folder. You’ll notice that Visual Studio automatically notices the new files and includes them in the project, without you needing to explicitly add them: Migrating the test project Let’s add a new class library for the unit tests, but this time it needs to be a Class Library (.NET Core). If you get this wrong and choose Class Library (.NET Standard) instead, Visual Studio won’t find your tests and the dotnet test command will refuse to run it (as per this Stack Overflow question). The reason why .NET Standard won’t work for unit tests is detailed in the corresponding answer: in short, we need to specify a target framework that will be responsible for running the tests; .NET Standard on its own is not enough. Next, we need to add a reference to the Dandago.Finance project. Now, we can repeat the procedure we did for the main library, and delete Class1.cs and copy over the test classes. However, this isn’t going to be as smooth as with the main library. The original test project uses NUnit, and at the time of writing, that isn’t fully supported by .NET Core. Fortunately, however, it’s easy to change to xUnit, which does already boast .NET Core support. First, we need to install the following packages: Install-Package Microsoft.NET.Test.Sdk Install-Package xunit Install-Package xunit.runner.visualstudio Then, we need to make the following substitutions: using NUnit.Framework;becomes using Xunit; [TestFixture]goes away [Test]becomes [Fact] Assert.IsTrue(...)becomes Assert.True(...) Assert.IsFalse(...)becomes Assert.False(...) The solution should now build, and the unit tests should run successfully: Summary Migrating Dandago.Finance to .NET Core has taught us a few things: - Visual Studio can automatically detect new files for .NET Core / .NET Standard projects. - Portable class libraries should target .NET Standard. - Unit test projects should target .NET Core. - Use xUnit for .NET Core unit tests. 2 thoughts on “Migrating Dandago.Finance to .NET Core”
http://gigi.nullneuron.net/gigilabs/migrating-dandago-finance-to-net-core/
CC-MAIN-2020-05
refinedweb
728
66.94
This - first you have write a significant amount of “dumb” code like this and second, you’re injecting a ton of “worthless” method calls which carry a significant performance overhead. If it was possible to eliminate the latter which could (perhaps) be eliminated in some smart way at engine level. Some smart syntax to specify a delegate / decorator would be cool and yet cooler would be some smart engine-level elimination of the redundant calls. Rant done - thanks for listening. November 23rd, 2005 at 11:25 am Well, here is hoping that they break BC entirely and leave it at that. In my view, the biggest mistake they made with PHP5 was retaining BC with PHP4.yuk Big mistake - I think I said as much in the early days before PHP5.0.x became common use? If they - again - make this mistake with BC in regards to PHP5.x or below, well **** them :eek: I’ve just not got the time for that - PHP needs a clean break, so lets have it. November 23rd, 2005 at 11:29 am Yeah, I studied the notes this morning and was about to write a review, but it’ll have wait until the end of my long day of work and floorball… November 23rd, 2005 at 2:58 pm What’s “BC”? Please. Thank you, kindly. November 23rd, 2005 at 3:21 pm Backward Compatibility. Also known as “Beware of Changes”. :) November 23rd, 2005 at 3:22 pm BC is Backward Compatibility. November 24th, 2005 at 12:46 am If PHP6 is going to break the BC, then I hope it is really going to worth it. I personally still develop PHP applications using PHP4, just because they can run on both PHP4 and PHP5. November 24th, 2005 at 12:55 am [...] Sitepoint发表了一篇简短的文章,里面收录了很多篇关于PHP6的资料。从其中的一条中可以看到,一些没有用的或者是受争议的功能都将被去除,包括register_globals,magic_quotes和safe_mode等。 [...] November 24th, 2005 at 5:07 am PHP feels like alpha software to me. Valid code written in 4.x isn’t guaranteed to work in new versions of 4.x. Valid code written in 5.x will break in 6.x. What does PHP want to be? I’d consider using it again if the developers would stop shooting from the hip. In other words, get together, write a game plan, and go from there. It would be wise for PHP to be renamed and a new project started with a game plan made publically available. November 24th, 2005 at 5:10 am I wrote the “PHP feels like alpha software to me.” comment. November 24th, 2005 at 11:23 am There is already another BC break in php 5 They changed the order they handle destructors so all objects are gone by the time you get to sessions or your custom shutdown handler. Meaning it is impossible to call other objects from either. This instantly breaks and session library that uses a object based database layer as before it has a chance to write the data the database object is destroyed. November 25th, 2005 at 2:00 am Ah! unicode support … why don’t we just migrate to the java camp now, PHP is beginning to resemble java a lot in terms of features. But then isn’t it a little too soon to be talking about PHP6, take a look around, look at Asian devs, PHP5 isn’t even mainstream yet and lo! they’re planning on PHP6. It was about time they took the register globals out completely, it has brought with it nothing but evil :D November 25th, 2005 at 9:48 am [...] Mais que faire d’une version PHP 5.1 alors que PHP 4 est encore présent à plus de 94% sur les serveurs (source Nexen.net, pour le mois d’octobre 2005) ? Ce qui me fait peur, c’est que PHP 6 est déjà en chantier (lire par exemple Sitepoint : PHP6 Planning ou Minutes PHP Developers Meeting)… [...] November 28th, 2005 at 12:22 pm going to drift further and further into the realm of OOP, it needs to have namespaces. Nothing annoys me more than class and function naming collisions! To get around naming collisions, developers of libraries and frameworks tend to name their classes with some sort of a prefix denoting the codebase to which they belong. For instance, the new Zend Framework uses a prefix of “Z” at the beginning of all its class names. It solves the name collision problem to a point, but still leaves you with an overcrowded “default namespace” and offers no organization whatsoever. If PHP 6 is aiming to be a true enterprise-ready object oriented language, they need to add this feature. November 28th, 2005 at 12:24 pm I somehow clipped the beginning of my last comment.. sorry! Should have read, January 5th, 2006 at 12:35 pm I can’t believe this is still an issue. It’s why I rarely use PHP. I thought it was going to be fixed in PHP5, but the pulled the rug from me again. March 10th, 2006 at 5:22 pm [...] As blogged a while back, you’ll find these changes discussed here. Nice use of carrot and stick in fact—for the pain on fixing your apps to run under PHP6, you get Unicode. Tags: php, php6 [...] May 10th, 2006 at 10:33 am Web needs scripting languages, not oop. oop doesn’t make sense for the web. July 19th, 2006 at 8:04 pm I agree with coffee_ninja,namespace is must August 12th, 2006 at 11:48 pm @chris That is a little harsh now is it not? If you develop a very large web application OOP is the best way to keep things organised and structured. I agree that sometimes it’s overkill though, but that is when we talk about those itty bitty projects. August 14th, 2006 at 10:51 am @chris No, the web needs people to code in PHP like real programmers, not like designers hacking a few haphazard lines of code into their HTML. Even simple web apps, regardless of wether they are coded in a PHP, Java, or .Net, can benefit from better organization and separation of responsibilities. My apologies if this reply sounds a bit venemous, but if your way of thinking is what the world truley wants out of PHP, I’ll switch to Java right now and not bat an eyelash. Fortunately I don’t think that it’s so. June 27th, 2007 at 5:46 pm Why don’t we all just use perl? October 4th, 2007 at 8:08 am Hey PHP is more BC than anything Microsoft ever wrote. Chris OOP is for Db accessibility I agree you dont need it to validate user input. December 17th, 2007 at 1:58 am I personally feel OOP is very important for programming. Some time we feel OOP is time consuming. But for a large project we need to be organized. OOP play good rule to organize our code and to bring reusability and readability finally we can reach a good standard. For new version of any language I think the performance is more important then BC. Because every moment we are moving forward so there should not be any scope to switch the language better switch version. Always we have to satisfy our clients and they just want their output. So my programming language needs good performance. And to bring performance better we break BC. Doing some more effort is better then excuse. March 15th, 2008 at 7:56 pm 1. please no more register globals 2. namespaces … yes please! The main focus for php6 should be on OOP i reckon.
http://www.sitepoint.com/blogs/2005/11/23/php6-planning/
crawl-002
refinedweb
1,274
73.27
In this article, I will take you through how we can classify the nationalities of people by using their names. You will be thinking about how we can classify nationalities by using just names. There is a lot about how we can play with names. Classify Nationalities Let’s get started with this machine learning task to classify nationalities by importing the necessary packages. I will classify nationalities based on names as Indian or Non-Indian. So, let’s import some packages and get started with the task: Also, Read – Machine Learning Full Course for free. Code language: JavaScript (javascript)Code language: JavaScript (javascript) from tensorflow import keras import tensorflow as tf import pandas as pd import os import re Now, let’s import the datasets. The datasets I am using here in this article can be easily downloaded from here. Now after importing the datasets I will prepare two helper functions for data cleaning and data processing: male_data = pd.read_csv(male.csv) female_data = pd.read_csv(femaile.csv) 13754 After loading and removing the wrong entries in the data, we got a few records around 13,000. For non-Indian names, there is a nifty package called Faker. This generates names from different regions: Code language: JavaScript (javascript)Code language: JavaScript (javascript) from faker import Faker fake = Faker(‘en_US’) fake.name() ‘Brian Evans’ We have generated approximately the same number of names as we have in the Indian data set. We then removed samples longer than 5 words. The Indian data set contained a lot of names with just first names. So we need to make the overall non-Indian distribution also similar. Code language: CSS (css)Code language: CSS (css) non_indian_data.head() We end up with about 14,000 non-Indian names and 13,000 Indian names. Now let’s build a neural network to classify nationalities using names: So this is how we can easily classify nationalities with machine learning. I did not include the full code and exploration here, you can have a look at the full code from here. Feel free to ask your valuable questions in the comments section below. Also, Read – How to Save Machine Learning Models?
https://thecleverprogrammer.com/2020/09/27/classify-nationalities-with-machine-learning/
CC-MAIN-2021-43
refinedweb
363
56.45
I have looked in the standard library and on StackOverflow, and have not found a similar question. So, is there a way to do the following without rolling my own function? Bonus points if someone writes a beautiful function if there is no built in way. def stringPercentToFloat(stringPercent) # ??? return floatPercent p1 = "99%" p2 = "99.5%" print stringPercentToFloat(p1) print stringPercentToFloat(p2) >>>> 0.99 >>>> 0.995 Use strip('%') , as: In [9]: "99.5%".strip('%') Out[9]: '99.5' #convert this to float using float() and divide by 100 In [10]: def p2f(x): return float(x.strip('%'))/100 ....: In [12]: p2f("99%") Out[12]: 0.98999999999999999 In [13]: p2f("99.5%") Out[13]: 0.995
https://codedump.io/share/MA05N88c4D11/1/what-is-a-clean-way-to-convert-a-string-percent-to-a-float
CC-MAIN-2017-51
refinedweb
115
79.77
Handling balloon hibernate / restore is tricky. If the balloon wasinflated before going into the hibernation state, upon resume, the hostwill not have any memory of that. Any pages that were passed on to thehost earlier would most likely be invalid, and the host will have tore-balloon to the previous value to get in the pre-hibernate state.So the only sane thing for the guest to do here is to discard all thepages that were put in the balloon. When to discard the pages is thenext question.One solution is to deflate the balloon just before writing the image tothe disk (in the freeze() PM callback). However, asking for pages fromthe host just to discard them immediately after seems wasteful ofresources. Hence, it makes sense to do this by just fudging ourcounters soon after wakeup. This means we don't deflate the balloonbefore sleep, and also don't put unnecessary pressure on the host.This also helps in the thaw case: if the freeze fails for whateverreason, the balloon should continue to remain in the inflated state.This was tested by issuing 'swapoff -a' and trying to go into the S4state. That fails, and the balloon stays inflated, as expected. Boththe host and the guest are happy.Finally, in the restore() callback, we empty the list of pages that werepreviously given off to the host, add the appropriate number of pages tothe totalram_pages counter, reset the num_pages counter to 0, andall is fine.As a last step, delete the vqs on the freeze callback to prepare forhibernation, and re-create them in the restore and thaw callbacks toresume normal operation.The kthread doesn't race with any operations here, since it's frozenbefore the freeze() call and is thawed after the thaw() and restore()callbacks, so we're safe with that.Signed-off-by: Amit Shah <amit.shah@redhat.com>--- drivers/virtio/virtio_balloon.c | 47 +++++++++++++++++++++++++++++++++++++++ 1 files changed, 47 insertions(+), 0 deletions(-)diff --git a/drivers/virtio/virtio_balloon.c b/drivers/virtio/virtio_balloon.cindex 1ff3cf4..4c327c7 100644--- a/drivers/virtio/virtio_balloon.c+++ b/drivers/virtio/virtio_balloon.c@@ -363,6 +363,48 @@ static void __devexit virtballoon_remove(struct virtio_device *vdev) kfree(vb); } +#ifdef CONFIG_PM+static int virtballoon_freeze(struct virtio_device *vdev)+{+ /*+ * The kthread is already frozen by the PM core before this+ * function is called.+ */++ /* Ensure we don't get any more requests from the host */+ vdev->config->reset(vdev);+ vdev->config->del_vqs(vdev);+ return 0;+}++static int virtballoon_thaw(struct virtio_device *vdev)+{+ return init_vqs(vdev->priv);+}++static int virtballoon_restore(struct virtio_device *vdev)+{+ struct virtio_balloon *vb = vdev->priv;+ struct page *page, *page2;++ /* We're starting from a clean slate */+ vb->num_pages = 0;++ /*+ * If a request wasn't complete at the time of freezing, this+ * could have been set.+ */+ vb->need_stats_update = 0;++ /* We don't have these pages in the balloon anymore! */+ list_for_each_entry_safe(page, page2, &vb->pages, lru) {+ list_del(&page->lru);+ totalram_pages++;+ }+ return init_vqs(vdev->priv);+}+#endif+ static unsigned int features[] = { VIRTIO_BALLOON_F_MUST_TELL_HOST, VIRTIO_BALLOON_F_STATS_VQ,@@ -377,6 +419,11 @@ static struct virtio_driver virtio_balloon_driver = { .probe = virtballoon_probe, .remove = __devexit_p(virtballoon_remove), .config_changed = virtballoon_changed,+#ifdef CONFIG_PM+ .freeze = virtballoon_freeze,+ .restore = virtballoon_restore,+ .thaw = virtballoon_thaw,+#endif }; static int __init init(void)-- 1.7.7.4
https://lkml.org/lkml/2011/12/22/129
CC-MAIN-2017-43
refinedweb
522
53.71
strtok, strtok_r - extract tokens from strings #include <string.h> char *strtok(char *s, const char *delim); char *strtok_r(char *s, const char *delim, char **ptrptr); A `token' is a nonempty string of characters not occurring in the string delim, followed by \0 or by a character occurring in delim. The strtok() function can be used to parse the string s into tokens. The first call to strtok() should have s as its first argument. Subsequent calls should have the first argument set to NULL. Each call returns a pointer to the next token, or NULL when no more tokens are found. If a token ends with a delimiter, this delimiting character is overwritten with a \0 and a pointer to the next character is saved for the next call to strtok(). The delimiter string delim may be different for each call. The strtok_r() function works the same as the strtok() function, but instead of using a static buffer it uses a pointer to a user allocated char* pointer. This pointer, the ptrptr parameter, must be the same while parsing the same string. Never use these functions. If you do, note that: These functions modify their first argument. The identity of the delimiting character is lost. These functions cannot be used on constant strings.- spn(3), strstr(3) GNU 2000-02-13 STRTOK(3)
http://nixdoc.net/man-pages/Linux/man3/strtok.3.html
CC-MAIN-2018-05
refinedweb
223
65.42
This article is the continuation on my Arcball module for C#. Previously, I had posted a code using CsGL. In this version, I have utilized the Tao.OpenGL wrapper and I have added Rotation/Zoom/Pan functions. I have also made use of Display Lists to speed up plot rendering. The Arcball module written here is general and not limited to OpenGL, and can be used in GDI+ and DirectX as well. Please note that my main focus in this tutorial is on the Arcball module, not on OpenGL application. Arcball (also know as RollerBall) is probably the most intuitive method to view three dimensional objects. The principle of the Arcball is based on creating a sphere around the object and letting users to click a point on the sphere and drag it to a different location. There is a bit of math involved and you can Google for it. Here are few good links to educate yourself: The code here is a C# source code implementing an Arcball in OpenGL (Tap.OpenGL). Here is the same object but zoomed using the mouse middle button: And, here is when it is panned to the left using the mouse right button: In this version, I am using Display List, Lighting, and Blending functions. I am not going to go into the details of OpenGL programming for the sake of brevity. Create a new form, create an instance of the Arcball class, and make if fill the form rectangle. All plots should go in the public function PlotGL in Form1.cs. I am plotting a torus and a backward torus in this example. Arcball PlotGL public void PlotGL() { try { lock (matrixLock) { ThisTransformation.get_Renamed(matrix); } Gl.glClear(Gl.GL_COLOR_BUFFER_BIT | Gl.GL_DEPTH_BUFFER_BIT); Gl.glLoadIdentity(); Gl.glPushMatrix(); // NEW: Prepare Dynamic Transform Gl.glMultMatrixf(matrix); // NEW: Apply Dynamic Transform #region plot something Gl.glPolygonMode(Gl.GL_FRONT, Gl.GL_FILL); Gl.glColor3f(0.8f, 0.3f, 0.1f); Gl.glCallList(plot_glList1); // plot using display list //Gl.glPolygonMode(Gl.GL_FRONT, Gl.GL_LINE); Gl.glColor3f(0.5f, 0.5f, 0.9f); Gl.glCallList(plot_glList2); // plot using display list #endregion plot something Gl.glPopMatrix(); // NEW: Unapply Dynamic Transform Gl.glFlush(); // Flush the GL Rendering Pipeline this.simpleOpenGlControl1.Invalidate(); } catch { return; } } I have defined the transformation matrices in here (Arcball.cs): public class Matrix4f { ...; // rotation; // translation (pan) M[0, 3] = pan.x; M[1, 3] = pan.y; // scale (zoom) for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) M[i, j] *= scl; } } public float Scale { set { scl = value; } } public Vector3f Pan { set { pan = value; } } } You don't need to change anything else and the code should work. I have included comments as much as possible, but feel free to contact me if you have questions. Note: For almost any code, you do not need to modify the Arcball class.
http://www.codeproject.com/Articles/22484/Arcball-Module-in-C-Tao-OpenGL
CC-MAIN-2016-26
refinedweb
472
65.62
LD.SO(8) Linux Programmer's Manual LD.SO(8) ld.so, ld-linux.so* - dynamic linker/loader The dynamic linker can be run either indirectly dependency does not contain a slash, then it is searched for in the following order: o (ELF only) Using the directories specified. (On some 64-bit archiectures, the default spaths for 64-bit libraries are /lib64, and then /usr/lib64.).). --inhibit-rpath list Ignore RPATH and RUNPATH information in object names in list. This option is ignored if ld.so is set-user-ID or set-group- ID. --audit list Use objects named in list as auditors. Among the more important environment variables are the following: debugger. mode. versions of ld-linux.so.1 also supported LD_ELF_PRELOAD. LD_AUDIT (glibc since 2.4) A colon-separated list of user-specified, ELF shared objects to be loaded before all others in a separate linker namespace (i.e., one that does not intrude upon the. For details, see rtld-audit(7). The auditing interface is largely compatible with that provided on Solaris, as described in its Linker and Libraries Guide, in the chapter Runtime Linker Auditing Interface.. LD_HWCAP_MASK (glibc since 2.1) Mask for hardware capabilities. LD_KEEPDIR (a.out only)(libc5) Don't ignore the directory in the names of a.out libraries to be loaded. Use of this option is strongly discouraged. LD_NOWARN (a.out only)(libc5) Suppress warnings about a.out libraries with incompatible minor version numbers. LD_ORIGIN_PATH (glibc since 2.1) Path where the binary is found (for non-set- user-ID programs). For security reasons, since glibc 2.4, LD_ORIGIN_PATH is ignored for set-user-ID/set-group-ID binaries. LD_POINTER_GUARD (glibc since 2.4) internals) are mangled semi-randomly to make it more difficult for an attacker to hijack the pointers for use in the event of a buffer overrun or stack-smashing attack. LD_PROFILE (glibc since 2.1) The name of a (single) shared object to be profiled, specified either as a pathname or a soname. Profiling output is appended to the file whose name is: "$LD_PROFILE_OUTPUT/$LD_PROFILE.profile". LD_PROFILE_OUTPUT (glibc since 2.1) Directory where LD_PROFILE By default (i.e., if this variable is not defined), executables and prelinked shared objects will honor base addresses of their dependent libraries executables nor PIEs will honor the base addresses.. LDD_ARGV0 (libc5) argv[0] to be used by ldd(1) when none is present. The ld.so functionality is available for executables compiled using libc version 4.4.3 or greater. ELF functionality is available since Linux 1.1.52 and libc5..), rtld-audit(7), ldconfig(8), sln(8) This page is part of release 4.01 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 2015-05-07 LD.SO(8)
http://man7.org/linux/man-pages/man8/ld.so.8.html
CC-MAIN-2015-32
refinedweb
477
53.37
Hi guys(especially Andrew), does FSOUND_CD_PLAYONCE work? here the example: include <stdio.h> if defined(WIN32) || defined(_WIN64) || defined(WATCOMC) #include <conio.h> #include <windows.h> elif defined(linux) #include “../../api/inc/wincompat.h” endif include <stdlib.h> include “../../api/inc/fmod.h” include “../../api/inc/fmod_errors.h” /* optional */ int main() { /* INITIALIZE */ if (!FSOUND_Init(44100, 32, FSOUND_INIT_USEDEFAULTMIDISYNTH)) { printf(“Error!\n”); printf(“%s\n”, FMOD_ErrorString(FSOUND_GetError())); return 1; } /* LOAD SONG */ char cddevice_ = 0; FSOUND_CD_SetPlayMode(cddevice_, FSOUND_CD_PLAYONCE); FSOUND_CD_Play(cddevice_, 1); return 0; } It plays the first track just fine. But than the whoel cd. I thought, it just has to play the track 1???. Any guess? platform: windows XP, fmod374 Cheers takomat fmod team - takomod asked 13 years ago - You must login to post comments any guesses? In the meantime I tried the simple example above on several computers with the same effect: It does not stop after playing the selected song Cheers Lars FMOD uses windows messages internally when it handles CD looping so you’re going to have to put a message pump in your app and link with user32.lib if you’re not already doing so. For example… [code:189d80yd] /* LOAD SONG */ char cddevice_ = 0; FSOUND_CD_SetPlayMode(cddevice_, FSOUND_CD_PLAYONCE); FSOUND_CD_Play(cddevice_, 4); int pos_sample_ms__ = FSOUND_CD_GetTrackLength(cddevice_, 4); for (;;) { MSG msg; if (PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE)) { if (GetMessage(&msg, NULL, 0, 0) > 0) { TranslateMessage(&msg); DispatchMessage(&msg); } } Sleep(14); static int display_time = 0; if ((display_time += 14) >= 20000) { std::cout << " total(sec): " << (pos_sample_ms__/60000); std::cout << " act(sec): " << (FSOUND_CD_GetTrackTime(cddevice_)/60000); std::cout << std::endl; display_time = 0; } } return 0; [/code:189d80yd] Hi Andrew, it is working on windows now. But: Actually I do not work with windows messaging as the application is platform independant. That implies the next question: what to do on linux or better what is the platform independent code? ifdef WIN32 MSG msg; if (PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE)) { if (GetMessage(&msg, NULL, 0, 0) > 0) { TranslateMessage(&msg); DispatchMessage(&msg); } endif ?? Thanx Lars } The linux version doesn’t use any message stuff for CD looping so just ifdef out the windows message pump stuff and it should all work fine. ok. it works in general But I recognized the first time I tried it, that the next song was played just for some 40 ms or so. This short hearing of sound happened also similar, when we set the stream or mod with channel_id__ = FSOUND_Stream_PlayEx(FSOUND_FREE, stream, NULL, TRUE); on pause and than setting all the modes like FSOUND_SetMute(channel_id__, TRUE); and than FSOUND_SetPaused(channel_id__, FALSE); As this “errors” occurs none predictable, we can not make you hear that effect, but it is worse to mention it here. I have not heared this small hearable error on linux. Cheers Lars Make sure your message pump is running fast enough i.e. don’t put a huge sleep in there or bog down your frame rate doing other stuff. FMOD can only respond to the “CD track finished” message when it’s pumped in by your app. [quote:3c0wm6ke] FSOUND_CD_Play(cddevice_, 1); return 0; [/quote:3c0wm6ke] You’re starting the CD and then exiting the app straight away. Because of the way CD playback (using MCI) works with Windows, the CD keeps playing through to the end even though the app is finished. Solution is to not exit your program straight away. Hi Andrew, sorry, made that example too simple. Of course, the calls are performed in a bigger application. Please exchange the part between load song and return(0) as follows: /* LOAD SONG */ char cddevice_ = 0; FSOUND_CD_SetPlayMode(cddevice_, FSOUND_CD_PLAYONCE); FSOUND_CD_Play(cddevice_, 4); int pos_sample_ms__ = FSOUND_CD_GetTrackLength(cddevice_, 4); while(pos_sample_ms__>FSOUND_CD_GetTrackTime(cddevice_)) { Sleep(20000); std::cout << " total(sec): " << (pos_sample_ms__/60000); std::cout << " act(sec): " << (FSOUND_CD_GetTrackTime(cddevice_)/60000); std::cout << std::endl; } Sleep(20000); It plays the 5th song???? … cheers lars
https://www.fmod.org/questions/question/forum-11714/
CC-MAIN-2018-17
refinedweb
634
61.87
15 An Example Device Driver It’s hard to find a good driver these days, one with character and style. — Unknown 15.1 Introduction Chapters in this section of the text explore the general structure of an I/O system, including interrupt processing and real-time clock management. The previous chapter presents the organization of the I/O subsystem, a set of abstract I/O operations, and an efficient implementation using a device switch table. This chapter continues the exploration of I/O. The chapter explains how a driver can define an I/O service at a high level of abstraction that is independent of the under- lying hardware. The chapter also elaborates on the conceptual division of a device driver into upper and lower halves by explaining how the two halves share data struc- tures, such as buffers, and how they communicate. Finally, the chapter shows the de- tails of a particular example: a driver for an asynchronous character-oriented serial de- vice. 15.2 The Tty Abstraction Xinu uses the name tty to refer to the abstraction of an interface used with character-oriented serial devices such as a serial interface or a keyboard and text win- dow.† In broad terms, a tty device supports two-way communication: a process can send characters to the output side and/or receive characters from the input side. Although the underlying serial hardware mechanism operates the input and output in- †The name tty is taken from early Unix systems that used an ASCII Teletype device that consisted of a keyboard and an associated printer mechanism. 267 268 An Example Device Driver Chap. 15 dependently, the tty abstraction allows the two to be connected. For example, our tty driver supports character echo, which means that the input side of the driver can be configured to transmit a copy of each incoming character to the output. Echo is espe- cially important when a user is typing on a keyboard and expects to see characters displayed on a screen as keys are pressed. The tty abstraction illustrates an important feature of many device drivers: multiple modes that can be selected at run-time. In our tty driver, the three modes focus on how the driver processes incoming characters before delivering them to an application. Fig- ure 15.1 summarizes the three modes and gives their characteristics. Mode Meaning The driver delivers each incoming character as it arrives raw without echoing the character, buffering a line of text, performing translation, or controlling the output flow The driver buffers input, echoes characters in a readable cooked form, honors backspace and line kill, allows type-ahead, handles flow control, and delivers an entire line of text The driver handles character translation, echoing, and cbreak flow control, but instead of buffering an entire line of text, the driver delivers each incoming characters as it arrives Figure 15.1 Three modes supported by the tty abstraction. Cooked mode is intended to handle interactive keyboard input. Each time it re- ceives a character, the driver echoes the character (i.e., transmits a copy of the character to the output), which allows a user to see characters as they are typed. Echo is not mandatory. Instead, the driver has a parameter to control character echoing, which means an application can turn off echo to prompt for a password. Cooked mode sup- ports line buffering, which means that the driver collects all characters of a line before delivering them to a reading process. Because the tty driver performs character echo and other functions at interrupt time, a user can type ahead, even if no application is reading characters (e.g., a user can type the next command while the current command is running). The chief advantage of line buffering arises from the ability to edit the line, either by backspacing or typing a special character that erases the entire line and allows the user to begin entering the line again. Cooked mode provides two additional functions. First, it handles output flow con- trol, allowing a user to temporarily stop and later restart output. When flow control is enabled, typing control-s stops output and typing control-q restarts output. Second, cooked mode handles input mapping. In particular, some computers or applications use a two-character sequence of carriage return (cr) and linefeed (lf) to terminate a line of Get Operating System Design now with O’Reilly online learning. O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.
https://www.oreilly.com/library/view/operating-system-design/9781439881118/chapter-20.html
CC-MAIN-2021-39
refinedweb
752
50.36
Important: Please read the Qt Code of Conduct - QMacStyle - File not found error Hi, I'm currently trying to port an app that was using Qt 4.8.3 to Qt 5.0. When I try to build the app (using Xcode) I get a "file not found" error for the #include <QMacStyle> What's going on and how can I fix this? Cheers, Chris - leon.anavi last edited by [quote author="cpsmusic" date="1358486908"]What's going on and how can I fix this?[/quote] It seems that QMacStyle was made internal in Qt 5. Check "this announcement": for details. If you are deriving off of QMacStyle, switch it to QProxyStyle. If you need to create QMacStyle use QStyleFactory.
https://forum.qt.io/topic/23350/qmacstyle-file-not-found-error
CC-MAIN-2021-04
refinedweb
120
84.57
Use managed identities to access Event Hub from an Azure Stream Analytics job Azure Stream Analytics supports Managed Identity authentication for both Azure Event Hubs input and output. Managed identities eliminate the limitations of user-based authentication methods, like the need to reauthenticate because of password changes or user token expirations that occur every 90 days. When you remove the need to manually authenticate, your Stream Analytics deployments can be fully automated. A managed identity is a managed application registered in Azure Active Directory that represents a given Stream Analytics job. The managed application is used to authenticate to a targeted resource, including Event Hubs that are behind a firewall or virtual network (VNet). For more information about how to bypass firewalls, see Allow access to Azure Event Hubs namespaces via private endpoints. This article shows you how to enable Managed Identity for an Event Hubs input or output of a Stream Analytics job through the Azure portal. Before you enabled Managed Identity, you must first have a Stream Analytics job and Event Hub resource. Create a managed identity First, you create a managed identity for your Azure Stream Analytics job. In the Azure portal, open your Azure Stream Analytics job. From the left navigation menu, select Managed Identity located under Configure. Then, check the box next to Use System-assigned Managed Identity and select Save. A service principal for the Stream Analytics job's identity is created in Azure Active Directory. The life cycle of the newly created identity is managed by Azure. When the Stream Analytics job is deleted, the associated identity (that is, the service principal) is automatically deleted by Azure. When you save the configuration, the Object ID (OID) of the service principal is listed as the Principal ID as shown below: The service principal has the same name as the Stream Analytics job. For example, if the name of your job is MyASAJob, the name of the service principal is also MyASAJob. Grant the Stream Analytics job permissions to access the Event Hub For the Stream Analytics job to access your Event Hub using managed identity, the service principal you created must have special permissions to the Event Hub. Go to Access Control (IAM) in your Event Hub. Select + Add and Add role assignment. On the Add role assignment page, enter the following options: Select Save and wait a minute or so for changes to propagate. You can also grant this role at the Event Hub Namespace level, which will naturally propagate the permissions to all Event Hubs created under it. That is, all Event Hubs under a Namespace can be used as a managed-identity-authenticating resource in your Stream Analytics job. Note Due to global replication or caching latency, there may be a delay when permissions are revoked or granted. Changes should be reflected within 8 minutes. Create an Event Hub input or output Now that your managed identity is configured, you're ready to add the Event Hub resource as an input or output to your Stream Analytics job. Add the Event Hub as an input Go to your Stream Analytics job and navigate to the Inputs page under Job Topology. Select Add Stream Input > Event Hub. In the input properties window, search and select your Event Hub and select Managed Identity from the Authentication mode drop-down menu. Fill out the rest of the properties and select Save. Add the Event Hub as an output Go to your Stream Analytics job and navigate to the Outputs page under Job Topology. Select Add > Event Hub. In the output properties window, search and select your Event Hub and select Managed Identity from the Authentication mode drop-down menu. Fill out the rest of the properties and select Save.
https://docs.microsoft.com/en-us/azure/stream-analytics/event-hubs-managed-identity?WT.mc_id=AZ-MVP-5003408
CC-MAIN-2021-39
refinedweb
625
53.1
Our assignment was to write a tic-tac-toe program for my programming class. It is person vs. computer and the computer makes "random" moves, even if computer is going to lose they will choose a random place to put their x or o it is all correct, now what I have to do is modify the program so the computer plays "smart", and by smart i mean blocking the player from making a 3 of a kind, etc. so I have no idea how to do that here is my program now: #include <iostream> using namespace std; void clearBoard(int board[]); void drawBoard(int board[]); int getPlayerMove(int player); int makeRandMove(int player); bool isMoveValid(int boardp[], int move); bool isaWin(int board[], int move); const int board_size = 9; int main() { int board[board_size]; int turn = 0; int move = 10; srand(time(0)); clearBoard(board); while(!isaWin(board, move)){ drawBoard(board); if(2 == turn) turn = 1; else turn = 2; do { if(2 == turn) move = getPlayerMove(turn); else move = makeRandMove(turn); } while(!isMoveValid(board, move)); board[move] = turn; } drawBoard(board); cout << "Player " << turn << " wins." << endl; return 0; } void clearBoard(int board[]) { int i; for(i = 0; i < board_size; ++i) { board[i] = -i - 1; } } void drawBoard(int board[]) { int i, j; for(i = 0; i <= 6; i = i+3) { for(j = 0; j < 3; ++j) { if(board[i + j] == 2) cout << "X"; else if(board[i + j] == 1) cout << "O"; else cout << "_"; } cout << endl; } } int getPlayerMove(int player) { int move; cout << "Player " << player << " enter move: "; cin >> move; return move; } int makeRandMove(int player) { cout << "Computer (player " << player << ") moving." << endl; return rand() % board_size; } bool isMoveValid(int board[], int move) { if(board[move] < 0) return true; return false; } bool isaWin(int board[], int move) { if((board[0] == board[1] && board[0] == board[2]) || (board[3] == board[4] && board[3] == board[5]) || (board[6] == board[7] && board[6] == board[8]) || (board[0] == board[3] && board[0] == board[6]) || (board[1] == board[4] && board[1] == board[7]) || (board[2] == board[5] && board[2] == board[8]) || (board[0] == board[4] && board[0] == board[8]) || (board[2] == board[4] && board[2] == board[6])) return true; return false; }
https://www.daniweb.com/programming/software-development/threads/118154/c-smart-tic-tac-toe-game
CC-MAIN-2019-30
refinedweb
361
51.86
It isn’t common for a relatively small microcontroller to have two cores. This is precisely why we will highlight today this marvel of ESP32, which is Multi-Core Programming. I have already mentioned this in other videos, which I intend to talk more about in a complete playlist. I also plan to discuss the FreeRTOS (Free real-time operating systems), which is an operating system for microcontrollers that allows for easy programming, deployment, protection, connection and management for devices of small and low capacity. Returning to the topic of today’s project, let's create a program where different tasks are executed simultaneously in different cores. To do so, we will introduce you to Multi-Core Programming in ESP32 in order to know its main functions. In our assembly, as shown in the image above, we use an i2c display, a button, a LED, and a source from 110 to 5v, which feeds our circuit. Step 1: Introduction One of the many interesting features of ESP32 is that it has two Tensilica LX6 cores, which we can take advantage of to run our code with higher performance and more versatility. • Both the SETUP and the main functions of the LOOP are executed with a priority of 1 and in core 1. • Priorities can range from 0 to N, where 0 is the lowest priority. • Core can be 0 or 1. Tasks have an assigned priority so the scheduler can decide which task to execute. High-priority tasks that are ready to run will have preference over lower priority tasks. In an extreme case, the highest priority task needs the CPU all the time, and the lowest priority task would never run. But with two cores available, the two tasks can be performed as long as they are assigned to different cores. Step 2: Functions Let's look now at some of the important functions we can use. xTaskCreate Create a new task and add it to the list of tasks that are ready to be executed. xTaskCreatePinnedToCore This function does exactly the same thing as xTaskCreate. However, we have an additional parameter, which is where we will define in which core the task will be executed. xPortGetCoreID This function returns the number of the kernel that is executing the current task. TaskHandle_t This is the reference type for the created task. The xTaskCreate call returns (as a pointer to a parameter) a TaskHandle_t that can be used as a parameter by vTaskDelete to delete a task. vTask Delete a created task. Step 3: WiFi NodeMCU-32S ESP-WROOM-32 Step 4: 16x2 Serial LCD Display With I2c Module Step 5: Assembly Our electric scheme is quite simple. Just follow it, and the project will work. Step 6: Library Step 7: Program We will make a simple program that consists of making a LED blink and count how many times it blinks. We will also have a button that, when pressed, changes a variable of its state control. The display will update all this information. We will program the display update task to run on the processor core UM, and the other operations will be on the ZERO core. Step 8: Libraries and Variables First, let's include the library responsible for display control and define the necessary settings. It’s also important to point out the variables for control of the LED, indicate the pins that will be used, as well as the variables that indicate the core. #include <Wire.h> #include <LiquidCrystal_IC2.h> //biblioteca responsável pelo controle do display LiquidCrystal_I2C lcd(0x27, 16, 2); //set the LCD address to 0x27 for a 16 chars and 2 line display int count = 0; int blinked = 0; String statusButton = "DESATIVADO"; //pinos usados const uint8_t pin_led = 4; const uint8_t pin_btn = 2; //variaveis que indicam o núcleo static uint8_t taskCoreZero = 0; static uint8_t taskCoreOne = 1; Step 9: Setup In this part, we initialize the LCD with the SDA and SCL pins. We turn on the display light, and create a task that will be executed in the coreTaskZero function, running in core 0 with priority 1. void setup() { pinMode(pin_led, OUTPUT); pinMode(pin_btn, INPUT); //inicializa o LCD com os pinos SDA e SCL lcd.begin(19, 23); // Liga a luz do display lcd.backlight(); lcd.setCursor(0, 0); lcd.print("Piscadas:"); //cria uma tarefa que será executada na função coreTaskZero, com prioridade 1 e execução no núcleo 0 //coreTaskZero: piscar LED e contar quantas vezes xTaskCreatePinnedToCore( coreTaskZero, /* função que implementa a tarefa */ "coreTaskZero", /* nome da tarefa */ 10000, /* número de palavras a serem alocadas para uso com a pilha da tarefa */ NULL, /* parâmetro de entrada para a tarefa (pode ser NULL) */ 1, /* prioridade da tarefa (0 a N) */ NULL, /* referência para a tarefa (pode ser NULL) */ taskCoreZero); /* Núcleo que executará a tarefa */ delay(500); //tempo para a tarefa iniciar Also in the Setup, we created a task that will be executed in the coreTaskOne function with priority 2. We have also created another task that will be executed in the coreTaskTwo function, running in core 0 with priority 2. //cria uma tarefa que será executada na função coreTaskOne, com prioridade 2 e execução no núcleo 1 //coreTaskOne: atualizar as informações do display xTaskCreatePinnedToCore( coreTaskOne, /* função que implementa a tarefa */ "coreTaskOne", /*One); /* Núcleo que executará a tarefa */ delay(500); //tempo para a tarefa iniciar //cria uma tarefa que será executada na função coreTaskTwo, com prioridade 2 e execução no núcleo 0 //coreTaskTwo: vigiar o botão para detectar quando pressioná-lo xTaskCreatePinnedToCore( coreTaskTwo, /* função que implementa a tarefa */ "coreTaskTwo", /*Zero); /* Núcleo que executará a tarefa */ } void loop() {} Step 10: TaskZero This function will change the LED status every second and will blink each time (cycle on and off), incrementing our blinked variable. //essa função ficará mudando o estado do led a cada 1 segundo //e a cada piscada (ciclo acender e apagar) incrementará nossa variável blinked void coreTaskZero( void * pvParameters ){ String taskMessage = "Task running on core "; taskMessage = taskMessage + xPortGetCoreID(); //Serial.println(taskMessage); //log para o serial monitor while(true){ digitalWrite(pin_led, !digitalRead(pin_led)); if (++count % 2 == 0 ) blinked++; delay(1000); } } Step 11: TaskOne This function will only be responsible for updating the information on the display every 100m. //essa função será responsável apenas por atualizar as informações no //display a cada 100ms void coreTaskOne( void * pvParameters ){ while(true){ lcd.setCursor(10, 0); lcd.print(blinked); lcd.setCursor(0,1); lcd.print(statusButton); delay(100); } } Step 12: TaskTwo Finally, this function will be responsible for reading the button state and updating the control variable. //essa função será responsável por ler o estado do botão //e atualizar a variavel de controle. void coreTaskTwo( void * pvParameters ){ while(true){ if(digitalRead(pin_btn)){ statusButton = "Ativado "; } else statusButton = "Desativado"; delay(10); } } Discussions Question 4 months ago on Step 12 Dear Fernando Thank you for this tutorial. Its very clear and complete. Im trying to run a dual core esp32 with one core wifi y task reading temp sensor and other core uploading data to Internet. When I try it crashes. Did you ever try somerhing similar? Can you help me with any example. Thank you in avance Regards Pablo
https://www.instructables.com/id/ESP32-With-Arduino-IDE-Multi-Core-Programming/
CC-MAIN-2019-04
refinedweb
1,187
50.06
Framing the problem Iterating and displaying data is a very common part of building applications. In React (and other frameworks), the most basic way of doing this is hard coding the entries into your HTML (view code): var Hello = React.createClass({ render: function() { return ( <ul> <li>Jake</li> <li>Jon</li> <li>Thruster</li> </ul> ) } }); Easy enough! But what if our names were in an array, and couldn’t be hard coded into the component? In other words, how could we iterate over [‘Jake’, ‘Jon’, ‘Thruster’] and create LI’s for each of them? Vanilla Javascript to the rescue One of the best things about React is that doesn’t require you to learn a myriad of new methods to manipulate & render data. Instead, it relies heavily on the Javascript language itself for these common tasks. Remember that React will evaluate any Javascript expression you provide it, and this also includes arrays (it renders each array entry, starting at index 0). For those of you who are Javascript experts, you’ll know that we can use Javascript’s map method to quickly iterate over our array and create a new one with our desired values! Not so fast though — also remember that <li>Jake</li> actually boils down to React.createElement('li', null, ‘Jake’), so our elements are actually just methods that will be executed. What this means is that we need to convert our array from [‘Jake’, ‘Jon’, ‘Thruster’] to [React.createElement('li', null, ‘Jake’), React.createElement('li', null, ‘Jon’), React.createElement('li', null, ’Thruster’)] — and since we’re using JSX (thank you programming gods), it would instead look super pretty: [<li>Jake</li>, <li>Jon</li>, <li>Thruster</li>]. Put that all together and you get: var Hello = React.createClass({ render: function() { var names = ['Jake', 'Jon', 'Thruster']; return ( <ul> {names.map(function(name, index){ return <li key={ index }>{name}</li>; })} </ul> ) } }); Note that we're using the 'key' attribute to ensure our elements are uniquely identified. Our component is now programmatically listing out Jake, Jon and Thruster! You can check out the working code here! Best practices The last thing we’ll do is tidy our code up a bit. As your components grow in size you’ll want to abstract as much code out of the return statement as possible. This typically requires setting your desired output in variables. It’s quite simple to do this: var Hello = React.createClass({ render: function() { var names = ['Jake', 'Jon', 'Thruster']; var namesList = names.map(function(name){ return <li>{name}</li>; }) return <ul>{ namesList }</ul> } }); You can check out the working code here! And that’s it, you’ve mastered the art of iterating & rendering loops in React! If you’re interested in learning more, this post from Jason Lee is fantastic and worth a read. What's Next To really dig deep into React, check out this full day workshop from Kent C Dodds on the fundamentals of react. And don't miss out on out our sale on Pro memberships as well.
https://thinkster.io/tutorials/iterating-and-rendering-loops-in-react
CC-MAIN-2019-13
refinedweb
503
64.61
JSF 2.2 and HTML 5 Placeholder (Passthrough) The Java EE 7 version of JSF (2.2) enables the definition of any arbitrary attributes, which are not going to be processed by the JSF runtime and directly passed to the browser.However, you will have to declare an additional namespace and qualify the attribute with the namespace: <html xmlns="" xmlns: <!-- ... --> <h:inputText <!-- ... --> The generated output is: <input type="text" name="j_idt9:j_idt10:j_idt11" placeholder="write something"> See you at Java EE Workshops at MUC Airport, especially at Java EE UI! "p:" to provoke all the PrimeFaces fans out there..? :-) Posted by Martin Kofoed on June 24, 2013 at 02:47 PM CEST # especially for Java EE UI: Have a look at CatainCasa server-centric JavaFX and Swing UI framework Posted by Dan on June 24, 2013 at 03:05 PM CEST # Good news but sad choice for the namespace prefix. Did somebody at Oracle thought that many of us use PrimeFaces and that unfortunately that "p:" was already taken? Posted by Andrea Pucci on June 26, 2013 at 01:39 PM CEST # @Martin Kofoed @Andrea Pucci Are you aware that the "p" is not fixed? if you already use th p prefix for PrimeFaces you can simply change the declaration to: xmlns:ph="" and use "ph" as the prefix... Posted by Rivas on June 27, 2013 at 09:06 AM CEST # Well, PrimeFaces Team prefers pt for this; Posted by Cagatay Civici on June 29, 2013 at 09:42 PM CEST # Hi Adam, How can i passthrough a placeholder with the value been read from a resource bundle for i18n having it not to be escaped? Ej: someProperty=<hi world> <h: inputText .... p: By default someProperty it's gonna be escaped so '<' and '>' are gonna be encoded Posted by Joaquin Moreira on July 31, 2013 at 01:30 AM CEST # Hello! I am beginner of Java EE 7. Now I am learning JSF 2.2 by using Glassfish 4.0 and Eclipse. While I writing HTML5 support JSF 2.2, eclipse validator show a warning message that they can't find the name space xmlns:ph="". How can I solve this problem. Regards Posted by Min Lwin on September 17, 2013 at 01:20 AM CEST # Thanks, nice tip Posted by Binh Nguyen on June 19, 2015 at 08:15 AM CEST # I have mental problems. Posted by Man on August 20, 2015 at 03:00 PM CEST #
https://adambien.blog/roller/abien/entry/jsf_2_2_and_html
CC-MAIN-2020-29
refinedweb
408
70.02
crowdflower 0.0.12 CrowdFlower API - Python client Client library for interacting with the CrowdFlower API with Python. Installation Install from PyPI: easy_install -U crowdflower Or install the latest version from GitHub: git clone cd crowdflower python setup.py develop Basic usage Import like: import crowdflower CrowdFlower API keys are 20 characters long; the one below is just random characters. (You can find your API key at make.crowdflower.com/account/user.) conn = crowdflower.Connection(api_key=') Inspecting existing jobs Loop through all your jobs and print the titles: for job in conn.jobs(): print job.properties['title'] Creating a new job Create a new job with some new units: data = [ {'id': '1', 'name': 'Chris Narenz', 'gender_gold': 'male'}, {'id': '2', 'name': 'George Henckels'}, {'id': '3', 'name': 'Maisy Ester'}, ] job = conn.upload(data) update_result = job.update({ 'title': 'Gender labels', 'included_countries': ['US', 'GB'], # Limit to the USA and United Kingdom # Please note, if you are located in another country and you would like # to experiment with the sandbox (internal workers) then you also need # to add your own country. Otherwise your submissions as internal worker # will be rejected with Error 301 (low quality). 'payment_cents': 5, 'judgments_per_unit': 2, 'instructions': 'some <i>instructions</i> html', 'cml': 'some layout cml, e.g., ' '<cml:text', 'options': { 'front_load': 1, # quiz mode = 1; turn off with 0 } }) if 'errors' in update_result: print(update_result['errors']) exit() job.gold_add('gender', 'gender_gold') Launch job for on-demand workers (the default): job.launch(2) Launch job for internal workers (sandbox): job.launch(2, channels=['cf_internal']) Check the status of the job: print job.ping() Clean up; delete all the jobs that were created by the above example: for job in conn.jobs(): if job.properties['title'] == 'Gender labels': print 'Deleting Job#%s' % job.id print job.delete() View annotations collected so far: for row in job.download(): print row Debugging / Logging To turn on verbose logging use the following in your script: import logging logging.basicConfig(level=logging.DEBUG) The CrowdFlower blog is the definitive (but incomplete) source for API documentation: The source code for the official ruby-crowdflower project is also helpful in some cases. This package uses kennethreitz’s Requests to communicate with the CrowdFlower API over HTTP. Requests is Apache2 licensed. Support Found a bug? Want a new feature? File an issue! Contributing We love open source and working with the larger community to make our codebase even better! If you have any contributions, please fork this repository, commit your changes to a new branch, and then submit a pull request back to this repository (peoplepattern/crowdflower). To expedite merging your pull request, please follow the stylistic conventions already present in the repository. These include: - Adhere to PEP8 - We’re not super strict on every single PEP8 convention, but we have a few hard requirements: - Four-space indentation - No tabs - No semicolons - No wildcard imports - No trailing whitespace - Use docstrings liberally The Apache License 2.0 contains a clause covering the Contributor License Agreement.): - 53 downloads in the last day - 422 downloads in the last week - 1240 downloads in the last month - Author: Christopher Brown - Keywords: crowdflower crowdsourcing api client - License: Copyright 2014 People Pattern: chbrown - DOAP record: crowdflower-0.0.12.xml
https://pypi.python.org/pypi/crowdflower/0.0.12
CC-MAIN-2015-32
refinedweb
533
56.66
02 December 2011 16:53 [Source: ICIS news] LONDON (ICIS)--?xml:namespace> The project will connect German chemical major BASF’s petrochemicals hub at Erwin Fellner, a spokesman for Ethylen-Pipeline Sud (EPS), told ICIS that an administrative court in Baden-Wurttemberg state had ruled against property owners who were seeking to block the pipeline. The court’s decision allows EPS to complete the remaining 1.5km of the 370km pipeline and to begin operations, but at its own risk as there are still cases against the project pending before higher courts, Fellner said. In Rhineland Palatinate and Bavaria the pipeline is already completed. Klaus Thiel, an EPS spokesperson who focuses on the project’s legal troubles in Baden-Wurttemberg, said about 20 plaintiffs are still pursuing cases before an administrative court in Stuttgart and before Germany’s federal constitutional court. The constitutional court would look at the legal basis of a Baden-Wurttemberg state law that was passed to allow certain expropriations to facilitate the project, Thiel said. Thiel said EPS was “about 90%” sure that those cases would go in its favour, given that all court decisions so far were favourable. The consortium will therefore go ahead to complete and start the pipeline up, he added. Meanwhile, EPS could negotiate further with the plaintiffs, who may still withdraw their cases, he added. However, he would not rule out that “in a worst case”, EPS may be ordered to stop operating the line if the courts should rule against it. So far, court cases and objections have delayed the project’s start-up by about four years, driving costs up to around €200m ($270m). As part of efforts to accommodate some property owners, the pipeline’s overall length had to be extended by 10km, which added to costs. The project, which received a €45m subsidy from the Following start-up in mid-2012, capacity would be gradually ramped up to its 400,000 tonnes/year volume, the officials said. EPS’ stakeholders include BASF, the Netherlands-based ethylene producer LyondellBasell, Austrian polyethylene producer Borealis, Swiss speciality chemicals producer Clariant, Austrian oil and gas firm OMV, German PVC producer Vinnolit and German chemical company Wacker. However, the line will not be reserved to those firms alone. Under the project’s “common carrier” concept, The project will connect ($ = €0.75) For more on BASF, LyondellBasell and other producers visit ICIS company intelligenceFor
http://www.icis.com/Articles/2011/12/02/9513721/german-ethylene-pipeline-start-up-set-for-mid-2012-after-court-ruling.html
CC-MAIN-2015-06
refinedweb
400
50.16
Running the Table With JMesa Shhhh. I’ll tell you a secret. I don’t like tables. I know. Shocking, isn't it? Don't get me wrong: I don't dislike tables per se. They're great for displaying tabular material. (For page organization, not so much.) But I so dislike the code needed to build a table within a JSP. It usually comes down to something like this: <c:forEach <c:if <table border="0" cellspacing="0" cellpadding="0"> <tr> <th>User ID</th> <th>Name</th> <th>Email</th> </tr> </c:if> <c:choose> <c:when <tr class="even"> </c:when> <c:otherwise> <tr class="odd"> </c:otherwise> </c:choose> <td>${row.userID}</td> <td>${row.name}</td> <td>${row.email}</td> </tr> <c:if </table> </c:if> </c:forEach> All that iterative logic simply looks incomprehensible to me. It's still better than scriptlets or custom tag libraries (both of which were, to be sure, phenomenal in their time), but it's an undigestible mass, and even if I do step through it line by line and understand what it does, I'm still left with just a table. Users accustomed to active, Javascript-assisted widgets don't respond to tables that just lie there. Many more lines of code will be needed to enable them to do useful things like paginating through long lists of items, sorting by column values, and the like. It'll be an unholy mix of HTML, JSP directives, JSP tags, EL, Javascript, Java, XML, properties files, and so forth. The whole thing seems so error-prone (note to self: more code + more languages = more "opportunities" for bugs). But recently I discovered an open-source Java library called JMesa that provides another way. I'm going to share with you some of the things I've found in JMesa, building up an HTML page containing a table from nothing to, well, considerably more than nothing. There's a good deal of code here, to give you a sense of the JMesa API; hopefully. you'll come away with some ideas about how you can use JMesa in your own projects. I won't bother with package declarations, imports, or code not relevant to the point at hand; the complete code is available for download in the form of an Eclipse project. Installation instructions will be found at the end of this article. Join me in exploring JMesa! Preparation A Page to Show Before we can get to JMesa, though, we'll need a few things: a page within which to display our table, for instance. In fact, we'll learn even more if we put this page in a context. I have recently fallen in like with Spring MVC and so will use that to build a simple site with a few pages. Just to be clear, while Spring dependency injection and utilities are woven into the code below, JMesa does not depend upon Spring. The pages are not fancy, and I am going to skip most of the setup. Everything is included in the download, of course. One thing I shouldn't skip is the controller for the search results page, the page within which we will build our table. We'll start with pretty much the simplest functionality we can: public class SimpleSearchController extends AbstractController { @Override protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { return new ModelAndView("simple-results", "results", "Here we will display search results"); } } For those not familiar with Spring MVC, the ModelAndView return value contains a string that will be resolved to a view (in this project, it is resolved to "/WEB-INF/jsp/simple-results.jsp"), and a key-value pair (the second and third constructor arguments) that can be accessed using EL on the JSP page: <%@ taglib prefix="spring" uri="" %> <%@ taglib prefix="tags" tagdir="/WEB-INF/tags" %> <tags:layout-top> <jsp:attribute<spring:message</jsp:attribute> <jsp:attribute<spring:message</jsp:attribute> </tags:layout-top> ${results} <tags:layout-bottom/> Finally, we use the Spring jmesa-servlet.xml configuration file to create and associate a URL with our controller: <bean id="simpleSearchController" class="com.javalobby.article.jmesa.web.SimpleSearchController"/> <bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"> <property name="mappings"> <props> <prop key="/welcome.html">welcomeController</prop> <prop key="/search.html">simpleSearchController</prop> </props> </property> </bean> Clicking on the "Search" link in the menu now produces: Figure 1.: A simple page for our table All right, not much. But it's the page we need. Something to Display Another thing we need before we can build a table is something to show in it. This "domain" object should be pretty easy to display: public class HelloWorld implements Comparable<HelloWorld> { private int pk; private String hello = "Hello"; private String world = "world"; private String from = "from"; private String firstName; private String lastName; private String format = "{0}, {1}! {2} {3} {4}"; // ... accessors and mutators public String toString() { return MessageFormat.format(getFormat(), hello, world, from, getFirstName(), getLastName()); } // ... implementations of equals, hashCode, and compareTo } Persistence Service Of course, we need instances of this domain object. Normally, we'd get them from a persistence service; for now, we'll just create them in memory: public class HelloWorldService { private int nextId; private Set<HelloWorld> helloWorlds = new TreeSet<HelloWorld>(); public HelloWorldService() { nextId = 1; helloWorlds.add(newInstance("Albert", "Einstein")); helloWorlds.add(newInstance("Grazia", "Deledda")); helloWorlds.add(newInstance("Francis", "Crick")); helloWorlds.add(newInstance("Linus", "Pauling")); helloWorlds.add(newInstance("Theodore", "Roosevelt")); helloWorlds.add(newInstance("Hideki", "Yukawa")); helloWorlds.add(newInstance("Harold", "Urey")); helloWorlds.add(newInstance("Barbara", "McClintock")); helloWorlds.add(newInstance("Hermann", "Hesse")); helloWorlds.add(newInstance("Mikhail", "Gorbachev")); helloWorlds.add(newInstance("Amartya", "Sen")); helloWorlds.add(newInstance("Albert", "Gore")); helloWorlds.add(newInstance("Amnesty", "International")); helloWorlds.add(newInstance("Daniel", "Bovet")); helloWorlds.add(newInstance("William", "Faulkner")); helloWorlds.add(newInstance("Otto", "Diels")); helloWorlds.add(newInstance("Marie", "Curie")); } public Set<HelloWorld> findAll() { return helloWorlds; } private HelloWorld newInstance(String firstName, String lastName) { HelloWorld hw = new HelloWorld(); hw.setPk(nextId++); hw.setFirstName(firstName); hw.setLastName(lastName); return hw; } } That's that. Now we're ready to focus on JMesa. - Login or register to post comments - 15075 reads - Printer-friendly version (Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.) nfrankel replied on Wed, 2008/06/18 - 10:19am Hello, Don't get me wrong, but displaying tabular data in HTML is done since a loooooong time with the DisplayTaglib. There's a short article on my blog if you're interested. They use taglibs but I see it as an advantage. For more informations, see their site or their live demos which are really bluffing when you see the tiny amount of config needed on the JSP. Cheers. Nicolas bguerout replied on Wed, 2008/06/18 - 10:53am I've a very bad recollection of the last time I've tried to create a table JMesa (old but wonderfull displaytag solved easly the problem). But, may be, this tutorial will help me to succeed the next time i'll try JMesa. jeff_johnston replied on Wed, 2008/06/18 - 7:19pm What a great article...I was very excited to read this today :)! It was very well thought out and complete. You really tapped into just how customizable JMesa is. By design, just about every aspect of JMesa can be tweaked and modified with very little code. I will for sure link to this article from the home page of JMesa and reference it in the tutorials! I am going to see about implementing your extended attributes notion. I think that is a nice improvement! I also hope to make some adapters for Spring so that those that choose to use the Spring framework can tie into Spring's notion of messages and preferences. It wouldn't be hard to do and would be a completely optional runtime dependency so non-Spring developers would not be effected. Nicolas, there is a complete tag library with JMesa. The tag library is just a thin wrapper around the API. In addition JMesa has first class Groovy support and, in the next release, will even have Grails support with GSP Tags. The latter is currently being built by a member of the JMesa community and I am very excited to see that work as well. I have seen other work by this developer and it is always top notch. Also, as the article mentions, JMesa can also be put in an editable mode and will track your changes automatically. bguerout, sorry to hear your first go around wasn't so great. How long ago was that? Based on how few questions I get nowadays I can say with confidence that your next experience should be really good. It is a very solid API! If you have any problems either post on the groups or email me directly. I try to get back ASAP as I know how frustrating it is to wait for replies when there are questions. I wanted to mention that JMesa was designed to be an API first and foremost. It also embraces the Model 2 environment. Both of these give it the advantage of being able to use JMesa with just about any framework and regardless of the view technology being used. David, if you don't mind, I also wanted to mention a few subtle improvements to your example that may make things easier: Once again, congratulations on a great article! -Jeff Johnston David Sills replied on Sun, 2008/06/22 - 1:59am in response to: nfrankel Nicolas: Thanks for your comment and thanks for reading. It was, in fact, using Display Taglib for a while that got me to looking around for something easier to customize and with a few more features. I agree completely that if it meets your needs, it's a terrific library. It simply didn't meet mine. That said, chacun à son goût, as the French say. The beauty of the Java world today is that we have enough open-source code around that everyone can use whatever they feel comfortable with. Cheers, David Sills David Sills replied on Sun, 2008/06/22 - 2:01am in response to: jeff_johnston Jeff: Thanks to you for authoring JMesa! Without it, of course, the article would have been, shall we say, less interesting? I have incorporated some of your comments into the code and resources. I would be pleased if you wanted to link to the article. All the best! David Sills blitzmoiko replied on Fri, 2008/08/22 - 9:07pm I guess were on same track, I'm using JMesa for quite a while, in my swf application. If I do have problems, could I ask for help? David Sills replied on Sat, 2008/08/23 - 1:23pm in response to: blitzmoiko
http://java.dzone.com/articles/running-table-with-jmesa
crawl-002
refinedweb
1,798
65.52
Hey All I'm having trouble making executables with py2exe. I'm using Python 2.6 and I'm trying to make the simple 'Hello World!' program work as an executable. My setup script is as follows: from distutils.core import setup import py2exe setup(console=['hello.py']) When I run the setup script in the command prompt 'C:\Python26\setup.py py2exe', I get the error message: 'error: hello.py: No such file or directory' I've tried importing hello.py using IDLE and it works perfectly. Does anyone know why it can't seem to find it when I use the command prompt? I also get a 'DeprecationWarning' but I don't think this is important. My hello.py script and setup.py script are both in the same directory. Any help would be appreciated
https://www.daniweb.com/programming/software-development/threads/209651/py2exe-cannot-import-module
CC-MAIN-2018-22
refinedweb
137
71.92
number and much more. In this article we will learn about the different types of Rotary Encoders and how it work. We will also interface it with Arduino and control the value of an integer by rotating the Encoder and display its value on a 16*2 LCD screen. At the end of this tutorial you will be comfortable with using an Rotary Encoder for your projects. So let’s get started... Materials Required - Rotary Encoder (KY-040) - Arduino UNO - 16*2 Alphanumeric LCD - Potentiometer 10k - Breadboard - Connecting wires How does a Rotary Encoder Work? A Rotary Encoder is an electromechanical transducer, meaning it converts mechanical movements into electronic pulses. It consists of a knob which when rotates will move step by step and produce a sequence of pulse trains with pre-defined width for each step. There are many types of Encoders each with its own working mechanism, we will learn about the types later but for now let us concentrate only on the KY040 Incremental Encoder since we are using it for our tutorial. The internal mechanical structure for the Encoder is shown below. It basically consists of a circular disc (grey colour) with conductive pads (copper colour) placed on top of this circular disc. These conductive pads are placed at an equal distance as shown below. The Output pins are fixed on top of this circular disc, in such a way that when the knob is rotates the conductive pads get in contact with the output pins. Here there are two output pin, Output A and Output B as shown in the figure below. The output waveform produced by the Output pin A and Output B is show in blue and green colour respectively. When the conductive pad is directly under the pin it goes high resulting it on time and when the conductive pad moves away the pin goes low resulting in off time of the waveform shown above. Now, if we count the number of pulses we will be able to determine how many steps the Encoder has been moved. Now the question may arise that, why do we need two pulse signals when one is enough to count the number of steps taken while rotating the knob. This is because we need to identify in which direction the knob has been rotated. If you take a look at the two pulses you can notice that they both are 90° out of phase. Hence when the knob is rotated clockwise the Output A will go high first and when the knob is rotated anti-clockwise the Output B will go high first. Types of Rotary Encoder. KY-040 Rotary Encoder Pinout and description The pinouts of the KY-040 Incremental type rotary encoder is shown below (Switch). Finally it has the two output pins which produce the waveforms as already discussed above. Now let us learn how to interface it with Arduino. Arduino Rotary Encoder Circuit Diagram The complete circuit diagram for Interfacing Rotary Encoder with Arduino is shown in the picture below The Rotary Encoder has 5 pins in the order shown in the label above. The first two pins are Ground and Vcc which is connected to the Ground and +5V pin of the Arduino. The switch of the encoder is connected to digital pin D10 and is also pulled high though a 1k resistor. The two output pins are connected to D9 and D8 respectively. To display the value of the variable which will be increased or decreased by rotating the Rotary encoder we need a display module. The one used here is commonly available 16*2 Alpha numeric LCD display. We have connected the display to be operated in 4-bit mode and have powered it using the +5V pin of Arduino. The Potentiometer is used to adjust the contrast of the LCD display. If you want to know more about Interfacing LCD display with Arduino follow the link. The complete circuit can be built on top of a breadboard, my looked something like this below once all the connections were done. Programming your Arduino for Rotary Encoder It is fairly easy and straight forward to program the Arduino board for interfacing a Rotary Encoder with it if you had understood the working principle of a Rotary Encoder. We simply have to read the number of pulse to determine how many turns the encoder has made and check which pulse went high first to find in which direction the encoder was rotated. In this tutorial we will display the number that is being increment or decrement on the first row of the LCD and the direction of the Encoder in the second line. The complete program for doing the same can be found at the bottom of this page with a Demonstration Video, it does not require any library. Now, let’s split the program into small chunks to understand the working. Since we have used an LCD display, we include the Liquid crystal library which is by default present in the Arduino IDE. Then we define pins for connecting LCD with Arduino. Finally we initialise the LCD display on those pins. #include <LiquidCrystal.h> //Default Arduino LCD Library is included const int rs = 7, en = 6, d4 = 5, d5 = 4, d6 = 3, d7 = 2; //Mention the pin number for LCD connection LiquidCrystal lcd(rs, en, d4, d5, d6, d7); lcd.begin(16, 2); //Initialise 16*2 LCD Next inside the setup function, we display an introductory message on the LCD screen, and then wait for 2 seconds so that that message is user readable. This is to ensure that the LCD is working properly. lcd.print(" Rotary Encoder "); //Intro Message line 1 lcd.setCursor(0, 1); lcd.print(" With Arduino "); //Intro Message line 2 delay(2000); lcd.clear(); The Rotary encoder has three output pins which will be an INPUT pins for the Arduino. These three pins are the Switch, Output A and Output B respectively. These are declared as Input using the pinMode function as shown below. //pin Mode declaration pinMode (Encoder_OuputA, INPUT); pinMode (Encoder_OuputB, INPUT); pinMode (Encoder_Switch, INPUT); Inside the void setup function, we read the status of the output A pin to check the last status of the pin. We will then use this information to compare with the new value to check which pin (Output A or Output B) has gone high. Previous_Output = digitalRead(Encoder_OuputA); //Read the inital value of Output A Finally inside the main loop function, we have to compare the value of Output A and Output B with the Previous Output to check which one goes high first. This can be done by simply comparing the value of current output of A and B with the previous output as shown below. if (digitalRead(Encoder_OuputA) != Previous_Output) { if (digitalRead(Encoder_OuputB) != Previous_Output) { Encoder_Count ++; lcd.clear(); lcd.print(Encoder_Count); lcd.setCursor(0, 1); lcd.print("Clockwise"); } In the above code the second if condition gets executed if Output B has changed from the previous output. In that case the value of the encoder variable is incremented and the LCD displays that the encoder is rotated in clockwise direction. Similarly if that if condition fails, in the subsequent else condition we decrement the variable and display that the encoder is rotated in the anticlockwise direction. The code for the same is shown below. else { Encoder_Count--; lcd.clear(); lcd.print(Encoder_Count); lcd.setCursor(0, 1); lcd.print("Anti - Clockwise"); } } Finally, at the end of the main loop we have to update the previous output value with the current output value so that the loop can be repeated with the same logic. The following code does the same Previous_Output = digitalRead(Encoder_OuputA); Another optional thing is to check if the switch on the Encoder is pressed. This can be monitored by checking the switch pin on the rotary coder. This pin is a active low pin, meaning that it will go low when the button is pressed. If not pressed the pin stays high, we also have used a pull up resistor to make sure the stays high when switch is not pressed thus avoiding floating point condition. if (digitalRead(Encoder_Switch) == 0) { lcd.clear(); lcd.setCursor(0, 1); lcd.print("Switch pressed"); } Working of Rotary Encoder with Arduino Once the hardware and code is ready, just upload the code to the Arduino board and power up the Arduino Board. You can either power it through the USB cable or use a 12V adapter. When powered the LCD should display the intro message and then get blank. Now rotate the rotary encoder and you should see the value begin incremented or decremented based on the direction you rotate. The second line will show you if the encoder is being rotated in clockwise or anti-clockwise direction. The picture below shows the same Also when the button is pressed, the second line will display that the button is pressed. The complete working can be found in the video below. This is just a sample program to interface the Encoder with Arduino and check if it is working as expected. Once you get here you should be able to use the encoder for any of your projects and program accordingly. Hope you have understood the tutorial and things worked as it is supposed to. If you have any problems use the comment section or the forums for technical help. /* * Interfacing Rotary Encoder with Arduino * Dated: 6-7-2018 * Website: * *"); } } Jul 27, 2018 thanks for showing some example and carrying on to send for me the new vision one to update old encoder Dec 27, 2018 Neat! Found an encoder (1 of an order of 5) made backwards.
https://circuitdigest.com/microcontroller-projects/interfacing-rotary-encoder-with-arduino
CC-MAIN-2019-43
refinedweb
1,613
61.26
Artefacts while copying pixelvalues Hi everybody, I would like to blend pictures manually using a loop. In detail I want to copy the white pixels from a binary image (0==black, 255==white, not other values possible) to a new Picture which is at the beginning a Mat just including black pixels. My code works fine if I use a Mat created with white pixels. But if I use my binary images I load into OpenCV I get artefacts. I cannot understand why this is happening. If I look in the source image in OpenCV the pixels have just 0 or 255, but if I vary with the thresholdvalue I get different Artefacts. Normaly intensity >=1 should work well, but If I use for example 100 I get still differend artefacts. This is the code I use: #include <opencv2/highgui/highgui.hpp> #include <iostream> using namespace std; using namespace cv; void Vblend(Mat src, Mat blend) { int colu, row; int intensity; for (row=0; row<=480; row++) { for (colu=0; colu<=640; colu++) { intensity = src.at<uchar>(row, colu); if(intensity >=1) {blend.at<uchar>(row, colu)=255;} } } } int main() { Mat src= imread("pic.jpg",CV_LOAD_IMAGE_GRAYSCALE); Mat blend(480,640,CV_8UC1,Scalar(0)); namedWindow("src"); namedWindow("blend"); Vblend(src,blend); imshow("src", src); imshow("blend",blend); while(char(waitKey(1)) != 'q') {} return 0; } In this picture you can see the original on the left and the artefacts on the right. How can I eliminate the artefacts? Thank you very much for your help :-) you're setting the blend pixel for anything > 1, maybe you need a higher threshold level than 1. also, your whole function could be as short as : Mat blend = img > 30; and look at threshold() .
https://answers.opencv.org/question/31668/artefacts-while-copying-pixelvalues/
CC-MAIN-2021-17
refinedweb
288
64
[Solved] Independant Threads with separate CommandLine Hello, I have a main Qt-Thread (main.exe), which in turn starts an executable jar via JNI (lets say external.jar). This external.jar listens continuously on a special socket(localhost, PORT). The expected message should be sent by the main.exe, which is blocked by the Listening external.jar. I would like to run that jar in a separate thread, and if possible with a separate cmd.exe. @ #include <jni.h> #include "ExternJar.h" #pragma comment (lib,"C:\Program Files\Java\jdk1.6.0_26\lib\jvm.lib") /// Constructor ExternJar::ExternJar(const char* pPathToJar, const char* pPathToLib, const char t_argv, const char t_path2Package, const char t_methodName) { int oi = 0; options[oi++].optionString = const_cast<char>(pPathToJar); vm_args.nOptions = oi; vm_args.version = JNI_VERSION_1_6; vm_args.options = options; vm_args.ignoreUnrecognized = JNI_FALSE; argumentString = t_argv; path2Jar = pPathToJar; path2Lib = pPathToLib; packagePath = t_path2Package; methodName = t_methodName; debugMode = 0; } void ExternJar::setClassName() { switch(JNI_CreateJavaVM( &jvm,(void **)&env, &vm_args)) { case JNI_OK: printf("\nJVM created --> Ready ...\n"); } if( NULL == (cls = env->FindClass(packagePath)) ) printf("\nCan't find class %s\n", packagePath); else printf("\nClass %s found!\n", packagePath); } void ExternJar::setArgCV() { if (!argumentString) return; this->applicationArg0 = env->NewStringUTF(argumentString); this->applicationArgs = env->NewObjectArray(1, env->FindClass("java/lang/String"), applicationArg0); env->SetObjectArrayElement(applicationArgs, 0, applicationArg0); } void ExternJar::setMethodName() { mid = env->GetStaticMethodID(cls, methodName, "([Ljava/lang/String;)V"); printf("\nMethod name set to: %s", methodName); } void ExternJar::callXMethod() { printf("\nCall now \n%s("%s"):", methodName, argumentString); if (mid != NULL) env->CallStaticVoidMethod(cls, mid, applicationArgs); else printf("\nMethod %s corrupted!\n", mid); } JavaVM * ExternJar::getVM() { return this->jvm; } void * ExternJar::getEnv() { return this->env; } bool ExternJar::destroyVM() { printf("\nDestroy VM now!"); if ( this->getVM()->DestroyJavaVM() == 1 ) return true; else return false; } void ExternJar::run() { this->setClassName(); this->setArgCV(); this->setMethodName(); this->callXMethod(); exec(); }@ I have Q_OBJECT set in the Header, it derives from QThread. I have a run() Method which also has a exec()... What else? Thank you for any hints. Cheers Huck Why don't you start the executable using [[Doc:QProcess]]? This gives you an asynchronous for free. But if you want to run with another cmd.exe why don't you use your main as a wrapper for the java process and then use QProcess to start such main? I wonder If can run that in a separate shell? @ QString program = "C:\Program Files\Java\jdk1.7.0\bin\java.exe"; QStringList arguments; arguments << "-jar" << "C:\Project\dist\Project.jar" << "-m" << "module.db" << "-i" << "K;1076076896,1076076882" ; QProcess *myProcess = new QProcess(); myProcess->start(program, arguments); @ What can I search for, when I want to use the wrapper possibility? First: Don't use backslashes for the program path, use forward slashes. Qt will do the translation transparently. Second: Why do you want to involve a shell? It will do nothing else than calling java.exe with your arguments! Does the code you presented not work? The code in my first post works, I can invoke my extarnal.jar from my Qt-Project. But my external.jar continuously listens on the socket to a port, while the expected message is never being sent by my suspended Qt-Project. Therefore I try to make run the external.jar indipendent. I meant the second snippet, using QProcess. Does that work? According to the TaskManager a java.exe appears just for 1-2 seconds and disappears, but the jar is not executed properly. And it does work from the command line itself? How about giving a complete path to your module.db - it's very likely that it is not found by your java application. Yes, when I call "java -jar external.jar -m modules.db ... " it works. I have catched in external.jar already if that modules.db file would not exist, it would throw an FileNotFound-Exception; but I'll try it. Here I call another *.jar, Its a Server, which listens uninterrupted to a socket and prints status messages System.out.println("Bla") continously as well. This jar has an infinte while-loop and does not terminate.. SO when I start this, another cmd.exe opens and that output should be visible? @ void MyClass::runExternal() { QString t_exe_name("java.exe"); QStringList t_exe_arguments; t_exe_arguments << "-jar" << "C:/SD_Projectz/TestServer/dist/TestServer.jar"; QProcess *myProcess = new QProcess(p_ToObject); QString t_joined = t_exe_arguments.join(" "); QString t_all = QString("%1 %2").arg(t_exe_name).arg(t_joined); myProcess->start(t_all); printf("\nWAIT: %d", myProcess->pid()); } @ Each start() my pid() is changed, visible on my Parent command line window, but no other cmd.exe opens for this Process. When p_ToObject (the parent) is deleted, my process is terminated as well, right? Why do you expect a cmd.exe running in case you start a java.exe? These *.jars have System.out.println("kljdas"); so without any further cmd.exe nothing is visible? Then the only way I recognize the running jar is the java.exe in the TaskManager? And since the jar is running continuously, I would say my java.exe should not disappear? Your java.exe does not "disappear". It has no user interface, so it runs in the background, where it belongs. If you want to see the output of stdout or stderr, you should write a .bat file. Either this opens a cmd.exe automatically when run, or you have to give it as argument to cmd.exe. Better yet: if you want to display the output, why not make your Qt application display it instead in some nicely integrated way? QProcess gives you access to the stdout and stderr outputs of the process, after all. To start in a separate shell try to detach the Process. Then you have your own cmd.exe: @myProcess->startDetached(prog_name, prog_arguments);@ But then you have no access to its stdio.. hth! [quote author="huckfinn" date="1317727677"] But my external.jar continuously listens on the socket to a port, while the expected message is never being sent by my suspended Qt-Project.[/quote] If I get it right, you need to start the process in background, since it is a daemon, then startdetached should work for you. If you need to check only the output, you can redirect stdout to a log file (or embed a logging facility in your java application). Yes, startDetached() works... Thank you!
https://forum.qt.io/topic/9995/solved-independant-threads-with-separate-commandline
CC-MAIN-2018-43
refinedweb
1,039
61.73
Donald Ball <balld@webslingerZ.com> writes: > On Wed, 26 Jul 2000, Matt Sergeant wrote: > > > > obviously we could elaborate a bit on the elements and attributes of the > > > xspdoc namespace, but that's the gist. any thoughts from other logicsheet > > > authors? worthwhile to pursue? > > > > This is pretty much the solution from the XSL-list regarding documenting > > stylesheets. Personally I write taglibs either in raw perl for speed, or > > in XPathScript, which means I can use POD to document them, but for XSLT > > based taglibs this seems like an excellent idea. > > hmm, i need to do some homework then. do you happen to have a reference to > this discussion (a URL, a subject line, a person?) is there an actual > standard evolving yet? Norman Walsh's Docbook XSL stylesheets use this doc namespace concept. The <doc:*> elements then contain valid Docbook XML code. Should be quite what you want because Docbook was designed for marking up software docs. Uli
http://mail-archives.apache.org/mod_mbox/cocoon-dev/200007.mbox/%3Cnxcd7jzpunj.fsf@maulaf.isd.uni-stuttgart.de%3E
CC-MAIN-2015-32
refinedweb
157
75.5
This problem seems daunting at first, but a few insights can give way to a greedy strategy for solving it: - You're free to mentally rearrange Elsie's cards however you like within each half, since you know what she's going to play, and you can simply "match" your cards to hers. - It's always best to use your N/2 highest cards in the first half, and your N/2 lowest cards in the second half. This means we can consider both halves completely independently, since we know which cards are going to be played in each. (For the remainder of the analysis, we'll only consider the first half -- the second half can be analyzed with very similar arguments.) - If you're aiming for X points, then you should always aim to beat Elsie's X lowest cards. This is because, if Bessie can beat some set made of X of Elsie's cards, then you can always swap Elsie's cards for lower cards without losing any points. - If you want to beat one of Elsie's cards, you should always do it with the lowest possible card you can do it with. After all, having a higher card in your hand is strictly better than having a lower card in your hand. This hints at a greedy solution: for each of Elsie's cards in ascending order, find the lowest possible card you have that beats it, play that card against hers, and try to beat the next one. Some thinking can convince you that this is the best possible solution, since it's the "lexicographically lowest" -- intuitively, each card played so far is the minimum possible card you could have played, so you'll have the maximum possible number of high cards available for you to use. Here is Mark Gordon's solution, which uses a pair of sweeps through each of the arrays to implement this idea: #include <iostream> #include <vector> #include <cstdio> #include <algorithm> using namespace std;; } sort(A.begin(), A.begin() + N / 2); sort(A.begin() + N / 2, A.end()); rotate(A.begin(), A.begin() + N / 2, A.end()); vector<int> B; for (int i = 0; i < 2 * N; i++) { if (!used[i]) { B.push_back(i); } } int res = 0; for (int i = N / 2, j = N / 2; i < N; i++, j++, res++) { while (j < N && B[j] < A[i]) { j++; } if (j == N) { break; } } for (int i = N / 2 - 1, j = N / 2 - 1; i >= 0; i--, j--, res++) { while (j >= 0 && B[j] > A[i]) { j--; } if (j == -1) { break; } } cout << res << endl; return 0; }
http://usaco.org/current/data/sol_cardgame_gold_dec15.html
CC-MAIN-2018-17
refinedweb
435
71.38
Newsletters are Walling Off Your Freedom I often forget a lot of "tech pundits" come from the finance sector and it's not so much an expertise in technology as it is an expertise in "applied technology"—wherein "applied" relates to capitalism with a potential skew towards financial extraction. This disconnect on my part—having spent over 20 years knee deep in programming—leads to the occasional disagreement with some of these pundits. It happened with Ben Evans over virtual reality. It also happened with Azeem Azhar over Bitcoin. Recently Azhar complained (in his paid newsletter) about only having Facebook for an ID to log into his Oculus. I brought up how this opens people up to data collection, and he was dismissive of my point—not caring about data collection, but instead upset that he had to use a proprietary ID of a different service to log into the device. He believed that his data didn't matter. We should not waste too many cycles on this. The real problem is that I can't use the Oculus without having a Facebook ID. And that Facebook has too much market power. My Oculus data is irrelevant, tbh I don't want to discount Azhar's points on the power of Facebook and the unnecessary usage of a Facebook ID, but his response about his data and Facebook's data collection habits is at odds reality. My response: Although I agree with the market power and login/ID statement to believe that any data is irrelevant is naive. The Oculus Quest guardian is literally a map of an area of your home. How many of those data points are being sent back to Facebook--a company well-known for data collection and privacy issues? Pre-COVID people rejected Facebook Portal for this very reason. My point wasn't to disparage the Oculus, which is a fine device, but the very reason you have to use your Facebook ID is for greater connectivity between Facebook accounts and services for the very purpose of better data sharing and data collection. Your Oculus data is not irrelevant. It's being merged with all the other data points that Facebook is collecting in order to create a profile with which to better sell you advertising (among other reasons). But a conversation like this is lost in the comments section of a paid newsletter. It's unquotable unless externalized like above. Azhar uses Substack, which is also being used by a plethora of modern journalists, pundits, and hobbyists in order to create a "noise-free" avenue of direct communication. It also helps that it has an easy subscription and payment mechanism. You may have noticed the increase in email-first communications and paid newsletters over the course of the last few years—especially as more journalists jump ship from traditional news magazines, newspapers, and web sites into a more self-directed writing approach. Here at Codepunk, we even put out the Bots + Beer newsletter as a secondary source of content for a time (non-paid, of course). But the novelty wore thin for a few reasons—namely because we were placing efforts on content for a specific audience (newsletter subscribers) that wasn't making it to the hundreds of thousands of people that read Codepunk. Our first transition was to start putting that content online. But with a Bots + Beer web site we were now focusing on two different web sites filled with content instead of one (with the former having markedly more readers). It didn't make sense, so we merged the two, and now the web site hosts the primary content for readers, subscribers, and anyone that searches via a search engine, and the newsletter points people in the right direction in case they missed the content. That last part should be completely unnecessary given modern technology and standards. But first, a history lesson. The Internet in its post-infancy, but pre-commercialization days was a collection of protocols providing complimentary services. Most today are familiar with HTTP—protocol of the world wide web—and email, but other protocols like Finger, Usenet, and Gopher provided other ways to communicate and disseminate information. And of course, if you're really a veteran of the Internet space, you remember bulletin board systems (BBS). Although the web ultimately won out (with the exception of email, which has become ubiquitous with daily communication), other protocols still existed on the periphery. As web sites moved beyond the hundred and thousands and into the millions, it became harder to disseminate information. This led to Internet directories, LISTSERVs, and eventually search engines, but only the LISTSERVs captured the community feel of the "communication revolution." LISTSERV is a trademarked name for a specific piece of mailing list software, but it has come to refer to—probably unfairly—mailing list software in general, such Sympa or GNU Mailman. These automated mailing list applications started to emerge in the mid-80's as a way to facilitate communication across large disparate groups where many subscribers hadn't met or even communicated outside of cyberspace. Electronic mailing lists existed before LISTSERV, but those were largely maintained manually and didn't have the automated pass-through of messages—instead relying on email addresses in totality or aliases. Most of the early electronic mailing lists were for academic and military purposes, but soon were adopted by early computer enthusiasts. In the vast wilderness of cyberspace—while web sites were still young—email and mailing lists becames the primary tool for delivering information to collaborators. As web sites began to birth weblogs (blogs), regularly published thoughts and information became more prevalent, including timely news, but how do you get timely information to potential readers? Mailing lists were great, but depending on the communication frequency, the email lists could get overwhelmed with messages, causing you to lose information, replies, etc. But with the emergence of blogging software, two competing standards surfaced to remediate this issue: RSS and later Atom. These standards were meant to be informative, uniform standards for providing a subscription model for structured information (e.g, blogs), and allowed for the consumption of multiple blogs from a single software source. (Really Simple Syndication) RSS is a way for website authors to publish notifications of new content on their website. This content may include newscasts, blog posts, weather reports, and podcasts. 1 Structured information is not new on the web. The idea was circulating as far back as 1995 with Apple Computers. The first version of RSS (known as RDF Site Summary) appeared in the late 1990's, primarily driven by the Netscape browser. When RSS 0.9 transformed into RSS 0.91, the format was simplified and diverged from a traditional RDF structure. RSS then stood for Rich Site Summary. RDF (or Resource Description Framework) is an XML-based information description language used for describing structured data in subject–predicate–object notation known as triples. Today, you see this most often in meta data parsing applications that require querying technologies like SparQL. When Netscape was purchased by AOL, AOL abandoned RSS support and the community split into two camps: UserLand (company of blogging pioneer Dave Winer) and the RSS-DEV working group. O'Reilly Media representatives worked together with several other organizations and individuals in this RSS-DEV working group to further the specification, while UserLand attempted to copyright the format and trademark the RSS name (which was rejected by the US Patent Office). Dave Winer's company was one of the first to concentrate on content management and blogging, and he had originally developed his own syndication format—ScriptingNews, named after his blog. When RSS 0.91 was released, he replaced his syndication specification with the new RSS version.2 The RSS-DEV working group re-injected RDF into the specification with version 1.0, which also added support for XML namespaces. Winer, meanwhile, added enclosures to his competing specification, introducing RSS 0.92. These enclosure elements allowed for RSS to ultimately be used for podcast feeds. With RSS 2.0, Winer re-dubbed the specification Really Simple Syndication, while now also introducing XML namespaces to the specification. Of course, despite the advancements, neither Winer nor the RSS-DEV working group could lay claim to being the official publishers of RSS. This left the world with two competing specifications with the same name… and no official stance of which is the official one to follow. Mostly, this was a disagreement on what RSS was actually for: [There] was eventually contention between a “Let’s Build the Semantic Web” group and “Let’s Make This Simple for People to Author” group […] 2 This confusion and the convoluted history of RSS led to the creation of the Atom specification, meant to be a clean slate for syndication, and for a time Atom was a relatively popular alternative. Winer eventually assigned his "copyrights" to the Berkman Klien Center for Internet & Society in 2004 and launched an RSS Advisory Board to clean up ambiguities in the specification. Unfortunately, multiple versions of the specification still exist today, but largely, RSS 2.0 has been the most widespread version of the specification used (including over Atom), and represents more than 50% of the current versions published on the Internet. The fight for RSS was not a fight for capitalist control—Netscape had already abandoned the format when AOL took over, and over the course of the last few decades, most browsers, publishers, and social media companies have abandoned the standardized format in order to lock users into their own proprietary feed offerings. Instead, the RSS fight was a philosophical one over how best to represent structured web information. On the frontline of this fight was a 14-year old boy named Aaron Swartz. Swartz participated in the early RSS-DEV working group before anyone realized how young he was. Although his contributions were to the RSS 1.0 specification that ultimately didn't win out, his push was namely for the inclusion of namespaces in the XML format for adding additional components outside of the original specification. This inclusion of namespaces was eventually adopted in the Winer version of RSS (and is included today), and is the primary reason why iTunes has its own namespace elements required for iTunes Podcast Connect inclusion. From the software perspective, Swartz is best known for his work as a founder of Reddit (yes, a founder— no matter what Steve Huffman says); however, even as early as 14, he was concerned with the culture of the Internet, freedom of information, and social justice. Despite Aaron Swartz's contributions to the history of the Internet, eventually he abandoned Reddit—not appreciating the direction Conde Naste was taking the web site and coming to several disagreements with fellow Reddit founders. This driving desire towards freedom of information, led him to participate in the development of several tools (e.g., SecureDrop) to help with press freedoms, and his social justice attitude prompted him to found DemandProgress. A child of the free Internet, Swartz began to have issues with the way scientific journals were controlling access to what was mostly publicly funded research. He exclaimed in his Guerrilla Open Access Manifesto. Adhering to this guerrilla principle, while attending Harvard on a fellowship and visiting MIT, Swartz installed a laptop in a networking closet and began downloading research papers via the JSTOR digital repository—a repository he had access to through his fellowship.3 In the on-going pursuit of criminal charges, many questioned the zeal with which the federal government pursued Swartz:.4 Instead of a tempered pursuit, prosecutor overcharging led to the possibility of 35 years in prison and $1 million in fines. On January 11th, Aaron Swartz was found hanged in his apartment… Robert Swartz—Aaron's father—exclaimed: Aaron was killed by the government […]5 The death of this freedom of information advocate reverberates even today as the fallout from the handling of his prosecution has enveloped the political game and helped changed the fate of Carmen Ortiz. Consider this piece recently from the Intercept:. […] Within days of Swartz’s death, over 61,000 people digitally signed a White House petition to fire Ortiz — a singular distinction for a U.S. attorney. The Senate and House judiciary committees pilloried her. Swartz was a pioneer of Internet freedom taken down by both capitalist and governmental overreach… and all he wanted to do was make information free. This was a long and twisting road to get back to the concept of paid newsletters, but the driving factor is the commercialization of communication and information. Douglas Ruskoff believed that the communication revolution was re-christened the "information revolution" because authentic communication between individuals was free, but information could be commoditized and sold. The Internet started as a new frontier of mutualism and open protocols, and it seems at each crossroads, somebody is trying to stamp out or control the protocols and processes that enrich people through freedoms of the Internet. Swartz committed suicide after having the book thrown at him for audaciously believing that academic research that furthers humankind ought not to be locked away for only those with enough finances to pay for it. This after participating in a multitude of Internet ventures pursuing open communications and free information. Participating in RSS, Swartz was collaborating with Internet pioneers trying to make structured data easily accessible and shareable regardless of platform. Unfortunately, RSS hit roadblocks (some self-imposed) over the lack of corporate adoption—and even the rescinding of corporate support—mostly so those same corporations could push their own locked-in protocol—all to drive growth. RSS peaked in popularity with Google Reader, but when Google shut down it's Reader software, it removed the largest aggregator from the market, forcing people to look elsewhere. Elsewhere led to less complete software, additional logins, and friction between everyday users and their software. This prevention of ease-of-use, limited (and even reduced) the appeal of RSS. Many web sites that are RSS capable today don't even publicize their RSS feed. You have go hunting in the code. Without the ease of use, everyday individuals retreated from RSS and it is not coincidental that the decline wasn't missed—mostly thanks to the rise of social media, which replaced your personally curated RSS feeds with advertising-enhanced algorithms… and all the vitriol that comes with social media. Drew Austin once wrote about email being a way to retreat from the algorithm and many people found comfort in a self-publishing model to deliver information directly to readers again—only instead of interactive LISTSERVs, we're left with single-direction newsletters. Single-direction was always there, but it is now the preferred newsletter distribution model. Substack didn't invent the newsletter, but they did a good job of partnering with major names in the beginning to push their platform into the forefront. If you look at Substack from the web application side, it's a blog with comments. The difference is that it allows for subscriptions and each post can be sent out in an email. We can call it a newsletter, but really it's a combination of a blog with email capabilities. Substack isn't the only platform, but between Substack, Revue (Twitter's recent purchase), and other platforms, these email subscriptions have taken off with names like Azhar, Glenn Greenwald, and Matt Taibbi jumping on-board. For some—like Greenwald—it presents a platform for communication devoid of the censorship he experienced at news organizations (including his own Intercept). For others (e.g., Azeem Azhar, Ben Evans, Ben Thompson) it's a platform to generate revenue for his business analysis. The problem with these newsletter platforms is that they are essentially walling off content behind paywalls, subscription logins, and mass email providers. Some of these platforms give you a window into the content… before shutting that window in your face. People retreated to email because we failed to give them a viable alternative. This isn't rant against paid newsletters. I personally pay for several newsletter, paid web sites, Patreon accounts, etc. It's a rant against the format. Keep paying writers and artists for content. They deserve it. On top of the problem of a walled Internet, I'm left with an inbox filled with newsletters that I now need to organize in subfolders to represent topics, priorities, etc. Although email management has gotten better, only the protocols associated with emails are a standard, not inbox design, labeling, tags, or other such features. Most email clients compete with each other on proprietary features, not the best implementation of the standard. Furthermore, those feature could differ between email clients and devices. RSS readers, on the other hand, implement a standard, and although readers can certainly implement their own proprietary functionality, the extensible nature of XML and XML namespaces allows these features to be documented within the RSS feed so that other readers can implement parity, if appropriate. But namespaces… what are those? Most people don't realize that RSS is a subscription model or that podcasts are actually served via RSS. I'm pained when I see web sites list their Spotify and iTunes link for their podcast, but don't actually list their RSS feed for people who want to listen to the podcast in their own podcast application. Most other applications have to rely on auto-discovery via a meta tag in the web site… but sometimes these tags are wrong. In fact, just have a glance at the explanation of RSS in the LifeWire article we quoted earlier. It slowly devolves into an collection of gibberish (for the everyday person). The biggest issue with RSS is that the only way people have found to monetize them is to truncate content and place the rest behind a web site paywall. Others have created RSS feeds that provide a token to subscribers (some podcasts do this with private feeds). A newsletter is always in your inbox, which has become ubiquitous with daily life, and that inbox is, in theory, private—unless you forward the email. RSS feeds require an application to honor authentication, or blogs need to provide specific (and private RSS) feeds. I was never a fan of truncating content. The other problem RSS has is the aforementioned ubiquity. Even your grandmother has an email address. It's one of the oldest protocols and it's ingrained with both business and personal interactions. It's more common than having a social media account. But for most people, RSS is still a mystery shrouded in techno-babble. Until we make RSS subcriptions as easy as emails, we'll continue to wall off the Internet behind social media algorithms and newsletter subscriptions. Until we make it easy, we'll continue to wall off the Internet behind closed windows, proprietary corporate protocols, and decisions that only benefit financial extraction.
https://codepunk.io/newsletters-are-walling-off-your-freedom/
CC-MAIN-2021-17
refinedweb
3,160
50.77
How to save files through file pickers (XAML) Use FileSavePicker to let users specify the name and location where they want to save your app’s content. Prerequisites Understand async programming for Windows Runtime apps using C++, C#, or Visual Basic You can learn how to write asynchronous apps in Quickstart: Calling asynchronous APIs in C# or Visual Basic. Instructions Step 1: Create and customize the FileSavePicker.Add to specify file types that the sample supports (Microsoft Word documents and text files). Add is the Append method as it is projected for C# developers. try the await operator. The File picker sample demonstrates how to display the file picker to let the user save a file.. file. Related topics - File picker sample - File access sample - Guidelines and checklist for file pickers - Quickstart: Accessing files with file pickers - Quickstart: Reading and writing a file - Reference - Windows.Storage.Pickers namespace - Windows.Storage.Pickers.FileSavePicker class - Windows.Storage.StorageFile class - File picker contracts - Integrating with file picker contracts - Quickstart: Integrating with file picker contracts - Guidelines and checklist for file picker contracts
https://msdn.microsoft.com/en-us/library/windows/apps/xaml/JJ150592(v=win.10)
CC-MAIN-2015-32
refinedweb
178
55.84
dandymcgee 0 Posted December 9, 2007 (edited) I'm having trouble creating a struct with a varying name... It's sort of hard to explain as I don't know much C++. Read the comments in the code. This is how I am currently trying to do it: CODE#include <iostream> using namespace std; void display(string accountname); struct database{ string acctname; int acctnum; int level; int exp; }; int main() { string currentaccount = "dandymcgee"; display(currentaccount); cin.get(); } void display(string accountname) { //"accountname" should be the input that was given when the function was called //the variable currentaccount was given, which is equal to "dandymcgee" // //I want to create a new entry in database called "dandymcgee" not "accountname" // database accountname; // "accountname" is a variable which i want to be replaced with "dandymcgee" accountname.acctname = "dandymcgee"; accountname.acctnum = 1; accountname.level = 28; accountname.exp = 14029; // Display the final result... cout<<"========================================"<< endl; cout<<" Account Name: "<< accountname.acctname << endl; cout<<" Account Number: "<< accountname.acctnum << endl; cout<<" Level: "<< accountname.level << endl; cout<<" Experience: "<< accountname.exp << endl; cout<<"========================================"<< endl; } Upon trying to compile this source code I get the error: ""declaration of 'database accountname' shadows a parameter"" This is because I'm telling it to store the string that was sent to the function in the variable "accountname", and then saying to make a new entry in database called "accountname"... but i want to create a new entry in database called "<data from string 'accountname' here>" (a.k.a. dandymcgee). Thanks for your help. Edited January 14, 2008 by dandymcgee - Dan [Website] Share this post Link to post Share on other sites
https://www.autoitscript.com/forum/topic/59074-help-with-c-structs/
CC-MAIN-2018-43
refinedweb
266
56.76
50750/when-ever-file-added-bucket-should-renamed-using-timestamp You can rename it on #bash and then upload it on s3 for f in test/*; do TIMESTAMP=$(date +%s); FILENAME=${f%.*}; EXTENSION=${f##*.}; NEWNAME="$FILENAME-$TIMESTAMP.$EXTENSION"; mv $f $NEWNAME; done You can use the below command $ aws ...READ MORE you need the chown -R not the ...READ MORE You can use method of creating object ...READ MORE Thanks for the answer. This should be clear ...READ MORE The code would be something like this: import ...READ MORE There are three ways in which you ...READ MORE Follow the guide given here in aws ...READ MORE Check if the FTP ports are enabled ...READ MORE To connect to EC2 instance using Filezilla, ...READ MORE AWS ElastiCache APIs don't expose any abstraction ...READ MORE OR Already have an account? Sign in.
https://www.edureka.co/community/50750/when-ever-file-added-bucket-should-renamed-using-timestamp?show=50803
CC-MAIN-2019-51
refinedweb
142
78.55
Connecting ESP8266 to WiFi Network – Beginners Guide Contents ESP8266 is the one of the most popular WiFi SoC (System on Chip) available today. It finds a lot of applications in IoT (Internet of Things), Home Automation fields. In this tutorial we will see how can we connect ESP8266 to a WiFi network. Modes of Operation ESP8266 has 3 operation modes. Those are: - Station Mode - Soft Access Point Mode - Station + Access Point Mode Station Mode: Connecting to one specific network: ST – Station mode in which ESP acts as a device & connects to an existing Access point.. Soft Access Point (Soft AP) AP – Access Point mode where the ESP itself acts as AP & other devices like Mobile can connect to it.. Station + Access Point Mode The third mode of operation permits the module to act as both an AP and a STA. The mode of operation is set by the AT command. Note: Read the article Getting Started with ESP8266 Programming – Arduino before following below steps. Steps - Get your Routers SSID and Password - Connect your ESP8266 to your Computer #include "ESP8266WiFi.h" // WiFi parameters to be configured const char* ssid = "SERVER NAME"; const char* password = "SERVER PASSWORD"; void setup(void) { Serial.begin(9600); // Connect to WiFi WiFi.begin(ssid, password); // while wifi not connected yet, print '.' // then after it connected, get out of the loop while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } //print a new line, then print WiFi connected and the IP address Serial.println(""); Serial.println("WiFi connected"); // Print the IP address Serial.println(WiFi.localIP()); } void loop() { // Nothing } - Save, Compile and Upload the code to ESP8266. - Verify The Output on the Serial Monitor - If ESP8266 is not connected then it will display “……” on Serial Monitor - If ESP8266 is connected then it will display ” WiFi connected and IP address” on Serial Monitor. Result Refer the our next article “LED Control by ESP8266 as Web Server – IoT” to control the LED from local server. hi.i followed every step but it doesn’t show me the ip address.what can i do?.could you please help me with that?
https://electrosome.com/connecting-esp8266-wifi/
CC-MAIN-2021-43
refinedweb
349
56.96
On Tue, Sep 04, 2012 at 09:18:20AM -0600, Eric Blake wrote: > On 09/04/2012 08:57 AM, Jasper Lievisse Adriaanse wrote: > >>From bafcb4ed2b90b5ba845ca6b61861e3caa548b16a Mon Sep 17 00:00:00 2001 > > From: Jasper Lievisse Adriaanse <jasper humppa nl> > > Date: Tue, 4 Sep 2012 16:57:09 +0200 > > Subject: [PATCH] Include some extra headers needed for OpenBSD. > > > > --- > > src/util/virnetdevbridge.c | 9 +++++++++ > > 1 files changed, 9 insertions(+), 0 deletions(-) > > Please show the compiler errors that you got without these includes. I > can't help but wonder if you have instead uncovered a bug in the gnulib > headers, but knowing which symbols were not declared makes a difference > in answering that question. > > > > > diff --git a/src/util/virnetdevbridge.c b/src/util/virnetdevbridge.c > > index 7b11bee..8559223 100644 > > --- a/src/util/virnetdevbridge.c > > +++ b/src/util/virnetdevbridge.c > > @@ -30,6 +30,15 @@ > > #include "intprops.h" > > > > #include <sys/ioctl.h> > > + > > +#ifdef HAVE_SYS_PARAM_H > > <sys/param.h> is non-standard; what are we using that requires us to > probe for its existence? Should gnulib consider guaranteeing this > header in spite of it being non-standard? Nope, it was an error on my side to include it. I thought it was needed by socket.h, but after trying to show you the error...there was none. > > +# include <sys/param.h> > > +#endif > > + > > +#ifdef HAVE_SYS_SOCKET_H > > This line shouldn't be necessary; gnulib guarantees a working > <sys/socket.h> on all architectures. OK. Could you please push this one then? > -- > Eric Blake eblake redhat com +1-919-301-3266 > Libvirt virtualization library > -- Cheers, Jasper "Stay Hungry. Stay Foolish"
https://www.redhat.com/archives/libvir-list/2012-September/msg00147.html
CC-MAIN-2016-50
refinedweb
261
60.11
14 February 2006 21:18 [Source: ICIS news] ?xml:namespace> The company did not give a reason for the proposed increase. ABS producer Dow also confirmed a 4 cents/pound increase planned for 1 March. Buyers and compounders said the boost was triggered by strong market fundamentals and growing demand. ABS producer Lanxess was believed to have followed suit, according to industry sources. ABS producer GE was not immediately available for comment on whether it also would seek an increase. It was not clear if customers would accept the proposed increase but producers said they were confident the planned hike would take hold. February ABS spot prices for large volumes are at 78-80 cents/pound
http://www.icis.com/Articles/2006/02/14/1041672/us-abs-producers-seeking-march-hikes.html
CC-MAIN-2014-35
refinedweb
116
65.83
2 Introduction Hello everyone. This little code snippet shows you how to read in scan codes from the keyboard. It is slightly different than reading in a regular character. When you use the getch() function, it is normally returning an ASCII value. Some keyboards have extra keys though. These include the F1 - F12 function keys and the directional arrows to start. These keys do not have an ASCII code. A char data type is a one byte item. When you press a key that doesn't have an ASCII code, it returns two bytes. If the first byte is 0, then the next byte contains the scan code. In the following code, I include the scan code for many typical keys and how to read them. Notes: - Even though there are two calls to getch(), it does not require two keystrokes. - Not all of these scan codes may be 100% accurate for all computers. It may, of course, need some modifications. /* This program shows how to pick up the scan codes from a keyboard */ /* These define the scan codes(IBM) for the keys. All numbers are in decimal.*/ #define PAGE_UP 73 #define HOME 71 #define END 79 #define PAGE_DOWN 81 #define UP_ARROW 72 #define LEFT_ARROW 75 #define DOWN_ARROW 80 #define RIGHT_ARROW 77 #define F1 59 #define F2 60 #define F3 61 #define F4 62 #define F5 63 #define F6 64 #define F7 65 #define F8 66 #define F9 67 #define F10 68 #include <iostream> #include <conio.h> using namespace std; void main() { char KeyStroke; cout << "Press Escape to quit." << endl; do { KeyStroke = getch(); if (KeyStroke == 0) { KeyStroke = getch(); // Even though there are 2 getch() it reads one keystroke switch (KeyStroke) { case PAGE_UP: cout << "PAGE UP" << endl; break; case PAGE_DOWN: cout << "PAGE DOWN" << endl; break; case HOME: cout << "HOME" << endl; break; case END: cout << "END" << endl; break; case UP_ARROW: cout << "UP ARROW" << endl; break; case DOWN_ARROW: cout << "DOWN ARROW" << endl; break; case LEFT_ARROW: cout << "LEFT_ARROW" << endl; break; case RIGHT_ARROW: cout << "RIGHT_ARROW" << endl; break; case F1: cout << "F1" << endl; break; case F2: cout << "F2" << endl; break; case F3: cout << "F3" << endl; break; case F4: cout << "F4" << endl; break; case F5: cout << "F5" << endl; break; case F6: cout << "F6" << endl; break; case F7: cout << "F7" << endl; break; case F8: cout << "F8" << endl; break; case F9: cout << "F9" << endl; break; case F10: cout << "F10" << endl; break; default: cout << "Some other key." << endl; } } else cout << KeyStroke << endl; } while (KeyStroke != 27); // 27 = Escape key }
https://www.daniweb.com/programming/software-development/code/216732/reading-scan-codes-from-the-keyboard
CC-MAIN-2016-18
refinedweb
408
77.27
First page Back Continue Last page Overview Graphics A simple example from Persistence import Persistent from Transaction import get_transaction from ZODB.FileStorage import DB class Counter(Persistent): _value = 0 def inc(self): self._value += 1 def main(): fs = DB(“data.fs”) conn = db.open(); root = conn.root() obj = root[“myobj”] = Counter() get_transaction().commit() obj.inc() get_transaction().commit() Notes: Explaining how this simple example works gets into a number of interesting implementation issues. The root object is a persistent object – a dictionary. When the “myobj” key is added, the object is marked as changed. When the transaction commits, a new data record will be written for the root object. When the data record is written, a reference to a new persistent object is noted. The new object (obj) is assigned a data manager and the DM assigns an oid. Then a new record is written for this object. When the transaction commits, any other object referencing the root object will receive an invalidation notice. At its next transaction boundary, it will update the object to its new state. It may also raise a ConflictError.
https://www.python.org/~jeremy/talks/zodb-ll2/text7.html
CC-MAIN-2016-22
refinedweb
183
52.15
Bad Programming Habits We Secretly Love (infoworld.com) 497 snydeq writes: Breaking the rules can bring a little thrill — and sometimes produce better, more efficient code. From the article: .' What bad programming habits can't you (or won't you) break? You're the problem (Score:5, Insightful) Re:You're the problem (Score:5, Insightful) “Any fool can make a rule And any fool will mind it.” Thoreau Re: (Score:3) âoeAny fool can make a rule And any fool will mind it.â Only a fool will not attempt to logically circumvent it ... sniff _____________________________________ live long and prosper Re:You're the problem (Score:5, Funny) Re:You're the problem (Score:4, Insightful) That's only an admonishment against following bad rules. Thoreau practiced a lot of civil disobedience. Hell, he wrote the seminal work on the subject, a little essay titled "Civil Disobedience." Or, in the words of his contemporary and mentor: If a rule is bad, change it. But ignoring it while leaving it on the books is poor form. Re:You're the problem (Score:4, Funny) Back during Y2K updates to our code base, we'd occasionally have to deal with code written by an ex-employee, who we'll call John. It was so bad that every time someone opened a file he had worked on you'd hear a loud "FUCK! Another John file!" over the cubical walls. Re: (Score:3, Interesting) We had a contractor I'll call Paul. He wrote exactly to spec, and not a line more. If you didn't say "protect against buffer overflows when accepting user input" you can guarantee his code would crash if you input a single extra character beyond the prescribed format. It only worked if you did exactly what the user manual described. Any slight deviation and you were screwed, often in ways that were not immediately obvious. Re:You're the problem (Score:5, Funny) ...who we'll call John... ...a contractor I'll call Paul Right, so who's going to come up with George and Ringo to make up the full set? Re: (Score:3) Half a million Rupees. Paul my ass, we all know he was called Palanduran. The Issue with programming. (Score:5, Insightful) We are hired to write new programs/new ways of solving a problem. Rules are made to solve common problems. If we only follow these rules we are limited to writing programs that have already been written, in that case we are just useless. If we know when to bend or break the rules, then we can create things that solve problems differently and is new and unique. When I work with programmers so are hard fixed on the right way to do things, I often get a response that x cannot be done. I break the rule and I have done it in a couple of days work, then they will go but you didn't follow the right form. The end user doesn't care about form, they care if it Works well, It can be maintained, and it is secure. Re: (Score:3, Insightful) You sound are one of the "men of some parts whose cleverness sets them apart from their fellows, but not nearly so far as they imagine." If we only follow these rules we are limited to writing programs that have already been written... Non sequitur, and nonsensical. All major programming languages are Turing-complete, and should all be able to express the same statements/programs. When I work with programmers so are hard fixed on the right way to do things, I often get a response that x cannot be done. There are things that are impossible in computer science, e.g. solving the Halting Problem. Most programmers tend not to conflate the impossible with the difficult or computationally expensive; your doing so is not a good sign. Re: (Score:3) Interesting how many of the "rules" are considered bad form in python (as one example) - and in fact following them is considered ugly, unmaintainable code. Then again, a lot of python rules specifically contradict the rules of everything that came before. A standard rule in every OOo course is that objects should not expose data, only methods for manipulating data - and the manipulation should be entirely confined to the class. Python considers getters and setters extremely bad form and insists that the var Re:You're the problem (Score:5, Insightful) I've heard arguments against writing proper comments similar to what the author makes: "but if you change the code and the documentation or comments don't change, then it might be worse than no documentation at all." My response is that if you're not updating the documentation or comments, then you're not finishing the job you were assigned. You could make the same arguments against taking the time to create meaningful variables and function names. There's another argument against comments I occasionally hear as well, which is "a competent coder should be able to discern what the code is doing without comments." While that's technically true, it's another argument I would reject. I feel the best comments can and should declare the intent of a block of code, rather than drilling down into the mechanics of the code. Those types of comments are often much more valuable than comments which simply regurgitate the mechanics of code in English. Still, in my own code, I don't have a fixed ratio of comment to code. It's entirely dependent on the complexity / obviousness of the code in question. For instance, if you have a very simple function, such as a handler that reacts to some UI event and just passes along the event to some other system, or performs a simple operation, it's stupid to spend a bunch of time and create excess visual noise to document that function. A quick glance at the code tells you everything you need to know about what's going on far easier than comment blocks. On the other hand, when code gets more complex, or the internal workings of a function is less than trivial, I expect to see a more comments in the code. In some of the most complex code I've either written or worked on, the number of lines of comments can actually exceed the number of lines of code. I've even seen some helpful little ASCII drawings in some particularly complex physics code, which was awesome. Re: (Score:2, Interesting) My comment about comments in code is that all comments need a date and the coder's initials as a minimum, and old comments should not be deleted. I have way too much experience knowing why these are my comments. Re: (Score:3) If you need comments to know who wrote what and on what date, then you need to get your code into source control. Re: (Score:3) Re: (Score:3) Tracking when changes were made, and why, is the job of your source control system. Describing what the code does, is mostly the job of the code; variable names, function names and an occasional brief comment. Describing the expected inputs and outputs of the code is the job of unit testing. Describing the intent of the code, well that's a bit harder to get the right balance. Of course there's lots of overlap, and some huge grey areas. When reading someone else's code to track down a bug, or add a new featu Re:You're the problem (Score:4, Insightful) Exactly. There's a lot of code that needs comments like "fixes bug XXX". If you had to fix a nasty bug and it took you a day to get the details right, let the next poor sap know what you were doing. Otherwise, he's likely to reintroduce the bug by tearing out this apparently useless code. Another good use of comments is to summarize a large block of code so that people don't have to dig into it to figure out what it does. For example, it's good to document functions at the top with enough detail that somebody would know how and when to call them without having to read through the whole thing. You need two expressions of intent to detect bugs. (Score:3) There's another argument against comments I occasionally hear as well, which is "a competent coder should be able to discern what the code is doing without comments." While that's technically true, it's another argument I would reject. Me, too. Sure, a competent coder can tell what the code IS DOING. So can a compiler. That's not the issue. What do you do if what the code is doing is the wrong thing? What is the RIGHT thing? If all you've go is the code, you're hosed. NO process can look at code alone and Re: (Score:2, Insightful) There's nothing wrong with GOTOs. Re: (Score:3, Interesting) Used judiciously, a goto can save a lot of trouble. The three use cases I have for occasionally using a goto are to break from nested loops, to break from a switch-case within a loop, or as part of error-handling routine where an exception-based approach are not possible or not permitted. In all cases, these are within the scope of a single function. Re:You're the problem (Score:4, Informative)... Re:You're the problem (Score:4, Funny) yeah, Knuth is always your go to guy... Re: (Score:3) An exception is a nonlocal jump, where the destination is in some totally unrelated section of the codebase, typically written by some other programmer even. Everything that's said to be wrong with GOTOs is often said to be right by exception supporters. Re:You're the problem (Score:4, Insightful) Re: (Score:3) 10 GOTO 20 15 ? "THIS LINE IS USELESS" 20 RETURN Yes, yes I did eventually hire professionals. No, no they did not need my help. Re: (Score:3) Real programmers use 11101011 (on x86). Re: (Score:3) Real programmers use 0001 (on PDP-11) Re:You're the problem (Score:4, Funny) "The code comes out cleaner"? (Score:5, Insightful) If the code comes out cleaner, you didn't break any of my rules. The rule "make the code as clean as possible" trumps all other rules. Re:"The code comes out cleaner"? (Score:5, Funny) Does it trump the "make the code work" rule? Re:"The code comes out cleaner"? (Score:5, Informative) I would not consider non-working code as clean. Re:"The code comes out cleaner"? (Score:5, Funny) Ah, the "No True Clean Code" fallacy. Re:"The code comes out cleaner"? (Score:5, Insightful) 2) Make the code readable 4) Make the code flexible. Re:"The code comes out cleaner"? (Score:4, Funny) 1) Make the code work 2) Make the code readable 4) Make the code flexible. 0) Make the code on time 3) ??? 5) Make the code - PROFIT! Re:"The code comes out cleaner"? (Score:5, Interesting) Having "taking over" a lot of code in my time, I can say for myself, having code that "works and I don't know why" makes me more nervous that code that "doesn't work and I don't know why". I'd rather have clean code, be it working or non working. If it's clean I can get it to work reasonably quick. If it's not clean and not working then I can easily justify a re-write. But if I can't understand it and it seems to be working, I always have the dread that someday it will break in a disastrous fashion in the most inconvenient of times with me being unable to do anything about it. Zen (Score:2) Bingo... the first rule is to be as zen as possible with your programming. Clean and efficient... no bullshit. Re: (Score:2) Yeah but none of the suggestions in the OTA actually make the code cleaner. Re: (Score:2) Sorry I I have too many threads running in my brain. I meant TFA not OTA. Re: (Score:3) Must be a race condition. Did you follow the thread safety rules? Re: (Score:2) a=b+c; If you really needed that comment, turn in your geek badge now. #3 vastly improves readability in most cases. Trying to read through one statement per line feels like trying to read a book with one word per line. #4 means you don't need to tediously declare every loop variable. I don't care what type "i" has - If the original coder sucks so badly that a simple iterator breaks, I don't keep trying to read their code, Re: (Score:2) Re:"The code comes out cleaner"? (Score:5, Insightful) Re: (Score:2) It's a tradeoff (Score:5, Insightful) Sure, you can trade maintainability for efficiency and reliability. People do it all the time. You just have to understand the costs involved. If the efficient code gains you a million dollars in performance, maybe you can afford for it to be crappy code. Or maybe you'll be running the code for 10 years, and if it costs you $250,000 to keep a crusty old engineer on staff who can maintain it, suddenly that million dollars in performance may not be worth it. <disclaimer>I am a crusty old engineer.</disclaimer> Re: (Score:3) If you get the million right now that may be worth spending 2.5 million over ten years, if you're short on cash flow. Going bankrupt is bad. Re: (Score:3) I think he's saying that he costs $250K/year. I'm getting on toward old and crusty, and my cost to the company is certainly closer to $250K/yr than $25K/yr. Dunno what they pay the whelps coming out of school these days, but I never worked for $25K/yr after I got out of school. Bad Habits? (Score:3) We ALL fully document our code, have clear specifications before we write code, use meaningful variable names and rely on IDEs...amirite? In my case, I only program (after doing it for pay for 45+ years) for myself, and I'm creating new stuff all the time, based on experience. For example, my backup strategy. It started out as a simple script to launch Drive Snapshot. It evolved, into having multiple, cascaded backups on one partition of the computer, which are replicated automatically to my main "server" in case the computer dies. Each computer in the office uses the same central repository. It's got bells and whistles that make my job a lot easier when I experiment...if I try some new app and it trashed Windows, I just roll back to last night's backup. (I believe in 100% backups of all computers...including the server...every night, and schedule "fixit/improve it" time first thing in the morning, so I can rollback and lose nothing.) So, personally, I now break all the rules, and let my needs dictate the code I write. It isn't specified, it's an evolving organism in my small environment. Oh, and I'm doing all that in cmd files...might consider upgrading to something exotic, like AutoIt, someday, but I've been saying that for four years now... Re: (Score:3, Funny) I once saw source code for a library, written in Ada that had the following "feature". Since Ada code is "self documenting", each routine had a block comment documenting said routine. The block comment was LITERALLY a copy of the routine, commented out... e.g.: -- procedure body f is -- begin --TEXT_IO.PUT_STRING('Hello world'); --TEXT_IO.PUT_LINE; -- end f; procedure body f is begin TEXT_IO.PUT_STRING('Hello world'); TEXT_IO.PUT_LINE; end f; Copy and Paste. (Score:5, Informative) Sometimes I will copy and paste a function and just do some minor tweaks were I could have just added a parameter. Why do I do this? Readability. Having a function called SplitPersonName(string name) and another one called SplitCompanyName(string name) So when I run the function it will be easily readable, as well if there is a bug in one of the fuctions but it works fine for the other. I can just change that one function without having to unit test other parts that could have been effected. Also I avoid too much Classes that are extended from other classes, that tends to add confusion on where a particular code is being called if you are debugging it from the middle of the class structure. It is OK to break rules, but you should have a good reason to do so. Also you should feel free to not break the rules when you do not have a good reason to do so. Re:Copy and Paste. (Score:4, Insightful) Adding another variant, when you have an existing function that you never expected to reuse part of, suddenly interested in a twist on it. The 'proper' answer is to refactor so that it is shared code, but the code being reused is something that's not changed in 3 years and never had an issue under impressive load. So I could either refactor including changing working code, or duplicate. I'll duplicate. Now my duplicate may break out the relevant code so that if such a circumstance arise later, that the duplication won't happen twice, but I would rather a duplicate exist than risk any change to proven code. Re: (Score:3) Re: (Score:3) This is the reason why you have comprehensive unit tests. You can refactor the original function safely in the knowledge that, if you break it, the unit tests will start failing. You do have comprehensive unit tests? Re:Copy and Paste. (Score:4, Insightful) That's just for simple integer addition. When you start writing real-life code the combinations of inputs grow very quickly. You do your best, but it simply isn't practical to test for every possible thing that could cause a problem. Re:Copy and Paste. (Score:5, Insightful) Also agreed about too many classes. People think they make nice modular things by having short classes, but I just went through an exercise of pouring through about a dozen mind numbingly tedious files to find the single line of code that actually did something rather than just do a few pointlessly segregated checks or providing an alternative function for what '+=' already did or coercion into some datatype only to have it coerced back 'just in case' that middle layer might one day have another developer that would naturally think of it another way... Re: (Score:3) Envelopes stuffed into envelopes which are stuffed into envelopes, which are stuffed into manila folders which are stuffed into binders, which are stacked into cabinets, which have a security guard standing in front with orders to shoot anyone looking suspicious. Re:Copy and Paste. (Score:5, Insightful) For any rule you can come up with, you can probably find a valid case where breaking the rule would result in better code. Even GoTo can be useful in certain circumstances. Most of the good uses of GoTo have been codified using other key words. .C# has the continue [microsoft.com] keyword. It's basically exactly the same as using a GoTo to skip processing the current item. GoTo would have accomplished the exact same task, but people have such a dislike of GoTo that they had to create a whole other keyword that does exactly the same thing. Re:Copy and Paste. (Score:4, Interesting) Re: (Score:2) The continue and break targets are clear enough in very simply code. They're much less clear when placed inside several levels of nested blocks. A goto statement has a named target you can easily search for, while the target of a break or continue statement is merely the end of the enclosing loop (or in the case of break, a switch statement). This may or may not be the same as the end of the current block. Besides the lack of a named target, this points out another drawback of continue/break: wrapping code i Re: (Score:3) Documentation (Score:5, Funny) From TFA:! He should have been shot. Re:Documentation (Score:5, Insightful) The boss or the developer? Yes. Re: (Score:2) Re:Documentation (Score:4, Interesting) The functionality of a non private API must be documented. Requiring people to read the code in a function in order to find out what it is supposed to do is stupid. If a programmer changes the code in a function such that its API documentation is wrong, the documentation hasn't gone stale, the programmer introduced a bug. long methods and coupling (Score:5, Insightful) long methods - someone thought it a good idea to limit every method to no more than 20 lines. I think this is a terrible idea, and can make code unreadable, which leads to: coupling - it's often best to tightly couple things for ease of debugging and development. How often are you going to change the database you're using? Is it worth going through another abstraction for every database call? Too much abstraction makes code unwieldy. I'd rather have a bunch of 200 line methods that represent logical units of work than a call stack 20 layers deep. Re: (Score:2) a call stack 20 layers deep. This here is my pet peeve of most 'modern' code projects, an insane call stack. Sometimes there's good reason, but often it's simply because the project is badly duct taped together rather than carefully thought out. Exacerbated in a lot of cases even more by having multiple over the network calls to chain several of these sorts of atrocities together. I have seen a team charged with being a sort of single middleware for a pretty straightforward sort of job self-create 4 distinct processes that each get in Re: (Score:2) long methods - someone thought it a good idea to limit every method to no more than 20 lines. Show them tcp_input(). After they have a heart attack at the number of pages it takes to implement the input state machine for the TCP protocol, bury them, and get on with your life. Re: (Score:2) When I have run into long methods the solution usually is not a deep call stack, but instead that the method has chained together 20 10 line logical units. It would make the code more readable to have that be 20 sequential (not nested) calls to well named functions that accurately describe what they are doing. Often those logical units are different if/else blocks as well, so extracting them makes it easier to unit test all branches rather than trying to set up 200 different branch possibilities on one me Re: (Score:3) GOTOs in C (Score:2, Interesting) I often use GOTO statements in C code to mimic exception catching without duplicating cleanup code. It works very well, and its easy to understand, maintain, and debug. Example: x = do_stuff(); if (x 0) { goto cleanup; } y = do_more stuff(); if (y 0) { goto cleanup; } return 1; cleanup: fix_my_mess(); fix_it_4realz(); return 0; Re:GOTOs in C (Score:5, Interesting) Comp Sci professors teach "goto = bad" because the wisdom necessary to use it competently comes only with experience. It's like jazz; you have to know the rules and follow them before you can break them and not sound like a jack-ass. Re: (Score:3, Interesting) { fix_my_mess(); fix_it_4realz(); } x = do_stuff(); if (x == 0){ cleanup(); return 0; } y = do_more_stuff(); if (y == 0){ cleanup(); return 1; } return 0; Re:GOTOs in C (Score:4, Insightful) So far we have 3 comments with the "right" way to do it that do nothing but add complexity and loss of readability for strict adherence to dogmatism imparted by our CS professors (few of whom had real-world programming experience). This is a straightforward problem. The suggested use of goto is a straightforward solution, and cleaner by far than the suggested alternatives. But most importantly, no one can demonstrate how it is wrong. Re:GOTOs in C (Score:4, Insightful) Wow. WAY too much code for what it actually needs to be. Furthermore the fix functions have now leaked scope all the way to main(). Re: (Score:3) Dijkstra Nailed It (Score:5, Insightful)...... --Edsger W. Dijkstra Lessons (Score:5, Interesting) Variable and object naming, and commenting is an art-form that takes experience to do well. Here's a few practical guidelines I've learned follow: 1. Think of newspaper headlines when commenting. Don't make somebody read the whole article to know what the article is about. 2. Comment the "odd" stuff, not the obvious stuff infer-able from function name etc. 3. Goldilocks Rule: Names both too long and too short can be bad. 4. The more frequent a name is used, the shorter it should be. Use comments at declaration to give the full name. Example of a variable that may be used often: var dhv_id; // Department of Housing vendor ID If it's used often, I'd rather have an abbreviation than see DeptOfHousingVendorID all over the code, making it long and "wrappy". 5. Everybody has their own preference, but you have to target the "average" developer (future unknown reader) to make code future-friendly. Re: (Score:2) Nice ones. There's also a Goldilocks size for functions: functions too long are a pain to decipher, and it's easy to get lost between calls when all functions are too short. The same applies for OOP with the trade off between one Godzilla class and the Lasagna of too many classes. Re: (Score:3, Insightful) I've been programming for quite awhile and honestly I'm in the verbose commenting camp. Not because I'm worried about code reviews, handing the code off to anyone else or even following some company's arbitrary rules on how things should be documented. I use verbose comments so I don't have to remember what was done and why it was done that way. Frankly I've got too many other things that I'd rather remember. Granted verbose comments will make my code seem pretty old school, but I have yet to hear any questio Re:Lessons (Score:5, Funny) One extra space per bracket (Score:3) Just one extra (or fewer) space per bracket...'cause I know it's driven SOMEONE nuts at every shop I've worked at. Not really about "better, more efficient" code (Score:2) ComeFrom's (Score:2) Breaking out of the middle of a loop (Score:2) Since when is returning from the middle of a loop a bad thing? I've never been taught that, and it certainly hasn't been a guiding principle in any code base I've worked in. break, don't return. Better - while(&&) (Score:2) Combine that with another poster's 200-line methods and someone looking at the code has no easy way to know what the code returns - what it DOES . And the person looking at it my be you in two years. Also, such code -lies- about what it does. More on that in a minute. It is better to return at the bottom of a function, partly so you can FIND the damn return statement. So an improvement over return () in the middle of the function is to break. Even better, make the loop condition honest. Instead of this: w Re: (Score:2) I think it's an extension of best practice having only one return in a function... which I kind of agree with since it works into your try catch loop. If you need more than one you probably need to split break up your method into more than one function Re:Breaking out of the middle of a loop (Score:5, Insightful) Re: (Score:2) There are a lot of people out there who subscribe to the "single point of exit" theory, meaning all your code paths through a function should lead to the same return point. I am not one of those people. Unapologetically guilty. (Score:2) For #6 (reinventing data structures), gimme a frickin' break - I will not pull in a 3rd party library just to implement a data structure I c cut and paste (Score:2) -although if/when I end up doing parameterization I have to hunt through the code and delete all the stuff that was obsoleted by the parameterization -I'm just sayin' All rules are not created equal (Score:2) There are a lot of bad "rules" running around out there. There's also a lot of good ones. Some have evolved through painful experience; others are more like cargo-cult beliefs. But the bottom line is that we're all terrible judges of our own work. That's why authors need proofreaders and (frequently) editors. If you want to break something you think is a rule, for whatever reason, try checking with your cow-orkers, to see what they think about it. Yes, they may all be hide-bound idiots, but if you get hit b #8 variable name length defines scope (Score:2) The longer or more descriptive the variable name, the wider the scope. can't code, afraid of disapproval (Score:5, Insightful) It seems that many in the field these days are afraid to code something themselves for fear that someone will find fault. So, they do things "the established" way, which is generally frameworks or anything that can be called "reusable", even if this generation's "reusable" is always less reusable than last, because it keeps getting needlessly more complex to the point that nobody *can* reuse it. Used to be programmers had a fault we called "not invented here", in that they'd insist on re-writing things that already existed, because it was easier to understand their own code than to use someone else's. These days it's reversed. For fear of criticism, they *must* use someone else's code rather than write their own. I call it "afraid to invent it here." tools, not rules (Score:2) I see a lot of rigidity around buzzwords and established practice, because programmers these days are given tools, and to appear smart to other programmers, they treat these tools as rules. As if knowing some rules is more important that solving problems and getting the job done. It's apparently easier to show how smart you are by regurgitating rules and criticizing people who don't follow them rigidly than it is to actually accomplish things. Re: (Score:2) Seriously people still use the goto statement and love it? I have never meet anyone that loved the goto statement. GOTO [slashdot.org] Re: (Score:3) Seriously people still use the goto statement and love it? I have never meet anyone that loved the goto statement. It's only loved by people who think functions should be single entry, single exit, so that you can wrap the code in asserts during testing so that you can be sure that you've got the right lock state on entry and exit. It's also great for detecting memory leaks. If you never use locks, or never had a lock leak, or never had a memory leak, or know bugger all about assembly (the compiler is going to emit the JMP instruction, whether you like it or not, and if you don't understand assembly, you should probably Re: (Score:2) I really hoping you are being sarcastic because if not, you really haven't worked on any projects of real size. What you describe is really nice for an app that does addition and subtraction, but when you have connections with multiple databases, have several dozen static sockets connections going while processing messages from those sockets, your suggestion of not using objects is naive at best. Re: (Score:2) Of course I was being sarcastic. Pretty much obvious, don't you think ? But still - on Embedded world you can do much without relying on dynamic allocation (and the expensive free). Just needs careful sizing and requirements analysis. Alvie Re: (Score:2) I just do some Perl (Score:2) Using Perl pretty much covers all nine and then some. Except, perhaps, for #5 Yo-yo code. That is actually a built-in feature.
https://developers.slashdot.org/story/15/10/20/1730232/bad-programming-habits-we-secretly-love?sdsrc=prevbtmprev
CC-MAIN-2017-17
refinedweb
5,445
70.73
In this tutorial I am going to show you how to create a class in python and then create an instance object from that class. What we want here is to create a python class which will receive the name, job, salary and a boolean parameter which indicates whether that person has changed his or her job recently or not so the default __str__ method from that class will return different string based on that boolean value. OK let get started. This time I will use eclipse to write the python script but you can use other IDE such as NetBeans 8.1 as well if you want to, both Eclipse and NetBeans are the top IDE I use to write the python script. Before you can create a python project in Eclipse make sure you have installed the PyDev plugin through Help->Install New Software. If you have not yet installed the PyDev plugin before then click on the Add button and provide a name together with this link to download and install the PyDev plugin. Once you have installed the plugin in Eclipse you can now go to File->New->PyDev project and create a new python project just like how you create other project in Eclipse. I will leave you to create the new project with Eclipse and concentrate on the main topic which is how to create a python class. After creating a package within that project you can now create a new module calls personaldata.py and enter the below script into it. class PersonalData(object): def __init__(self, name, work, earning = 0, change = False): self.name = name self.work = work self.earning = earning self.change = change def __str__(self): if(self.change == False): return "%s works as a %s and he has a monthly income of %s" % (self.name, self.work, self.earning) else: return "%s now works as a %s and he has a monthly income of %s" % (self.name, self.work, self.earning) def changeJob(self, work, income, change = False): self.work = work self.earning = income self.change = change Every python class needs to have an __init__ method where self is the first parameter which will be automatically passed into the method, self is very important because the instance of that class will use this parameter to call a method or to access a variable of that object. The rest of the parameters will be passed in at the time you create a new instance of that class. You can also set the default value for each parameter so that instance can use any of those values if any of those values has not been passed into the class at the time you create an instance of that class. The same goes to the class’s method as well. Now let us create the main python module which will include the PersonalData’s class instance in it. Let create a new python module and name it runmyclass.py. Now you should see those two python modules under the same package. Next enter below script into the runmyclass.py module… from personaldata import PersonalData if __name__ == '__main__': personalData = PersonalData("John", "computer programmer","1000") print (personalData) personalData.changeJob("project manager", "3000", True) print (personalData) As you can see you will need to import the PersonalData class into this module before you can use it. If you want to run any python module then you will need this line of statement, if __name__ == ‘__main__’ make sure you do that. Next let create an instance of the PersonalData class and enter the second, third and fourth parameter into it, you do not need to enter the fifth parameter if you don’t want to because it already has a default boolean value which is False. Now you can call the print method and pass in that new instance, what will happen here is this instance will call it’s own __str__ method and return a string based on the boolean value you have passed in, in this example when we first create the new instance Mr. John has not changed his job yet so change = False. We can overwrite the __str__ method and return any string that we wish to in this program. We then call the changeJob method and pass three parameters into that method, the last one will be used as the boolean value to decide which string should we return this time. The program above will produce the below output. That is it for this tutorial, as you can see creating class in python is not that hard after all, right? If you are interested in learning more about class in python then continue to read this tutorial Create an inner class in python language.
http://gamingdirectional.com/blog/2016/07/31/how-to-create-a-python-class/
CC-MAIN-2018-22
refinedweb
792
69.11
it is in java and I just sent the assignment via email as soon as possible before 26/09 That means tomorrow I am chatting from Australia, we are a day ahead I just would like to be sure not to get a very high level code. I need you to add as many comments as you can so I can understand the code. I don't want to have the solution only, I need to know how the question has been solved by the code cannot be in the 24/09 I need to study the code 21- 24 hrs I wish I can get exactly in 19 hrs Thank you Thanks Raj I didn't ask, what about the UML activity diagram? the UML is a sub question in the assignment and I want you to do the assignment and all its parts, the UML activity diagram as well part as well can you submit the code as we agreed and the uml activity diagram a couple of time after? I mean a couple of hours after Hello Raj,when are you gonna submit the code files?I am waiting :) 2 more hrs? I need the code at least now, we agreed upon that yesterday 9 hrs is too much You didn't reply me Attachment: 2013-09-23_235209_coit29222assignment2detailt2_2013.pdf Raj when are you gonna send me the solution ? Raj when are you gonna send the solution You there? I'm dealing with a trust, please don't put in a bind and tell your are gonna send me the solution today hi johndo u receive my assignment?I need to receive its solution in 11 hrscan u? yes this link time is very important for me you sure?1 ur not gonna opt out as the other expert did?because he was sure as welldont put me in a bind ! ok, I trust you waiting for the solution in 10 hrs and 45 mins Thank you My maximum number in my student ID number is XXXXX There a question about UML activity diagram can you solve it it is part of the assignmentThank you and please watch the time Would u please add as many comments as you can so I can understand the code as well? Appreciated Thank you hiok i will do which java compiler you are using I am very worried, I am gonna get the solution withing the time, John? 8 hrs remaining NetBeans IDE 7.3.1 OK, sureThanks done? 45 mins Hello John Thank you for being on time The N has to be equal to 8 in my caseplus, some imported packages are too advanced way for me "ArrayList();" we didn't use this sign before "<>" ..i could not tell which package is related to it.it's like less than more than sample. yeah please, I need the code to be less advanced plus, My N is supposed to be 8 Yes exactlyand we didn't study in our lectures those two packages import java.util.Collections;import java.util.Comparator;import java.util.ArrayList; yeah sure, 2 hrs? check point 6 in the assignment 6. Sort the customer names in ascending order and display sorted names with their discounts This option sorts the customer names in ascending order and display sorted names with their discounts. You can use any sorting algorithm which uses at least two while loops and one if statement. The built-in sort algorithm should not be used. I am gonna rate you know,Just wanted to say thank you very much for being on time with me and for helping I would appreciated if you can send me any source I can use to enhance my java programming skills, if possible Thank you again Sure :) Thanks again
http://www.justanswer.com/homework/80hqq-objectivesthis-assessment-item-designed-test-understanding.html
CC-MAIN-2014-35
refinedweb
633
75.03
Sourceware Bugzilla – Bug 4772 strptime() doesn't support strftime()'s flags Last modified: 2013-12-04 12:54:46 UTC Tomasz Kępczyński has found a bug in strptime(): its format specification doesn't support strftime()'s flags. Steps to reproduce: $ cat foo.c #define _XOPEN_SOURCE #include <stdio.h> #include <time.h> int main(void) { struct tm tm; printf("%s\n", strptime("1", "%-d", &tm) ? "Success!" : "Woe is me!"); return 0; } $ gcc foo.c && ./a.out Woe is me! $ As a result, gnucash misparses dates in, at least, Polish and Czech locale (see). The attached patch against cvs head causes strptime() to correctly parse and interpret (i.e. ignore) flags and field width. Created attachment 1915 [details] flags and field width support for strptime() There is no requirement at all that strptime understands the same formats as strftime. In fact, this will never be the case. Unless you can show that any extension is absolutely necessary to parse a *reasonable* date string I won't change anything. As I wrote in I am not convinced that this is a bug in strptime. But please note, that strftime(..., nl_langinfo(D_FMT), ...) will print something, according to format we define in a locale. My opnion is that we should be able to parse this string back to internal representation using strptime (or maybe other function) _AND_ data defined in locale definition file. The first attempt is to use: strptime(..., nl_langinfo(D_FMT),...) and this fails miserably for pl_PL.UTF8 in F7. So we either need: 1. fix in strptime 2. some oher format data in locale definition equivalent to D_FMT which will work for strptime 3. I am open to any suggestion here. Please note, that strptime with %x format specifier also fails. > There is no requirement at all that strptime understands the same formats as > strftime. In fact, this will never be the case. The strptime(3) manual page says: "For reasons of symmetry, glibc tries to support for strptime() the same format characters as for strftime()." I find it quite reasonable. The patch is trivial and solves a real-world problem. The patch is not reasonable. Ignoring the modifiers can give the wrong impression and there might be situations where it makes a difference. There never ever has been a promise that the locale formats are usable in strptime. And whatever the man page says couldn't possibly more irrelevant. The man pages are not written by the people who write the code. The info pages clearly state The only difference is that the flags `_', `-', `0', and `^' are not allowed. Using strptime to parse anything by untranslated strings is a gamble anyway. If you want to do this then prepare the strings yourself. Get the locale format, strip out the flags, and then pass it on to strptime. I have not seen any argument why this should be the problem of the implementation which at that point would expose itself to additional problems. > The patch is not reasonable. Ignoring the modifiers can give the wrong > impression and there might be situations where it makes a difference. Ignoring these modifiers matches existing behaviour. The introduced modifiers control padding, case, and field width, all of which are already ignored by strptime(). > There never ever has been a promise that the locale formats are usable in > strptime. Such a correspondence has, however, clearly been the intent. SUSv3 explicitly says: "Several "equivalent to" formats and the special processing of white-space characters are provided in order to ease the use of identical format strings for strftime() and strptime()." Since the standard format specification of strptime() closely matches the standard format specification of strftime(), it is not, in my opinion, unreasonable to expect the same from glibc's extensions to the format. Introducing a functionality that works _usually_, but not always, is a trap for unwary programmer. It is, of course, easy for gnucash to workaround this particular limitation, but the real problem is that other programs are likely to fall victim of it as well. I see you are unconvinced, let the code speak: ---- #include <clocale> #include <ctime> #include <iostream> #include <langinfo.h> int main() { time_t t; tm t1, t2; char *p, buf[128]; setlocale(LC_ALL, "pl_PL.UTF8"); t = time(NULL); t1 = *localtime(&t); std::cout << "nl_langinfo(D_FMT):" << nl_langinfo(D_FMT) << std::endl; strftime(buf, sizeof(buf), nl_langinfo(D_FMT), &t1); std::cout << "strftime (1): " << buf << std::endl; p = strptime(buf, nl_langinfo(D_FMT), &t2); strftime(buf, sizeof(buf), nl_langinfo(D_FMT), &t2); std::cout << "strftime (2): " << buf << std::endl; return(0); } ---- Results from FC6: nl_langinfo(D_FMT):%Y-%m-%d strftime (1): 2007-07-11 strftime (2): 2007-07-11 Results from F7: nl_langinfo(D_FMT):%-d %b %Y strftime (1): 11 VII 2007 strftime (2): 0 II 1953 My question is: what have I done wrong? Now, if the answer is nothing, then fix the library. If the answer is: you haven't removed flags characters from format string, then my answer is: fix the library. Reasoning: As in #6. If I have to work around something in a library then what happens if someone decides thar strftime needs to support flag, let's say '+'? I have to change the code and in that case I can as well write my own fuction. This puts us in a position where I can as well write my own library and renders strptime completly useless and in a posistion where I have as application developer to check ALL strptime calls to verify that they will work. THIS IS UNREASONABLE. Stop reopening the bug. I told you that you cannot pass locale format strings to strptime. Well, then consider this: in Polish locale strptime fails to parse time formated with stftime with the following flags: "%c" and "%x" (using these flags as format specifier for strptime itself and this is documented as valid in man page). I bet 100$ that this boils down to this problem and another 100$ that this is very close to violation of the rule you specified in comment #8 above. The code to prove my point: #include <clocale> #include <ctime> #include <iostream> #include <langinfo.h> void checkfmt(const char *fmt) { using std::cout; using std::endl; time_t t; tm t1, t2; char *p, buf[128]; t = time(NULL); t1 = *localtime(&t); cout << "format string: " << fmt << endl; strftime(buf, sizeof(buf), fmt, &t1); cout << "strftime (1): " << buf << endl; memset(&t2, 0, sizeof(t2)); p = strptime(buf, fmt, &t2); strftime(buf, sizeof(buf), fmt, &t2); cout << "strftime (2): " << buf << endl; cout << "--------------------------------------------------" << endl; } int main() { setlocale(LC_ALL, "pl_PL.UTF8"); checkfmt(nl_langinfo(D_FMT)); checkfmt("%a"); checkfmt("%A"); checkfmt("%b"); checkfmt("%B"); checkfmt("%c"); checkfmt("%x"); checkfmt("%X"); return(0); } Feel free to close if I am wrong but then we need another bug for strptime to fix %c and %x formats. This is an automated email from the git hooks/post-receive script. It was generated because a ref change was pushed to the repository containing the project "GNU C Library master sources". The branch, master has been updated via 19e3372ba4538f85b6c73361feaf408ae0e65ebe (commit) from ecaf142d3d70630a0d7f028d334b5339ff2b996d (commit) Those revisions listed above that are new to this repository have not appeared on any other notification email; so we list those revisions in full, below. - Log -----------------------------------------------------------------;h=19e3372ba4538f85b6c73361feaf408ae0e65ebe commit 19e3372ba4538f85b6c73361feaf408ae0e65ebe Author: Ondřej Bílka <neleai@seznam.cz> Date: Wed Dec 4 13:53:13 2013 +0100 Allow strptime read outputs from strftime. Fixes bug 4772. ----------------------------------------------------------------------- Summary of changes: ChangeLog | 8 ++++++++ time/strptime_l.c | 19 ++++++++----------- time/tst-strptime.c | 2 ++ 3 files changed, 18 insertions(+), 11 deletions(-) Fixed with a modified patch.
http://sourceware.org/bugzilla/show_bug.cgi?id=4772
CC-MAIN-2013-48
refinedweb
1,254
64.71
On Sat, Dec 13, 2008 at 10:08:47AM +0100, Reimar D?ffinger wrote: > On Sat, Dec 13, 2008 at 08:44:51AM +0000, Jacob Meuser wrote: > > > __BSD_VISIBLE is from cdefs.h: > > > #if !defined(_BSD_SOURCE) && \ > > > (defined(_ANSI_SOURCE) || defined(__XPG_VISIBLE) || defined(__POSIX_VISIBLE)) > > > # define __BSD_VISIBLE 0 > > > #endif > > > #ifndef __BSD_VISIBLE > > > # define __BSD_VISIBLE 1 > > > #endif > > > > yes, I know how this works. but this has never been a problem before. > > you don't see patches for this in the ffmpeg port, for example. so > > where is the other part being defined (_ANSI_SOURCE etc)? > > __POSIX_VISIBLE is always defined for FFmpeg, because _POSIX_C_SOURCE is > set. that must be new since the last time I updated ffmpeg. anyway, yes, defining _BSD_SOURCE would be the thing to do in that case. -- jakemsr at sdf.lonestar.org SDF Public Access UNIX System -
http://ffmpeg.org/pipermail/ffmpeg-devel/2008-December/043979.html
CC-MAIN-2014-10
refinedweb
132
60.51
Distributed Processing With Flex and AIRBy Jack Herrington The starship Enterprise can scan the entire surface of a planet in one second and report back that there are signs of life. But for those of us who don’t live in the world of sci-fi, searching for extra-terrestrial intelligence is a much more involved process; the computational power required is immense. So immense, in fact, that the scientists at the Search for Extraterrestrial Intelligence (SETI) developed a distributed application that ran on Mac and Windows called SETI@Home. This application allows us non-scientists to contribute the processing power of our machines to help SETI find intelligence in the stars. SETI@Home is a wonderful example of the power of distributed computing. You give a little chunk of data to a large number of computers. Let them chew on it for a while, and when they’re done they spit back the results. The larger the number of computers, the faster the processing. So how can you apply the power of distributed computing to your own cool project? I suggest using Adobe’s Integrated Runtime (AIR) technology. With AIR, you can build a single application in ActionScript, or in HTML/JavaScript, that runs on Windows, Macintosh, and Linux. And that application can use the network to request data from the server, process it locally, and send the results back to the server once the processing is completed. In this article, I’m going to demonstrate how to build all the required components of a distributed processing system. The first is the web server component that coordinates the delivery of data to clients, and receives the results from the clients. The second is the processing client, which requests the data, processes it, and returns the results to the server. The final piece is a monitoring client that monitors the activity on the server so that you can see the processing in motion. Readers who have followed this series will guess that there’ll be a quiz at the end, to test you on what you’ve learned, and help it all sink in that much further. The first 100 people to give the quiz their best shot will receive a free copy of the Adobe AIR for JavaScript Developers pocket guide in the post, courtesy of the kind people at Adobe Systems. Remember, too, that the book can be downloaded free as a PDF! Building the Server The little sample distributed application we’re going to build is a dummy solution for the “traveling salesman problem.” The problem appears to be fairly simple – you have a salesman who has a list of cities to visit. You have to deduce the most efficient route from a given starting point. This problem, however, has been proven to be one of the most difficult problems known to computer science. In this article, we’re just going to provide a random route generating stub. If you’d like to replace the stub with an effective algorithm, feel free – you’ll be on your way to winning yourself a Fields Medal! It’s the job of the server to provide the list of cities, along with their latitude and longitude, as well as providing the starting city that the client should process. Each client works on a different starting point. Once it’s finished, it sends the fastest route back to the server and requests a new starting city. We’ll write the server in PHP 5 and use the AMFPHP project to provide an AMF API to the client. If you’re unfamiliar with the Action Message Format (AMF), it’s a way of making remote procedure requests from a client to a server. It works very well with Flex, which is what we’ll be using for the client. Setting up AMFPHP couldn’t be much simpler. Download the latest code from the site and copy the code into the Apache home directory. At this point, you also may want to download the code archive for this tutorial, so you can play along at home. In this example, I’ve put the code in a subdirectory called amfphp. If you browse to, you’ll be presented with an empty service browser. In a second, we’ll see how easy it is to start populating this list with actual services. We’ll also be using SQLite to store the data on the server. The schema for the database is shown in Listing 1. Listing 1. salesman.sql CREATE TABLE city ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, lat REAL NOT NULL, lon REAL NOT NULL, processing REAL ); INSERT INTO city(name, lat, lon, processing) VALUES('Albany, N.Y.', 42, 73, null); INSERT INTO city(name, lat, lon, processing) VALUES('Albuquerque, N.M.', 35, 106, null); INSERT INTO city(name, lat, lon, processing) VALUES('Amarillo, Tex.', 35, 101, null); CREATE TABLE sequence ( start INTEGER, element INTEGER, city INTEGER ); We load this into the database by executing these commands: $ sqlite3 -init salesman.sql salesman.db SQLite version 3.4.0 Enter ".help" for instructions sqlite> .exit $ The schema is pretty simple. The city table holds the names and locations of the individual cities, along with a processing field. This processing field holds the number of solutions run against the city. If it’s non- null, it means it’s been processed. So when a new client comes along, the server will give them a starting city where the processing field is null. The sequence table holds the final sequence that the client develops as a solution when given the starting city. Next, we need to build a PHP class for accessing and manipulating this information. Create a directory called salesman inside AMFPHP’s services directory, and place the following file inside it: Listing 2. CityService.php <?php class CityService { private $_user; private $_password; private $_dsn; public function __construct() { $this->_user = ''; $this->_password = ''; $this->_dsn = 'sqlite:/Users/craiga/salesman.db'; } public function getCities() { $connection = new PDO($this->_dsn, $this->_user, $this->_password); $statement = $connection->prepare('SELECT * FROM city'); if($statement->execute()) { $result = $statement->fetchAll(PDO::FETCH_OBJ); } else { $errorInfo = $statement->errorInfo(); throw new Exception(sprintf('PDO Error %d: %s', $errorInfo[1], $errorInfo[2])); } return $result; } public function requestCity() { $connection = new PDO($this->_dsn, $this->_user, $this->_password); $statement = $connection->prepare('SELECT * FROM city WHERE processing IS NULL'); if($statement->execute()) { $result = $statement->fetch(PDO::FETCH_OBJ); } else { $errorInfo = $statement->errorInfo(); throw new Exception(sprintf('PDO Error %d: %s', $errorInfo[1], $errorInfo[2])); } return $result; } public function updateProcessing($city, $amount) { $connection = new PDO($this->_dsn, $this->_user, $this->_password); $statement = $connection->prepare('UPDATE city SET processing=:amount WHERE id=:city'); if(!$statement->execute(array('city' => $city, 'amount' => $amount))) { $errorInfo = $statement->errorInfo(); throw new Exception(sprintf('PDO Error %d: %s', $errorInfo[1], $errorInfo[2])); } return $result; } public function setSequence($city, $sequence) { $connection = new PDO($this->_dsn, $this->_user, $this->_password); $statement = $connection->prepare('DELETE FROM sequence WHERE start=:city'); if(!$statement->execute(array('city' => $city))) { $errorInfo = $statement->errorInfo(); throw new Exception(sprintf('PDO Error %d: %s', $errorInfo[1], $errorInfo[2])); } $elem = 1; foreach($sequence as $seqcity) { $statement = $connection->prepare('INSERT INTO sequence (start, element, city) VALUES (:start, :element, :city)'); if(!$statement->execute(array('start' => $city, 'element' => $elem, 'city' => $seqcity))) { $errorInfo = $statement->errorInfo(); throw new Exception(sprintf('PDO Error %d: %s', $errorInfo[1], $errorInfo[2])); } $elem++; } } } ?> This simple server has four methods. The first, getCities, returns the list of cities straight out of the database. The method starts by connecting to the database. It then runs the query and stores each row in an array. It then returns the rows as an array. To attach to the database, we use PHP Data Objects (PDO): a set of classes designed to make database access simple and portable, regardless of what database you use. In this example we’re using SQLite, but getting this code to use a MySQL, Oracle, or SQL Server backend would be a simple matter of changing the data source name (DSN). The next three methods deal with the processing. The requestCity method returns the first city that has a null processing value, meaning that the city has not yet been processed. The updateProcessing method sets the processing value in the database for the corresponding city. And the setSequence method adds the fastest route (or sequence) to the database for the corresponding starting city. If you reload the AMFPHP service browser, you’ll see that it will automatically recognize your new CityService, and display its four methods, as shown in Figure 1. As you can see from the code, writing an AMF service using AMFPHP is super easy. You don’t have to do any of the work you might expect in a web service, like formatting the data as XML, JSON, or CSV. All you have to do is write the methods as you would with any other PHP object. AMFPHP does all the work of turning PHP data types into their corresponding AMF types. Here you can see the browser in Figure 1. Along the left side of the window are the available services. In this case we have two: the built-in amfphp service and the new salesman service. When we select the salesman service, we see the CityService within it; when we select this, we see the individual methods. We can then click on the Call button to invoke the method. From here, we can view the results in different ways. Figure 1 shows the results as pseudo-objects. Then we click in the RecordSet view to produce the result in Figure 2. Pretty sweet, huh? A real web service in just a few lines of code. The server you implement for your distributed processing system will probably have a lot more methods. But given how easy it is to implement methods using AMFPHP, you should really consider using AMF and AMFPHP as your web server technology. Building the Processing Library Now that we have the server built, it’s time to start building the client. There are two ways to build AIR applications. The first is using DHTML, so that your application is written in a combination of HTML and JavaScript. The second way is to build a Flash or Flex application. We’ll go with the Flex option, and use the Flex Builder 3 IDE from Adobe to build it. Flex Builder 3 has AIR support built right in, along with a very useful debugger, and it’s free as a trial. Of course, if you’d rather use your own editor and the Flex SDK and AIR SDK, then those are available as free downloads too. Once we have Flex Builder 3 installed, the first step is to build a library for connecting to the server. Since we’re building two clients, both of which want to connect to the server, it’s best if both use the same code base. To create the library, we choose File > New > Flex Library Project. This will bring up the New Flex Library Project wizard; we name the project salesmanLib, then click Finish. This will create the salesmanLib project, which should be visible in the Flex Navigator panel. From there, we select File > New > ActionScript Class from the menu to create a new class called Server in the com.distributed namespace. This singleton object will act as a proxy for the web service. It will do all of the connecting to the web server, as well as maintain the list of cities and the current starting city. A “singleton” means that there can only be one of these objects around at a time – you access that one object by calling the instance method on the class. The code for the Server class is shown in Listing 3. Listing 3. Server.as package com.distributed { import flash.events.EventDispatcher; import mx.messaging.ChannelSet; import mx.messaging.channels.AMFChannel; import mx.rpc.events.ResultEvent; import mx.rpc.remoting.Operation; import mx.rpc.remoting.RemoteObject; public class Server extends EventDispatcher { private static const SERVER_URL:String = ""; private static var _instance:Server = new Server(); public static function get instance() : Server { return _instance; } private var _ro:RemoteObject; private var _getCities:Operation; private var _requestCity:Operation; private var _updateProcessing:Operation; private var _setSequence:Operation; private var _cities:Array = []; private var _cityById:Object = {}; private var _startCity:int = 0; public function get cities() : Array { return _cities; } public function get startCity() : int { return _startCity; } public function cityById( id:int ) : Object { return _cityById[ id ]; } public function distance( fromID:int, toID:int ) : Number { var f:Object = cityById( fromID ); var t:Object = cityById( toID ); var dx:Number = f.lat - t.lat; var dy:Number = f.lon - t.lon; return Math.sqrt( ( dx * dx ) + ( dy * dy ) ); } public function Server() { var cs:ChannelSet = new ChannelSet(); var amfc:AMFChannel = new AMFChannel("CityService",SERVER_URL); cs.addChannel( amfc ); _getCities = new Operation( _ro, "getCities" ); _getCities.addEventListener( ResultEvent.RESULT, onGetCities ); _requestCity = new Operation( _ro, "requestCity" ); _requestCity.addEventListener( ResultEvent.RESULT, onRequestCity ); _updateProcessing = new Operation( _ro, "updateProcessing" ); _updateProcessing.addEventListener( ResultEvent.RESULT, onUpdateProcessing ); _setSequence = new Operation( _ro, "setSequence" ); _setSequence.addEventListener( ResultEvent.RESULT, onSetSequence ); _ro = new RemoteObject( "salesman.CityService" ); _ro.channelSet = cs; _ro.source = "salesman.CityService"; _ro.operations = [ _getCities, _requestCity, _updateProcessing, _setSequence ]; } public function updateProgress( progress:int, seq:Array ) : void { _updateProcessing.send( _startCity, progress ); _setSequence.send( _startCity, seq ); } public function getCities() : void { _getCities.send(); } public function requestCity() : void { _requestCity.send(); } private function onGetCities( event:ResultEvent ) : void { _cities = event.result as Array; for each ( var city:Object in _cities ) { _cityById[ int( city.id ) ] = city; } dispatchEvent(new ServerEvent(ServerEvent.GET_CITIES)); } private function onRequestCity( event:ResultEvent ) : void { _startCity = int( event.result.id ); dispatchEvent(new ServerEvent(ServerEvent.REQUEST_CITY)); } private function onUpdateProcessing( event:ResultEvent ) : void { dispatchEvent(new ServerEvent(ServerEvent.UPDATE_PROCESSING)); } private function onSetSequence( event:ResultEvent ) : void { dispatchEvent(new ServerEvent(ServerEvent.SET_SEQUENCE)); } } } There is a lot of code here, but it’s all fairly simple. In the constructor, we create a connection to the server as well as to objects that represent each of the four different server methods (or operations). These operations all have listeners that are called when the method completes on the server. AMF, as well as most of Flex, is asynchronous. So when you make a call the control immediately returns. When the call completes, you receive an event back from the operation method saying that it’s completed. Let’s take getCities as an example. The getCities method calls the send method on the _getCities operation; this invokes the web server. But control comes back to the application immediately. Once the server has returned all of the data, the onGetCities method is called. That method then stores the list of cities in the _cities array, as well as creating a quick-lookup object called _cityById, which has the list of cities indexed by ID. The onGetCities method then dispatches its own custom event called a ServerEvent, which says that the cities have been downloaded by specified the event type of GET_CITIES. Create the ServerEvent class as before, by selecting File > New > ActionScript Class. The code for this class is shown in Listing 4. Listing 4. ServerEvent.as package com.distributed { import flash.events.Event; public class ServerEvent extends Event { public static const UPDATE_PROCESSING:String = 'UPDATE_PROCESSING'; public static const GET_CITIES:String = 'GET_CITIES'; public static const REQUEST_CITY:String = 'REQUEST_CITY'; public static const SET_SEQUENCE:String = 'SET_SEQUENCE'; public function ServerEvent(type:String, bubbles:Boolean=false, cancelable:Boolean=false) { super(type, bubbles, cancelable); } } } The final object we need for the library is a data object that represents a Sequence, or a route, that the salesmen will take as he goes from city to city. The Sequence class, created in the same way as the previous two classes, is shown in Listing 5: Listing 5. Sequence.as package com.distributed { public class Sequence { private var _sequence:Array = []; private var _distance:Number = 0; public function get sequence() : Array { return _sequence; } public function get distance() : Number { return _distance; } public function Sequence( cities:Array, startCity:int ) { _sequence.push( startCity ); var seq:Array = []; for each ( var city:Object in cities ) if ( int( city.id ) != startCity ) seq.push( { rand:Math.random(), city:int( city.id ) } ); seq = seq.sortOn( 'rand' ); var last:int = startCity; for each ( var cObj:Object in seq ) { _distance += Server.instance.distance( last, cObj.city ); _sequence.push( cObj.city ); last = cObj.city; } } } } The task of the Sequence class is to create the sequence and to calculate the distance of the route. To save on implementation space, we’ll just have the Sequence create a random route. (Obviously this isn’t optimal, but the point of this article is to demonstrate how to set up processing clients and servers, not really to attempt to solve the travelling salesman problem!) The library now contains all of the tools that we need to build both the processor application and the monitoring application. We’ll start by building the processor. Building the Client To build the client, we start by creating a new Flex Project (File > New Flex Project) called processor and selecting the Desktop Application (runs in Adobe AIR) option. The code for the application is shown in Listing 6: Listing 6. processor.mxml <?xml version="1.0" encoding="utf-8"?> <mx:WindowedApplication xmlns: <mx:Script> <![CDATA[ import com.distributed.Sequence; import com.distributed.ServerEvent; import com.distributed.Server; private var _minDistance:Number = Number.MAX_VALUE; private var _minSequence:Sequence = null; private var _checkedSequences:int = 0; private function onStartup() : void { Server.instance.addEventListener( ServerEvent.GET_CITIES, onGetCities ); Server.instance.addEventListener( ServerEvent.REQUEST_CITY, onRequestCity ); Server.instance.getCities(); } private function onGetCities( event:Event ) : void { Server.instance.requestCity(); } private function onTimer( event:Event ) : void { var nseq:Sequence = new Sequence( Server.instance.cities, Server.instance.startCity ); var dist:Number = nseq.distance; if ( dist < _minDistance ) { _minDistance = dist; _minSequence = nseq; } lblMinDistance.text = _minDistance.toString(); lblSequences.text = _checkedSequences.toString(); _checkedSequences += 1; if ( _checkedSequences % 10 == 0 ) Server.instance.updateProgress( _checkedSequences, _minSequence.sequence ); } private function onRequestCity( event:Event ) : void { var t:Timer = new Timer( 10 ); t.addEventListener( TimerEvent.TIMER, onTimer ); t.start(); lblStartCity.text = Server.instance.cityById( Server.instance.startCity ).name; } ]]> </mx:Script> <mx:Form> <mx:FormItem <mx:Label </mx:FormItem> <mx:FormItem <mx:Label </mx:FormItem> <mx:FormItem <mx:Label </mx:FormItem> </mx:Form> </mx:WindowedApplication> The file is split in two. At the top of the file is the ActionScript code that uses the Server object to request the cities, request the starting city, and run the sequence creation on a timer. At the bottom of the file is the user interface, which is just a Form that shows the starting city, the number of sequences tested, and the current minimum distance, which is the fastest route around the cities. Have a look back at the implementation for a second, and you’ll notice that the creation of the sequences is on a timer. That’s because the Flash environment is not multi-threaded. This means that if the application just created sequences continuously, the display would never be updated, since the display is updated when there are idle cycles. We use the timer in this case to do a little bit of processing, then let the display update, then do some more processing, and so on. You can see the application running in Figure 3. Every ten cycles the client updates the server with its progress, so that the server knows that some work is being done. In addition, the monitor can then display the current status. The final step in this simple distributed system is to build an application to monitor what’s going on server-side. Building the Monitoring Application The monitoring application is extremely simple. It gets the list of cities from the server, a list which contains the current processing numbers, and it puts up a list of the city and the current processing value, if there is one. Let’s create the monitoring application by again selecting File > New > Flex Project, entering the project’s name ( monitor), and making sure that Desktop Application is selected. The code for monitoring application is shown in Listing 7: Listing 7. monitor.mxml <?xml version="1.0" encoding="utf-8"?> <mx:WindowedApplication xmlns: <mx:Script> <![CDATA[ import com.distributed.Server; private function onStartup() : void { var t:Timer = new Timer( 1000 ); t.addEventListener( TimerEvent.TIMER, onTimer ); t.start(); } private function onTimer( event:Event ) : void { var cities:Array = []; Server.instance.getCities(); for each ( var city:Object in Server.instance.cities ) { if ( city.processing != null ) cities.push( city ); } dg.dataProvider = cities; } ]]> </mx:Script> <mx:DataGrid <mx:columns> <mx:DataGridColumn <mx:DataGridColumn </mx:columns> </mx:DataGrid> </mx:WindowedApplication> When the application starts up it creates a timer that fires off an event once every second. The application then watches for that event; each time, it first requests the list of cities and displays the current list of cities in the data grid. It uses the dataProvider attribute on the dg grid to provide the list of cities to the DataGrid control defined at the bottom of the file. The monitoring application, which shows the status of the server to the user, is shown in Figure 4. When you have the client running along with the monitoring application you can see it updating the data in real time. And if you want to have some real fun, use the Export Release Build method in Flex Builder 3 to build the production version of the client application. Then install it on a couple of different machines and run them all at the same time. Of course, you’ll have to set up a web server visible to each of the clients, but if you have everything set up the right way, you’ll have your own little distributed processing application. Where to Go from Here I used the travelling salesman problem to illustrate something that takes a long time to process. It’s not the sexiest application, I grant you – but it serves the purpose of demonstrating distributed processing. The potential for this combination of technologies – AIR, Flex, AMFPHP, and PHP – in building distributed processing is very powerful. AMFPHP makes it very easy to create a web server that manages large groups of distributed clients. And AIR and Flex make building cross-platform applications that work consistently across Windows, Macintosh, and Linux simple. Strangely, however, using AIR for distributed computing doesn’t seem to have caught on yet. I hope that this article, in combination with the obvious potential of the technologies, will help fix that. Test Your Knowledge! Now you’ve made it this far, why not test your understanding of this tutorial with this quick quiz? Be in the first 100, and you’ll score a FREE copy of the pocket guide, Adobe AIR For JavaScript Developers, courtesy of Adobe Systems, so get in quick. Just missed out? You can still download the book in PDF format for free!
https://www.sitepoint.com/distributed-processing-flex-air/
CC-MAIN-2017-34
refinedweb
3,788
55.95
I need an efficient (read native) way to convert an ArrayBuffer to a base64 string which needs to be used on a multipart post. I have following Python code to encrypt (RSA) input value using PyCrypto. Now I need to encode the encrypted value in Base64. I tried the following and I gives me following error: a bytes-like object is required, not 'tuple' How to get the encoding done correctly for Base64? from Crypto.PublicKey import RSAkey = RSA.generate(4096)f = open('C:/Test/my_rsa_public.pem', 'wb')f.write(key.publickey().exportKey('PEM'))f.close()f = open('C:/Test/my_rsa_private.pem', 'wb')f.write(key.exportKey('PEM'))f.close()f = open('C:/Test/my_rsa_public.pem', 'rb')f1 = open('C:/Test/my_rsa_private.pem', 'rb')key = RSA.importKey(f.read())key1 = RSA.importKey(f1.read())x = key.encrypt(b"MyTest",32)print(x)z = key1.decrypt(x)print(z)from base64 import b64encode, b64decodemret = b64encode(x) this is the encoded string YjRmYTJhMGEtYjI0ZC00ZjU4LTg2ZDktNTNiN2I2ODM4YjY3IzU1YjFjNGUzZTRiMGQ4OTUxMGM2YWEyNw i want to generate UUID for this I want to achieve Base64 URL safe encoding in C#. In Java, we have the common Codec library which gives me an URL safe encoded string. How can I achieve the same using C#? byte[] toEncodeAsBytes = System.Text.ASCIIEncoding.ASCII.GetBytes("StringToEncode");string returnValue = System.Convert.ToBase64String(toEncodeAsBytes); The above code converts it to Base64, but it pads ==. Is there is way to achieve URL safe encoding? I am encoding the URL suffix of my application: $url = 'subjects?_d=1';echo base64_encode($url);// Outputsc3ViamVjdHM/X2Q9MQ== Notice the slash before 'X2'. Why is this happening? I thought base64 only outputted A-Z, 0-9 and '=' as padding? I have tried using an online base64 encoder to check, and it seems base64 always does this. I can't tell if it's the underscore "_" or the question mark "?" or the "=" perhaps?
https://www.convertstring.com/id/EncodeDecode/Base64Encode
CC-MAIN-2019-43
refinedweb
308
51.95
Hi, I wonder about the changes of the next skinning architecture in Apache Flex 5 - possibly codenamed after Doug Arthur [1]. My hope is that the following goals would be achieved: 1) Get rid of the old MX namespace and place the old Flex 3 components into optional SWC files (e.g. framework_flex3.swc) 2) Refactoring UIComponent and SkinnableComponent for higher performance 3) Improving the performance of SkinnableComponent for mobile components with FXG and MXML skins 4) FXG 2.0 (or later) should be supported by Adobe design tools - like Photoshop CS6 (and later), Illustrator CS6 (and later) and Photoshop CS6 (and later) 5) An alternative open interaction design tool to Adobe Flash Catalyst CS5.5 [2] should be build by the Apache Flex community and Adobe folks ... maybe the "Radiate" project [3] will do ... for more information please read these threads [4] [5] 6) SkinnableComponents should be exportable to HTML5/CSS/JS 7) UIComponent and SkinnableComponent should be GPU accelerated in Flashplayer 11.6 (and later) Thank you for your thoughts! [1] [2] [3] [4] [5] -- Sebastian (PPMC) Interaction Designer Looking for a Login Example with Apache Flex? Please check out this code:
http://mail-archives.apache.org/mod_mbox/flex-dev/201303.mbox/%3CCAE3jacGo432pZ7WUn30m2t18TRJgnjNjWTtGLw9KQYVUQC9QaA@mail.gmail.com%3E
CC-MAIN-2018-13
refinedweb
194
60.95
On Sat, Apr 03, 2004 at 06:04:00PM -0500, Colin Walters wrote: > It is nice and clean, but we have to face the fact that mkpatch/dopatch > have to treat some filenames specially; e.g. {arch}/=tagging-method. > There's absolutely no way around that. Once you see it that way, > treating the patch logs specially isn't really different. ... and it'd make a more efficient representation for .arch-ids pretty trivial (the only real problem with doing it now being that it requires special diff/patch treatment). Would it be easier/more-reliable to make dispatching specialized diff/patch handlers based on the _id-tag_ rather than the filename (I'm thinking that there may be places in the code where the tag is availabe, but the name is not)? The sort of special arch files being discussed here already have their own special id-tag namespace, so ... -Miles -- The secret to creativity is knowing how to hide your sources. --Albert Einstein
http://lists.gnu.org/archive/html/gnu-arch-users/2004-04/msg00155.html
CC-MAIN-2014-15
refinedweb
165
61.16
We at lemon.markets provide the infrastructure so everyone can build their own brokerage experience at the stock market. In this blog post, we show you how to easily access your trading account information with one simple API call. Additionally, we dive a little deeper into our /account endpoint. Let us begin! The first step to accessing your account is to make sure that you actually have one. So, sign up on our dashboard and verify your account through the email that we send you after registration. You can then sign into the dashboard, where we already provide you with your first API Key. Finding your way around our API Using that API Key, you can go ahead and start testing our API. You can find everything you need to know in our documentation. We created several endpoints concerned with everything related to your account. Using these endpoints, you can find information about your name (in case you forgot), your current balance, how much cash you have left to invest, the IBAN of your brokerage account and many many more things. To retrieve information about your account, place a GET request against the following request URL: You can do so by grabbing the API Key from your dashboard and placing it into the following Python code snippet (find a JavaScript example in our documentation). import requests request = requests.get("", headers={"Authorization": "Bearer YOUR-API-KEY"}) print(request.json()) Placing this request will result in a response similar to this one: { "time": "2021-11-22T15:37:56.520+00:00", "status": "ok", "results": { "created_at": "2021-10-12T10:29:49.769+00:00", "account_id": "acc_pyNQNll99hQbXMCS0dRzHyKQCRKYHpy3zg", "firstname": "Michael", "lastname": "Burry", "email": "m_burry@tradingapi.com", "phone": "+491637876521", "address": "Ritterstraße 2A 10969 Berlin", "billing_address": "Ritterstraße 2A 10969 Berlin", "billing_email": "m_burry@tradingapi.com", "billing_name": "Michael Burry", "billing_vat": "DE999999999", "mode": "money", "deposit_id": "K2057263187", "client_id": "2057263", "account_number": "2057263187", "iban_brokerage": "DE12345678902057263", "iban_origin": "DE123456789012345", "bank_name_origin": "Test Bank", "balance": 100000000, "cash_to_invest": 80000000, "cash_to_withdraw": 20000000, "trading_plan": "basic", "data_plan": "basic", "tax_allowance": 8010000, "tax_allowance_start": "2021-01-01", "tax_allowance_end": "2021-01-01" } } As you can see, you get a lot of information on everything related to your account, like when it was created, what your current balance is, on which trading & data plan you are on and the IBAN of your brokerage account. Make sure to check out our documentation for in-depth information on all endpoint response parameters. Withdrawing money As you can see in the endpoint response above, you also have a response element called cash_to_withdraw. This is your current balance minus the current sum of your buy orders. Based on that number, you can very easily withdraw money into your reference account via: (Note that we are currently still working on releasing the real money feature, so it might take some more time until you can use this endpoint 🙂) Use the following code snippet (with your own API Key, of course) to withdraw money into your reference account. import requests import json request = requests.post("", data=json.dumps({ amount: 5000000, pin: 1234 }), headers={"Authorization": "Bearer YOUR-API-KEY"}) print(request.json()) Define the amount you want to withdraw in your request body, along with your individual 4-digit PIN that you set during your onboarding process. After a successful API request, the specified amount is automatically withdrawn. Retrieving your Bank statements Obviously, as a user you are interested in staying up to date regarding all activity that is happening on your account. That is what the /bankstatements endpoint is there for. The endpoint returns a list of objects containing all activities from your last “active day” (in the paper money environment) and all activities from the last working day (in the real money environment), where, by default, an end of day balance is created for you. You can access your bank statements using the following request URL: import requests request = requests.get("", headers={"Authorization": "Bearer YOUR-API-KEY"}) print(request.json()) This will return a response similar to the following one: "time": "2021-12-20T12:48:06.199+00:00", "status": "ok", "mode": "paper", "results": [ { "id": "bst_pyHLSwwFFd6r9fJsNbFhxrB3sl43xCP1GK", "account_id": "acc_pyNQNll11hQbXMCS0dRzHyNKLZTYHpy3zg", "type": "eod_balance", "date": "2021-12-16", "amount": 987033450, "isin": null, "isin_title": null }, { "id": "bst_pyQWCwwFFrBm9NhMYJ1yYDnhnMtMs64DNT", "account_id": "acc_pyNQNll11nQbXMCS0dRzHyKQCRKYHpy3zg", "type": "order_buy", "date": "2021-12-16", "amount": 8829000, "isin": "US88160R1014", "isin_title": "TESLA INC." } ], "previous": null, "next": null, "total": 2, "page": 1, "pages": 1 } As you can see, the last thing I did was I placed a buy order in the paper environment and an end of day balance was created for me. Seeing some documents Lastly, you have the chance to very easily access all important documents related to your account via the following URL: Use the following code snippet, extended by your own API Key, to retrieve a list of documents: import requests request = requests.get("", headers={"Authorization": "Bearer YOUR-API-KEY"}) print(request.json()) This will provide you with a list similar to this one: { "time": "2021-11-22T15:41:04.028+00:00" "status": "ok", "results": [ { "id": "doc_pyNjNcc77ht3T3lH8dJa5fD8jhj2JHJ1xX", "name": "account_opening.pdf", "created_at": "2021-10-19T14:58:52.813Z", "category": "kyc", "public_url": "", "link": "'", "viewed_first_at": "2021-10-19T14:58:52.813Z", "viewed_last_at": "2021-10-19T14:58:52.813Z" } ] } In there, you find all documents, along with a download link. By clicking the link, you are redirected to a .pdf version of the file. Alright, that was all there is to say about the lemon.markets account endpoints and what you can do with them. Make sure to sign up to our trading API to build your own brokerage experience at the stock market. Also, join our Slack community, where we discuss all things trading and lemon.markets with more than 400 developers. Looking forward to seeing you there 🍋 🚀 Discussion (0)
https://practicaldev-herokuapp-com.global.ssl.fastly.net/lemon-markets/how-to-access-your-lemonmarkets-trading-api-account-with-one-api-call-4h5g
CC-MAIN-2022-27
refinedweb
944
54.73
Stress-Free Deployment Options with Argo Rollouts Despite the propagation of DevOps culture for several years, many development teams still don't have a healthy implementation strategy. Join the DZone community and get the full member experience.Join For Free Working as a software consultant allowed me to get to know different realities of different companies. These realities were not always the best, and they still aren't. Despite the propagation of DevOps culture for several years, even with the emergence of many tools that facilitate the delivery of software (and many of these tools being freely distributed), many development teams still suffer when they have to deploy software in a production environment. Stress, tension, fear, guilt, and frustration are some of the feelings involved when you don't have a healthy implementation strategy. What Is Progressive Delivery? Users expect their applications to be available at all times. IT professionals expect to deploy their software as quickly and smoothly as possible. Progressive delivery is a term for software delivery strategies that aim to release new features gradually. We are talking about productive environments that are containerized and managed by Kubernetes. No matter what strategy you use to deploy your application, you will always deal with these two elements: 1) Cluster A cluster is a set of computers linked together in a network. Each computer is a node. The purpose of the cluster is to solve difficult problems using computational speed and improve data integrity. A Kubernetes cluster is a set of nodes that run containerized applications. A container packages an application and its dependencies. 2) Load Balancer This component is responsible for efficiently distributing incoming network traffic to a group of servers. Big Bang This is one of the cheapest and most primitive ways of deploying a new version of software. It's not exactly a strategy, but may seem like the natural way. During deployment, the previous version is destroyed and a new one is installed in its place. One of the obvious problems with this model is the downtime between shutting down the stable version and starting the new one. Always thinking about the best-case scenario, it can be said that this downtime is negligible, maybe a few seconds. However, in the worst-case scenario, it can last for a few days. Of course, no one would like to take the risk of having their productive environment stopped for a long period, in addition to the stress that all this generates. This basic form of deployment can be a valid alternative if the application is not critical, is not part of a business, or simply does not need high availability. Blue/Green In the blue/green strategy, two identical environments are used, one called blue and the other green, representing staging and production respectively. One of the environments stores the stable version and the other the newly deployed version. If the acceptance tests are successful, then Load Balancer traffic will be directed to the environment running the latest version. During this deployment, there is no downtime. The process is simple and fast. While the previous version is running, we can do the rollback just by pointing the load balancer at it again. Some obvious issues with blue/green are the need for a dual backend and the possibility of slowdowns while current and previous backends are running concurrently. Another factor to consider is finance. Rolling Updates In the rolling updates strategy, the update is incremental: one pod is terminated while another is started with the new software version. During the deployment process, the maximum number of Pods that can be unavailable is only one and the maximum number of Pods that can be created is also one. Rolling updates is the default Kubernetes strategy and is used in most cloud services. Canary In the canary model, deployment is incremental, as in rolling updates. The idea of the canary model is to deploy the change to a small group of servers first, test it, and then deploy it to the remaining servers. This deployment mode serves as an early warning indicator with less impact on downtime, that is, if the first deployment fails, the remaining servers will not be impacted. This upgrade is done in phases, for example, first upgrade 10%, then 25%, until you reach 100% upgrade. Argo CD To paraphrase the documentation of the tool itself: “Argo CD is a declarative, GitOps continuous delivery tool for Kubernetes.” But what is GitOps? In a nutshell, GitOps is a set of practices that empower developers to perform tasks that normally fall under the purview of IT operations teams. Argo CD is a tool that greatly facilitates the deployment process, is easy to install, is intuitive, has many features, and is open-source. To enrich this experience, let's do a quick demo starting with installing the Argo CD. Let's assume you already have Kubectl and Minikube installed on your desktop. An important requirement is that you have the Ingress Controller enabled. To enable this feature in Minikube use the following command: $ minikube addons enable ingress Everything will be simpler if you also download the following project from Github:. $ git clone $ cd exp-cd/ Within this project, I have some configurations for Istio, which is a service mesh that provides us with some interesting tools, especially in the strategy using canary. $ kubectl apply -f istio/ The next step is to install Argo CD. $ kubectl create namespace argocd $ kubectl apply -n argocd -f $ kubectl patch svc argocd-server -n argocd -p '{"spec": {"type": "LoadBalancer"}}' And to access Argo CD in the browser, make sure you have initialized all pods. Then, with the following commands, get the admin password and port forwarding from Argo CD. $ kubectl port-forward svc/argocd-server -n argocd 8080:443 $ kubectl -n argocd get secret argocd-initial-admin-secret -o jsonpath="{.data.password}" | base64 -d; echo Port forwarding is recommended to do in another terminal window. After these steps, you can access in the browser and enter the user "admin" and the newly generated password. After logging in, you must click "New App" to register your first software to be deployed using Argo CD. For this example, I filled in the fields with the following values: Application Name: realtimeapp Project Name: default Sync Policy: Manual Repository URL: Revision: HEAD Path: argo Cluster URL: Namespace: default The other fields I kept unchanged. After filling in the fields, I clicked on the Create button. If all goes well, the newly registered app will appear on the Argo CD home screen, as shown in the image below: Argo Rollouts With the Argo CD installed, we already have a tool that makes the deployment process much easier. Now adding Argo Rollouts allows us to use the strategies we covered a few lines ago. Argo Rollouts is yet another tool from the excellent open-source Argo project. Argo Rollouts is a Kubernetes controller that facilitates the implementation of a progressive delivery strategy. It can also be integrated with ingress controllers and with service meshes. Let's start by installing the tool with the following commands: $ kubectl create namespace argo-rollouts $ kubectl apply -n argo-rollouts -f After the installation is complete, we can test it on Argo CD. For this, we will click on the application that we have just registered, then on the "Sync" button, and then on "Synchronize." The first deployment will take place. Next, we will change the canary.yml file in the project, inside the argo directory, in the line corresponding to the version of the image to be applied. In this case, I changed from v1.0-1 to v1.0-2. spec: selector: matchLabels: app: realtime replicas: 5 template: metadata: labels: app: realtime spec: containers: - name: realtimeapp image: marceloweb/app-demo-html:v1.0-2 Now I will make a commit with the new version. After that, I'll sync it again on Argo CD. After clicking the "Synchronize" and "Synchronize" buttons again, Argo CD starts executing all the steps configured in the canary.yml file according to the rules that have been defined. At no time do we have downtime for our application. We can track the deployment both through the Dashboard, noting that whenever there is a pause defined in the canary.yml file, in the Dashboard the value "Suspended" is displayed under the App Health label. We can also follow the deployment through the terminal using the following command: $ kubectl argo rollouts get rollout realtimeapp It will be shown in the image below: Upon successful completion, the App Health label shows the Healthy value, as exemplified in the image below: It is also possible to verify that the deployment was successful by querying via the terminal: Conclusion If you are starting a project, there is no reason to opt for the old software delivery model. There is also no longer any reason to arbitrarily use any software that is not intended for software delivery. In this article, we analyzed some tools from the Argo project. There are no other significant tools on the market that are also open-source. All codes presented in the examples in this article are available in the following repository:. You can download, change, and migrate to your own repo. Opinions expressed by DZone contributors are their own.
https://dzone.com/articles/stress-free-deployment-options-with-argo-rollouts?fromrel=true
CC-MAIN-2022-40
refinedweb
1,551
53.51
Your exclusive source for fine clocks or movements by German craftsman for United States distribution only. Save up to 25% to up to 40% off the normal prices in the United States. Only German clock movements here! Every wall, mantel and anniversary clock listed uses the finest movements made in Germany or parts from other countries in Europe where the finest clocks in the world are crafted. Many major brands are starting to use movements built in China to cut costs. We wish to offer real German Movement Clocks at a price comparable or sometimes less than many built in China. Some of our cases are made in Asia, but all of our movements being the heart of the clock are all 100% German Movements. All of our clocks are inspected and shipped from facilities in North Carolina, Virginia, Ohio, Missouri and Michigan. Warranties are covered by ourselves as well as factory authorized service centers across the United States. Our goal is to offer the finest clocks we can import at the lowest price possible with service and parts available for every clock. Many of these offerings are hand-built or assembled and sometimes availability takes a little longer than most clocks, but most models we can deliver within 7 business days. Our Grandfather clocks can be seen here. Our Outlet store hours in Durham, N.C. are 10:00 - 6:00 Monday - Friday. Call us toll free at 1-866-402-8714 for any questions or availability of any clock selection. -Free Shipping on all Clocks-- pendulum wall clocks | hermle clock history | manufacturers | retired clocks |Grandfather Clocks | sitemap
http://www.clockimports.com/
crawl-002
refinedweb
269
71.75
Your browser does not seem to support JavaScript. As a result, your viewing experience will be diminished, and you have been placed in read-only mode. Please download a browser that supports JavaScript, or enable it if it's disabled (i.e. NoScript). Hi there, I'm wanting to access the sound tracks path attribute (and potentially other sound attributes) Is that possible with the python API? I have a null that i've created a a Special Track (Sound) on and now want to access the sound paths location as well as the time offset value. Any ideas how to do this? I can access the null object fine. Edit: I can also access the CTrack with obj = doc.SearchObject('sound') sound_track = obj.GetFirstCTrack() # Its only going to have track on it at any point in time data = sound_track.?? # what to do here? Thanks! Jono So i figured it out. This is what i needed. sound_track[c4d.CID_SOUND_NAME] sound_track[c4d.CID_SOUND_START] I also found out an extremely useful little thing! You can drag and drop attributes into the console to get their id....that should be on the front page of the python documentation for people starting in c4d py dev! Not sure how to set this to SOLVED Hi Mafster, thanks for reaching out us. We're glad to hear that the issue has been addressed already on your side and, for the sake of completeness, I'd like to point to the Python Console section in the Python Documentation. Last but not least, you can set a topic to be shown as a question via the "Topic Tools" menu drop down and, after doing that, set a topic solved by using the humburger menu in the post. Check here for further details on Q&A functionality. Best, Riccardo. @mafster Any chance you could share the final script? I’m trying to do something similar and running into some roadblocks @mrittman sure thing: from c4d import documents doc = documents.GetActiveDocument() obj = doc.SearchObject('sound') # "sound" is just an in-house convention...could be anything # Note there its the first track. Also convention... sound_track = obj.GetFirstCTrack() # Get the audio file audio_path = sound_track[c4d.CID_SOUND_NAME] If i had to get the soundtrack another way by name or something i wouldnt quite know. Im guessing using sound special track id or something might do it...im very experienced with python but complete noob to c4d just a couple weeks back. Thanks a ton @mafster, I really appreciate it! I think what I’ve got is pretty similar. I am using a python node inside of xpresso to target sound tracks. I notice you’re using CID_SOUND_NAME, while I’m using CID_SOUND_START. I hardly know anything about this stuff, so I hope I’m doing it correctly haha. import c4d #Welcome to the world of Python def main(): global output_secs output_secs = input_secs # store input_secs inside output_secs sn = doc.SearchObject(input_name) # sound in timeline t = sn.GetFirstCTrack() # 1st track of object t[c4d.CID_SOUND_START] = c4d.BaseTime(output_secs) Hey @mrittman, i cant find the id names in documentation but i think CID_SOUND_START would be the timecode of when the audio starts (notice you are assigning a BaseTime object to it) CID_SOUND_NAME which i'm using is the audio file path. My application is taking the audio file path and the image sequence output (as defined by the render output settings) and combining them via a subprocess using ffmpeg. If there was a way i could do it straight through c4d id prefer that! Mainly cos ffmpeg is a mission! especially when you need to shift/delay audio and what not.
https://plugincafe.maxon.net/topic/11459/access-sound-attributes-using-python-api/7?lang=en-US
CC-MAIN-2022-05
refinedweb
606
66.23
I've been thinking about how we could improve our diagnostics, by moving more of the diags into tasks themselves. Every task could have a diagnostics(PrintStream) method that would be called to do the diags. With this the -diagnostics routine could run through all tasks that it knows about, creates them, and for everyone one that can be created, asks for its diagnostics. This would move logic into the tasks, let junit be aware about its needs, xslt and junit report probe for an XSL engine, etc. 1. we could introspect for a public static void diagnostics(PrintStream) throws BuildException method. This would let us diagnose even if you cannot instantiate the task enough for new() to work. 2. or we'd use an interface Diagnostics that things could implement 3. the -diagnostics command and <diagnostics> tasks could be made to diagnose a single task ant -diagonistics -task junit and maybe even a single antlib namespace ant -diagnostics -xmlns antlib:org.example.something the <diagnostics> task would make it easy to test this stuff on a task-by-task basis, and for third party tasks to join in. Thoughts? --------------------------------------------------------------------- To unsubscribe, e-mail: dev-unsubscribe@ant.apache.org For additional commands, e-mail: dev-help@ant.apache.org
http://mail-archives.apache.org/mod_mbox/ant-dev/200702.mbox/%3C45C9E2B6.70207@apache.org%3E
CC-MAIN-2016-30
refinedweb
209
62.38
scr_dump, scr_init, scr_restore, scr_set - screen file input/output functions #include <curses.h> int scr_dump(const char *filename); int scr_init(const char *filename); int scr_restore(const char *filename); int scr_set(const char *filename); The scr_dump() function writes the current contents of the virtual screen to the file named by filename in an unspecified format. The scr_restore() function sets the virtual screen to the contents of the file named by filename, which must have been written using scr_dump(). The next refresh operation restores the screen to the way it looked in the dump file. The scr_init() function reads the contents of the file named by filename and uses them to initialise the Curses data structures to what the terminal currently has on its screen. The next refresh operation bases any updates on this information, unless either of the following conditions is true: - The terminal has been written to since the virtual screen was dumped to filename - The terminfo capabilities rmcup and nrrmc are defined for the current terminal. The scr_set() function is a combination of scr_restore() and scr_init(). It tells the program that the information in the file named by filename is what is currently on the screen, and also what the program wants on the screen. This can be thought of as a screen inheritance function. On successful completion, these functions return OK. Otherwise, they return ERR. No errors are defined. The scr_init() function is called after initscr() or a system() call to share the screen with another process that has done a scr_dump() after its endwin() call. To read a window from a file, call getwin(); to write a window to a file, call putwin(). delscreen(), doupdate(), endwin(), getwin(), open() (in the XSH specification), read() (in the XSH specification), write() (in the XSH specification), <curses.h>.
http://pubs.opengroup.org/onlinepubs/7990989799/xcurses/scr_set.html
crawl-003
refinedweb
296
60.35
updated copyright years \ create a documentation file \ Copyright (C) 1995,1999,2000,2003,2004. \ the ( -- ) dpp @ normal-dp = \ not defining locals latest 0<> and \ not an anonymous (i.e. noname) header if s" " >fileCR s" make-doc " >file >in @ >r parse-name 2dup s" (" str= if 2drop ') parse else 2dup s" {" str= if 2drop '} parse else \ no stack comment or locals 2drop r@ >in ! \ restore "\" s" unknown " \ default stack comment endif endif [char] \ parse 2drop >in @ bl word dup c@ IF dup count 1- chars + c@ [char] - = IF s" --" >file count >file drop ELSE drop >in ! THEN ELSE drop >in ! THEN latest name>string >file s" " >file >file s" )" >file POSTPONE \g r> >in ! endif ; : (doc-header) ( -- ) defers header put-doc-entry ; ' (doc-header) IS header
http://www.complang.tuwien.ac.at/viewcvs/cgi-bin/viewcvs.cgi/gforth/doc/makedoc.fs?rev=1.12&view=markup
CC-MAIN-2013-20
refinedweb
126
80.51
IRC log of tagmem on 2003-02-07 Timestamps are in UTC. 17:21:41 [Ian] <start> 17:21:43 [Ian] contentPresentation-26 : Separation of semantic and presentational markup, to the extent possible, is architecturally sound. 17:21:45 [DanC_jam] DanC_jam has joined #tagmem 17:22:29 [Ian] Action CL: Create a draft finding in this space. Deadline 3 March. 17:22:30 [Ian] === 17:22:34 [Ian] IRIEverywhere-27 : Should W3C specifications start promoting IRIs? 17:23:00 [Ian] CL: There is movement here; Martin commented on CL / IJ draft. 17:24:13 [Ian] CL: Interrelated with URIEquivalence. Decision there affects IRIEquivalenc.e 17:24:58 [Ian] CL: I had a proposal, but discussion happening and consensus shifting. 17:25:39 [Ian] Action CL: post document to www-tag, with notation that MD doesn't agree. 17:28:12 [Ian] 17:28:19 [Ian] ======= 17:28:43 [Ian] fragmentInXML-28 : Use of fragment identifiers in XML 17:28:47 [Ian] xmlIDSemantics-32 : How should the problem of identifying ID semantics in XML languages be addressed in the absence of a DTD? 17:28:53 [Ian] TB: I think they are related. 17:29:21 [Ian] TB: If you are solving the ID problem, you need to also decide how to solve the frag id problem. 17:29:34 [timbl] timbl has joined #tagmem 17:29:35 [Ian] [Roll call: TB, CL, PC, RF, DO, DC, SW, TBL, IJ] 17:32:46 [Ian] PC: I am willing to be owner of 32 17:33:08 [Ian] === 17:33:18 [Ian] binaryXML-30 : Standardize a "binary XML" format? 17:33:46 [Ian] (for XML ID, see msg from CL to tag ) 17:34:04 [Ian] CL: I wrote up stuff for TAG, processing input on it. 17:34:19 [Ian] TB: Is there a sense that W3C should do something in this space? 17:34:32 [Ian] CL: There are issues, e.g., streaming (been demonstrated). 17:34:47 [Ian] CL: BIM is patent-encumbered. 17:37:02 [Ian] TB: I am not favorable to W3C doing work in this area. 17:37:06 [Ian] DC: We should publish what we've done. 17:38:09 [Ian] Action CL: Write up this work on binary XML. 17:38:11 [Ian] ==== 17:38:57 [Ian] metadataInURI-31 : Should metadata (e.g., versioning information) be encoded in URIs? 17:39:10 [Ian] Action SW: Draft finding for this one. 17:39:28 [Ian] ---- 17:39:32 [Ian] xmlProfiles-29 : When, whither and how to profile W3C specifications in the XML Family 17:39:47 [Ian] PC: Henry Thompson asks what the TAG wants to happen. 17:40:03 [Ian] PC: They are looking for more details than we have given them. 17:40:13 [Ian] DC: Liam Quin has the ball on this; he has accepted this. 17:42:58 [Ian] ----- 17:46:46 [Ian] Findings. 17:47:39 [Ian] DC: I have some questions on how to compare URIs. 17:48:01 [Ian] DC: I want to tell people that if they use strcmp that they can get the right answer. 17:50:21 [Ian] TB: It's clear that strcmp won't produce a false positive, but may produce some false negatives, but that's ok for some apps. 17:51:37 [Ian] TB: People feel that appropriate place for this material is RFC2396 17:52:00 [Ian] Action TB: Send URI equiv draft finding to uri@w3.org. 17:52:33 [Ian] Resolved: Accept deep linking finding. 17:52:49 [Ian] b 17:53:01 [Ian] Action IJ: Publish Deep Linking finding as accepted finding. 17:54:55 [Ian] === 17:55:04 [Ian] [DC slide presentation on URI equivalence] 18:04:33 [timbl] Cliunets should only assume foo and foo/ are equive when redot occurs 18:04:35 [Ian] DC: Redirection [Slide information hiding] 18:05:47 [Ian] TBL: We should say here "Don't do this!" ; there's a high cost to reserved names here. 18:06:28 [Ian] TB: robots.txt has problems; could have been done lots better. 18:06:34 [Chris] Chris has joined #tagmem 18:06:48 [timbl] We should actually look at a a technical solution to the robots.txt problem in future, and even think of transitioning 18:07:55 [Ian] TB: Two things should happen: 18:08:01 [timbl] q+ to say that we should actually look at a a technical solution to the robots.txt problem in future, and even think of transitioning 18:08:08 [Ian] 1) I should take several things from DC's slides and give a different takeaway message. 18:08:11 [Zakim] Zakim has joined #tagmem 18:08:17 [timbl] q+ to say that we should actually look at a a technical solution to the robots.txt problem in future, and even think of transitioning 18:08:30 [Ian] TB 2): I think you should dress up your slides and publish it as a service to the world. 18:08:38 [Ian] Action DC: Pretty up slides and publish. 18:09:32 [Ian] TBL: You can look at 2 URIs some times and sometimes tell they are equivalent; you can never tell (just by looking at the URIs) that they are different. 18:10:03 [Ian] ==== 18:10:10 [Ian] Architecture Document 18:10:32 [timbl] q? 18:11:23 [Ian] TBL (on robots.txt): If this is bad, should we invest time into asking some group to do it properly. 18:11:51 [Ian] TBL: A generic hook for putting site metadata on a header. 18:12:09 [Ian] RF: It's a design trade-off. Latency with every GET, or reserved space to look for information. 18:12:59 [Ian] Action TBL: Write up a proposal for a new issue regarding generic metadata hooks (related to robots.txt). 18:13:01 [Ian] ==== 18:13:04 [Ian] Back to Arch Doc. 18:13:37 [Ian] SW: I like the structure of the document; but I don't think this document tells me what the architecture of the Web is. 18:14:09 [Ian] SW: Could talk more about people building on top of the platform that is the Web. 18:14:58 [Ian] SW: I'd like a conceptual model to be presented up front. 18:15:08 [Ian] SW: We get into good practice without establishing the model. 18:15:44 [Ian] SW: I'd like the doc to be as short as possible, with links out to more info. 18:16:56 [Ian] TBL: The style of the doc is close to what I think is reasonable. We spend a lot of time talking about nuggets, but have as a goal to produce an all-encompassing work. We should allow ourselves to produce a document that is uneven. 18:17:17 [Ian] TBL: I think that we should assume that the reader knows a fair amount about the WEb. 18:17:37 [Ian] TBL: We should use terms consistently, but we needn't be overly formal. 18:18:28 [Ian] TBL: If we want to be formal, doing a mathematical ontology would be unbelievably useful, but I see that as something separate. 18:19:20 [Ian] TBL: The document is morphing slowly; I don't know when to read it. 18:20:06 [Ian] TBL: HTTPRange-14 has become a discussion between me and Roy. I think that if we come up with a consistent story, people will probably go along with that. 18:21:16 [Ian] RF: I think we need to ensure that we are using the terms consistently. 18:24:25 [Ian] TB: I think I would like the doc to be thin and consist of bald statements ("this is the way it is") with examples in the document. 18:24:53 [Ian] TB: Whenever you need historical exegesis, good place for a finding. 18:25:25 [Ian] TB: Still need to clear up principle v. constraint v. choice. Need to clean up or throw out. 18:25:35 [Ian] TB: Pace has been unsatisfactory over last 4 months. 18:26:02 [Ian] TB: I'm unlikely to use CVS; Happy to use Ian as a single point of editing. 18:26:36 [Ian] CL: I'm getting more comfortable since I've started editing. 18:28:44 [Ian] PC: I don't have many concerns right now. What is public perception of the document? 18:28:50 [Ian] TB: We haven't had much feedback. 18:29:06 [Ian] PC: I don't know whether we're doing enough to get people to comment on this document. 18:30:49 [Ian] PC: Do we really expect to go to last call in 5 months? We have to have real targets about what we want in the document at last call. 18:31:50 [Ian] PC: For last call, this document has to describe the Web as it is today. I'm not convinced we have to describe the Web of the future in v 1.0. 18:34:00 [Ian] TBL: We need to make clear in status of this document that we don't expect to be done in v 1.0. 18:34:18 [Ian] PC: We need to agree to the scope of v 1.0. 18:35:05 [Ian] CL: We need to make clear whether we are following, e.g., the Process Doc model or model of a technical spec. 18:35:26 [Ian] RF: I'd like to add more scenarios and more background. 18:36:02 [Ian] RF: I think we need to do a better job explaining the framework. 18:36:44 [Ian] RF: I can deal with people using different terms; but not happy with people using same terms differently. 18:37:02 [Ian] RF: I would prefer to have an agreed upon TAG / attribute mechanism so I can edit in place. 18:37:36 [Ian] Action IJ: Explain how to edit in place. 18:38:25 [Ian] DO: To me, a lot of things are missing about the Web architecture: 18:38:32 [Ian] - We don't say what we mean by an architecture. 18:39:55 [Ian] There are things like data, connectors, etc. in RF's thesis. Those are useful; I'd like to be able to relate WSA to Web Arch via this framework.l 18:41:00 [Ian] DO: E.g., definition of "agent" used in arch doc caused criticism of term in WSA community. 18:41:00 [DanC_jam] (odd... I see those things [constraints, etc.] in our arch doc.) 18:41:38 [Ian] DO: Clearer glossary terms 18:42:39 [Ian] PC to DO: Should arch doc be limited to Web today or Web with Web services? 18:42:44 [Ian] DO: Let's discuss later. 18:42:53 [Ian] DO: We need treatment in other areas than URIs. 18:43:00 [Ian] DO: E.g., architecture of XML. 18:44:20 [Ian] DC: I'm invested in arch doc up to 2.1. Swimming in rest of 2. Not much opinion of rest of doc. 18:44:28 [Ian] DC: Process has been sort of ok for me. 18:44:44 [Ian] DC: I don't understand why there are pent up comments; people should send text. 18:45:18 [Ian] DC: On the challenge of brevity v. understandability; I see that what we are doing is having some effect. 18:45:44 [Ian] DC: Probably ok with terse prose and elaboration elsewhere. 18:46:16 [Ian] DC: In many cases, I find that rationale is economic, not logical. That's ok. 18:46:43 [Ian] DC: There are a few cases where the principle is something I agree with, but not expressed exactly correctly. 18:46:57 [Ian] DC: Often problematic in quantifiers. I owe text on this. 18:47:03 [Ian] DC: Diagrams would be nic.e 18:47:14 [Ian] DC: I'd like to see more discussion of the text that we've got. 18:47:40 [Ian] RF: I'd like to get all of us writing into the document. Fine to have 10x the text, and then reduce it from there. 18:48:24 [Ian] <break> 19:03:43 [Ian] </break> 19:03:56 [Ian] [On the Interactions section.] 19:04:03 [Ian] RF: I have affinity for this section, but not as it stands. 19:04:44 [Ian] ==== 19:04:57 [Ian] Discusssion of terms. 19:08:08 [Ian] URI ----Identifies---> Resource 19:08:25 [Ian] Resource ----RepresentedBy----> bag of bits + media type 19:09:39 [Ian] Representation includes bits and other metadata about the representation 19:10:37 [Ian] RF: I note that Content-Length is used inconsistently. 19:12:30 [Ian] TBL: Web Architecture doesn't tell you whether two resources are the same. 19:13:46 [Ian] TBL: Difference between URI-equivalence and HTTP-equivalence. 19:15:03 [Ian] TB: Both DC and TBL are right. We know that moby and moby.html are quite possibly the same thing in real life. But the Web arch doesn't have the notion of "same in real life" built in. 19:15:27 [Ian] TB: We need to ack the fact that (1) this occurs in real life but that (2) just by looking at the URI there's no way to tell. 19:17:28 [Ian] DC: I don't agree to TBL's constraint that only one URI identifies a resource and no way to talk about URI-equivalence. 19:18:09 [Ian] TB: Web arch doesn't have a built-in relationship "isEquivalentTo" that applies to multiple URIs. 19:22:16 [Ian] TBL: We agree on URIs (as set of bits) and Representations (as set of bits) since we have machines that can work on them. We don't have agreement in the abstract realm (Resources). 19:22:39 [Ian] TBL: You can't claim that "resource" is a shared term. 19:24:16 [Ian] [Disagreement about identity relationship.] 19:25:30 [Ian] DC: To me, the URI spec is a worldwide agreement for a convention for making up identifiers and how they take on meaning through use. 19:25:42 [Ian] DC: You share your understanding of their meaning by servicing GET requests. 19:30:12 [Ian] [Discussion of range of "Resource"] 19:31:37 [Ian] [Question: Can you use ANY URI to talk about ANY Resource?] 19:34:06 [Ian] TBL: My expectation is for consistent information about a resource from one representation to the next. What keeps the Web working is that the form of identity is that representations for a resource continue to convey the same information. 19:38:26 [Ian] PC: I think DC's original diagram should be included in arch doc. 19:39:26 [Ian] PC: I still haven't heard pros and cons of TBL's model v. DC's model. 19:42:36 [Ian] TBL: Problem with DC model is that when you have a URI for a real book, you can get two inconsistent DC:Creator assertions for the same URI (either email address of person who created page about the book v. Herman Melville). 19:43:43 [Ian] [RF writes "urn:isbn:2389768" on the white board] 19:44:48 [Ian] TBL: Following the specs can lead to an inconsistency. 19:45:34 [Ian] RF: DC:Creator specifically refers to the creator of the representation. 19:46:07 [Ian] RF: DC:Author is another identifiers 19:47:17 [Ian] [DC moves to reopen this issue for a variety of reasons.] 19:47:46 [Ian] DC: I think an arch doc that addresses knowledge representation is a valuable asset; I would like to spend my time there. 19:47:54 [Ian] DO: I'd prefer to not reopen this issue. 19:48:16 [Ian] PC: I'd rather not reopen. 19:48:45 [Ian] PC: The second diagram may be a refinement of the first diagram (DC's) but we can do that later. 19:49:27 [Ian] TBL: I'm not trying to go down path of KR, just trying to use terms precisely. 19:49:51 [Ian] TBL: Without getting the diagram nailed down, we will not have a precise definition of these terms. 19:50:25 [Ian] RF: WSA does need to verify that HTTP URIs don't always refer to documents. 19:51:52 [Ian] For - 4, Against - 3, Abstain 1 19:52:13 [DanC_jam] RESOLVED to reopen it. 19:52:38 [Ian] RF: I don't think we will have a document in July unless we resolve this issue. 19:52:51 [Ian] TBL: I have a hard time contributing to the document without clear term usage. 19:53:06 [Ian] SW: I think we have to agree to foundational model and put it up front in document. 19:54:40 [Ian] <pause to meeting plan> 19:54:54 [Ian] Assignments for tech plenary: 19:55:21 [Ian] Three issues, overview of arch doc, relationship of TAG to community. 19:55:35 [Ian] CL: issue 32 19:56:24 [Ian] PC: Issue 8 19:57:21 [Ian] NW (not confirmed: 29 19:58:31 [Ian] DC: Walk-through of arch doc. 19:58:58 [Ian] TBL: Role of the TAG (10 mins). 19:59:49 [Ian] Action PC: Report this plan to the tech plenary planning committee. 20:00:15 [Ian] ===== 20:00:18 [Ian] Meeting planning 20:00:27 [Ian] [May? July? Oct/Nov?] 20:05:36 [Ian] Resolved: 21 May (afternoon), 22 May, 23 May (morning) in Budapest. 20:05:52 [Ian] Action IJ: Talk to admin folks to schedule this. 20:07:37 [Ian] TBL: Please note that this overlaps with the W3C track, and so there may be some absences. 20:08:13 [Ian] Action PC: Talk to WWW 2003 conf organizers (Ivan?) about registration fees and also TAG session. 20:09:10 [Ian] Proposed 21,22,23 in YVR. 20:09:18 [Ian] RF: I prefer Bristol. 20:09:36 [Ian] DC: Likely regrets for 21 July. 20:10:00 [Ian] [Issue of not flying during weekend.] 20:10:11 [Ian] Proposed 21 afternoon,22,23 in YVR. 20:10:40 [Ian] Resolved: 21 July (afternoon), 22, 23 in Vancouver. 20:10:46 [Ian] November 20:12:38 [Ian] 14-15 Nov in Japan. 20:20:08 [Ian] [Strong expectation, but not resolved.] 20:20:21 [Ian] Action IJ: Talk to Nov AC meeting planners to see if 14-15 ok for TAG meeting. 20:20:50 [Ian] ==== 20:20:54 [Ian] Arch Doc scheduling. 20:21:03 [Ian] Does CR period make sense? 20:21:15 [Ian] SW: I think we should see, e.g., whether we help two WGs get to Rec. 20:23:13 [Ian] <lunch> 20:39:11 [Zakim] Zakim has left #tagmem 22:27:23 [Ian] </lunch> 22:28:18 [Ian] ---- 22:28:26 [Ian] Chris Lilley stuff 22:29:54 [DanC_jam] DanC_jam has joined #tagmem 22:31:41 [Ian] <we review changes CL made in source of arch doc> 22:34:34 [Ian] " 1. An Internet Media Type, which may include optional or mandatory parameters" 22:34:44 [Ian] TB: I disagree with this. There are other parameters. 22:35:36 [Ian] TB: Does internet media type include charset, etc.? 22:35:44 [Ian] DC: I'd feel better with citation of the relevant spec. 22:36:03 [Ian] RF: The whole first paragraph is bogus. 22:38:06 [Ian] TB: Do we consider that representation includes just data, or just media type header, or all headers....? 22:38:33 [Ian] From HTTP 1.1 spec: 22:38:39 [Ian] "representation 22:38:39 [Ian] An entity included with a response that is subject to content 22:38:39 [Ian] negotiation, as described in section 12. There may exist multiple 22:38:39 [Ian] representations associated with a particular response status." 22:39:31 [Ian] RF: Representation is data and metadata. 22:40:35 [Ian] TB: Representation = body + one or more headers that are included in the message response (but not part of body). 22:41:06 [Ian] TBL: Mime type is particularly important since determines how to interpret bag of bits. 22:41:22 [Chris] Chris has joined #tagmem 22:41:44 [Chris] the representation is payload in the message 22:42:18 [Chris] current text assumes a one way server to client delivery, need to widen to include sending *to* the server 22:43:12 [Chris] metadata is more stuff than just the media type 22:43:20 [Chris] eg content transfer encoding 22:43:35 [Chris] draw attention to the media type as a fundamental part of the metadata 22:43:54 [Chris] metadata in the body (eg rdf in html) is not being considered here 22:44:06 [Chris] .... or is it (html meta http-equiv stuff) 22:44:20 [Chris] rrsagent, pointer? 22:44:20 [RRSAgent] See 22:45:22 [Ian] TBL: Some parts of an HTTP header are not part of a representation 22:45:27 [Ian] DC: E.g., Date. 22:46:02 [Ian] CL: Slicing half of the headers as being in or out of the representation is a pain. 22:46:07 [Ian] DC: That's part of life as we know it. 22:46:36 [Ian] DC: "Not modified' means previous representation not good. But the transfer metadata can change. 22:46:50 [Ian] s/not good/not modified. 22:48:46 [Ian] TB: I think I agree with CL. From the perspective of agents, I have access to all headers and status. In principle and practice, this is information that is available to the agent. It doesn't seem to me to be harmful to dispatch processing based on, e.g., transfer encoding. 22:49:01 [Ian] TB: Furthermore, other headers will be invented. 22:49:15 [Ian] TB: I propose that we assert that the representation is data + all metadata. 22:49:41 [Ian] [DO distinguishes metadata about content from metadata about the message.] 22:49:44 [Chris] DO message metadata and format metadata 22:49:57 [Ian] DO: I would like to distinguish message from representation in the arch doc. 22:52:06 [Ian] RF: Representation defined this way so that it has the same meaning in both PUT and POST situations. 22:52:20 [Ian] RF: You don't create messages on a server; you create representations. 22:52:53 [Chris] messages contain representations and other headerstuff; representatios contain formats and headerstuff 22:53:46 [Chris] message metadata and representation metadata 22:53:48 [Ian] RF: We know that that it was a mistake in HTTP to not be able to distinguish msg metadata from representaiton data. 22:53:58 [Ian] RF: We would fix that in the next protocol spec. 22:54:06 [Chris] protocol-ng should explicitly differentiate there two 22:54:11 [Chris] these two 22:56:09 [Ian] RF proposal: 22:56:22 [Ian] - Resource rep consists of metadata about the representation and data for the representatoin. 22:56:30 [TBray] TBray has joined #tagmem 22:56:47 [Ian] DO: We need to talk about msgs in the arch doc. 22:56:49 [Chris] message consists of message metadata and representation. 22:57:05 [Chris] in http headers the two types of metadata are unfortunately comingled 22:57:09 [TBray] What I think we agreed on (just joined IRC so pardon if redundant) 22:57:46 [TBray] A representation includes some data, e.g.. arbitrary bag of bits, plus some metadata about the data 22:58:35 [Chris] rrsagent, pointer? 22:58:35 [RRSAgent] See 22:58:37 [DanC_jam] where is "representation data" used, Roy? 22:58:49 [TBray] In the case of HTTP, some of the headers are part of the representation, e.g. Media-type and Content-length; others are not, e.g. Date and Content-encoding 23:00:09 [Chris] add diagrams to document 23:00:18 [Chris] diagrams reuse existig concepts 23:00:25 [Ian] PC: I'd like to have a diagram, reuse existing definitions, link to authoritative specs that define these terms. 23:01:08 [Ian] DC: "entity" "entity body". 23:01:17 [Ian] RF: "representation data" comes from RF PhD. 23:02:40 [Ian] --- 23:03:53 [DanC_jam] I asked whether we intend to import "body" from the MIME spec ; the question went unanswered. Lilley said he had sufficient advice on the matter to produce another draft. Nothing was decided. 23:05:45 [Chris] add +xml to processing model section 23:05:58 [Ian] TB: In section on processing model, include info about following mime type, support for 3203, xml namespaces.... 23:08:30 [Chris] these are properties arising from using xml 23:09:12 [Chris] xml as a constraint 23:10:10 [Ian] PC: Main reason to use XML is neutral format for interoperability 23:10:11 [Chris] xml gives interop 23:10:15 [Chris] major reason 23:12:33 [Ian] RF: Application-independent at the parser level. 23:14:36 [Ian] CL: Facilitates composability. 23:14:40 [Chris] facilitates composability 23:15:55 [Chris] xml for interop 23:15:57 [DaveO] DaveO has joined #tagmem 23:16:00 [Chris] namespaces withour schemas 23:16:00 [Ian] PC: namespaces w/o schemas help define parts of xml doc. 23:16:05 [Chris] namespaces with schemas 23:16:09 [Ian] PC: When you add schemas, you get a more powerful definition language. 23:16:45 [DaveO] for definition purposes, from wsd document: A Message is the basic unit of communication between a Web Service and a Client; data to be communicated to or from a Web Service as a single logical transmission.] 23:17:11 [Chris] well knoown namespaces confer meaning 23:23:36 [Ian] CL: I try to present things as a continuum. 23:24:02 [Ian] TBL: I like "presentation", I don't like abstract/concrete. 23:25:21 [Chris] tim wants me to avoid the term semantics here - great! 23:27:27 [Ian] CL: Need to clarify use of term "interaction": network interaction or human-computer interaction. 23:27:40 [Ian] TB: "Protocol" is heavily overloaded. 23:29:13 [Ian] RF: There are multiple architectures of the Web - at the agent level, at the UI level, etc... 23:32:22 [TBray] 23:45:34 [Ian] CHris's draft: 23:45:35 [Ian] 23:46:25 [Ian] --------------- 23:46:51 [Ian] TB comments review 23:47:09 [Ian] 23:49:07 [Ian] TB: Lose distinctions. 23:49:22 [Ian] IJ: I find three distinctions useful: best practice, design choices, and axioms ("it is this way") 23:50:46 [Ian] IJ: It's one thing to design the doc with these things explicitly in mind; another to label them explicitly. 23:51:02 [Ian] TB: I'm not convinced that it's valuable to create a taxonomy and label things in the document according to this taxonomy. 23:52:04 [Ian] RF: Useful to distinguish goal, way to get to that goal, and a property established by making that decision. 23:52:56 [Ian] RF: Allows other communities to see that, by relaxing a particular constraint, they may lose a particular goal. 23:53:20 [Ian] TBL: I don't find property/goal distinction useful. 23:55:32 [Ian] RF: Constraint is "The only identifiers in the Web are URIs." 23:55:38 [Ian] RF: But arch doc is not expressed that way. 23:55:59 [Ian] TB: however, it's useful to instruct in terms of best practice. 23:56:11 [DanC_jam] i.e. "if you're pointing from one thing to another, use URIs". Yes, that's a constraint.
http://www.w3.org/2003/02/07-tagmem-irc
CC-MAIN-2016-50
refinedweb
4,621
73.07
tensorflow:: ops:: ParallelConcat #include <array_ops.h> Concatenates a list of N tensors along the first dimension. Summary The input tensors are all required to have size 1 in the first dimension. For example: # 'x' is [[1, 4]] # 'y' is [[2, 5]] # 'z' is [[3, 6]] parallel_concat([x, y, z]) => [[1, 4], [2, 5], [3, 6]] # Pack along first dim. The difference between concat and parallel_concat is that concat requires all of the inputs be computed before the operation will begin but doesn't require that the input shapes be known during graph construction. Parallel concat will copy pieces of the input into the output as they become available, in some situations this can provide a performance benefit.
https://www.tensorflow.org/versions/r1.15/api_docs/cc/class/tensorflow/ops/parallel-concat
CC-MAIN-2019-51
refinedweb
117
52.19
C Programming COP 3223 lecture 1. Raja Iqbal. About Myself. Graduate Student at the School of EECS Areas of Interest are Image Compression, Signal Processing, Hardware and ASIC Design and FPGA Architectures Work Experience Graduate Research Assistant, School of Eaja Iqbal On completion of this syllabus you should be able to There are millions of books on C Programming. I will name few that I like. #include <stdio.h> void main(void) { printf(“Hello, world\n”); } Variable names are example of identifiers.They have the following rules: char short intorshort int long int or long Floating point types float double long doubleBasic types int counter1; long num_records = 0; double length = 3.7, width = 2.7; What is 5 divided by 2? printf("There are %d people here.\n", num_people); \% or %% for literal % sign \" for literal " \n for new line \t for tab \\ for literal backslash scanf("%d %f", &my_int, & my_float); fflush(stdin); x + 2; y = x + 2; a = 5 + b = c * 2; 1. Include stdio.h and declare main 2. Declare space for variables 3. Input the value in centigrade 4. Do the calculation 5 Output the answer. void main (void) { float cent, fahr; printf("Enter temperature in Centigrade\n"); scanf("%f",¢); fahr = cent * 9/5 + 32; printf("In Fahrenheit this is %.2f degrees\n",fahr); } instead write a+= b; instead write a++ or ++a Order in which arithmetic operations are evaluated unsigned int population;
http://www.slideserve.com/albert/lecture-set-no-1
CC-MAIN-2017-30
refinedweb
235
65.32
How We Analyze and Visualize Kubernetes Events in Real Time at Rockset October 1, 2019 Kubernetes at Rockset At Rockset, we use Kubernetes (k8s) for cluster orchestration. It runs all our production microservices — from our ingest workers to our query-serving tier. In addition to hosting all the production infrastructure, each engineer has their own Kubernetes namespace and dedicated resources that we use to locally deploy and test new versions of code and configuration. This sandboxed environment for development allows us to make software releases confidently multiple times every week. In this blog post, we will explore a tool we built internally that gives us visibility into Kubernetes events, an excellent source of information about the state of the system, which we find useful in troubleshooting the system and understanding its long-term health. Why We Care About Kubernetes Events Kubernetes emits events whenever some change occurs in any of the resources that it is managing. These events often contain important metadata about the entity that triggered it, the type of event ( Normal, Warning, Error, etc.) and the cause. This data is typically stored in etcd and made available when you run certain kubectl commands. $ kubectl describe pods jobworker-c5dc75db8-7m5ln ... ... ... Events: Type Reason Age From Message ---- ------ ---- ---- ------- Normal Scheduled 7m default-scheduler Successfully assigned master/jobworker-c5dc75db8-7m5ln to ip-10-202-41-139.us-west-2.compute.internal Normal Pulling 6m kubelet, ip-XXX-XXX-XXX-XXX.us-west-2.compute.internal pulling image "..." Normal Pulled 6m kubelet, ip-XXX-XXX-XXX-XXX.us-west-2.compute.internal Successfully pulled image "..." Normal Created 6m kubelet, ip-XXX-XXX-XXX-XXX.us-west-2.compute.internal Created container Normal Started 6m kubelet, ip-XXX-XXX-XXX-XXX.us-west-2.compute.internal Started container Warning Unhealthy 2m (x2 over 2m) kubelet, ip-XXX-XXX-XXX-XXX.us-west-2.compute.internal Readiness probe failed: Get dial tcp connect: connection refused These events help understand what happened behind the scenes when a particular entity entered a specific state. Another place to see an aggregated list of all events is by accessing all events via kubectl get events. $ kubectl get events LAST SEEN TYPE REASON KIND MESSAGE 5m Normal Scheduled Pod Successfully assigned master/jobworker-c5dc75db8-7m5ln to ip-XXX-XXX-XXX-XXX.us-west-2.compute.internal 5m Normal Pulling Pod pulling image "..." 4m Normal Pulled Pod Successfully pulled image "..." ... ... ... As can be seen above, this gives us details - the entity that emitted the event, the type/severity of the event, as well as what triggered it. This information is very useful when looking to understand changes that are occurring in the system. One additional use of these events is to understand long-term system performance and reliability. For example, certain node and networking errors that cause pods to restart may not cause service disruptions in a highly available setup but often can be hiding underlying conditions that place the system at increased risk. In a default Kubernetes setup, the events are persisted into etcd, a key-value store. etcd is optimized for quick strongly consistent lookups, but falls short on its ability to provide analytical abilities over the data. As size grows, etcd also has trouble keeping up and therefore, events get compacted and cleaned up periodically. By default, only the past hour of events is preserved by etcd. The historical context can be used to understand long-term cluster health, incidents that occurred in the past and the actions taken to mitigate them within Kubernetes, and build accurate post mortems. Though we looked at other monitoring tools for events, we realized that we had an opportunity to use our own product to analyze these events in a way that no other monitoring product could, and use it to construct a visualization of the states of all of our Kubernetes resources. Overview To ingest the Kubernetes events, we use an open source tool by Heptio called eventrouter. It reads events from the Kubernetes API server and forwards them to a specified sink. The sink can be anything from Amazon S3 to an arbitrary HTTP endpoint. In order to connect to a Rockset collection, we decided to build a Rockset connector for eventrouter to control the format of the data uploaded to our collection. We contributed this Rockset sink into the upstream eventrouter project. This connector is really simple — it takes all received events and emits them into Rockset. The really cool part is that for ingesting these events, which are JSON payloads that vary across different types of entities, we do not need to build any schema or do structural transformations. We can emit the JSON event as-is into a Rockset collection and query it as though it were a full SQL table. Rockset automatically converts JSON events into SQL tables by first indexing all the json fields using Converged Indexing and then automatically schematizing them via Smart Schemas. The front-end application is a thin layer over the SQL layer that allows filtering events by namespace and entity type (Pod, Deployment, etc.), and then within those entity types, cluster events by normal/errors. The goal is to have a histogram of these events to visually inspect and understand the state of the cluster over an extended period of time. Of course, what we demonstrate is simply a subset of what could be built - one can imagine much more complex analyses - like analyzing network stability, deployment processes, canarying software releases and even using the event store as a key diagnostic tool to discover correlations between cluster-level alerts and Kubernetes-level changes. Setup Before we can begin receiving events from eventrouter into Rockset, we must create a collection in Rockset. This is the collection that all eventrouter events are stored in. You can do this with a free account from A collection in Rockset can ingest data from a specified source, or can be sent events via the REST API. We’ll use the latter, so, we create a collection that is backed by this Write API. In the Rockset console, we can create such a collection by picking “Write API” as the data source. When creating the collection, we can pick a retention, say, 120 days or any reasonable amount of time to give us some sense of cluster health. This retention is applied based on a special field in Rockset, _event_time. We will map this field to a specific field within the JSON event payload we will receive from eventrouter called event.lastTimestamp. The transformation function looks like the following: UNIX_MILLIS(PARSE_TIMESTAMP_ISO8601(event.lastTimestamp)) After creating the collection, we can now set up and use eventrouter to begin receiving Kubernetes events. Now, receiving events from eventrouter requires one more thing - a Rockset API key. We can use API keys in Rockset to write JSON to a collection, and to make queries. In this case, we create an API key called eventrouter_write from Manage > API keys. Copy the API key as we will require it in our next step setting up eventrouter to send events into the Rockset collection we just set up. You can set up eventrouter by cloning the eventrouter repository and edit the YAML file yaml/deployment.yaml to look like the following: # eventrouter/yaml/deployment.yaml config.json: |- { "sink": "rockset" "rocksetServer": " "rocksetAPIKey": "<API_KEY>", "rocksetCollectionName": "eventrouter_events", "rocksetWorkspaceName": "commons", } You can substitute the <API_KEY> with the Rockset API key we just created in the previous step. Now, we’re ready! Run kubectl apply -f yaml/deployment.yaml, and eventrouter can start watching and forwarding events right away. Looking at the collection within Rockset, you should start seeing events flowing in and being made available as a SQL table. We can query it as shown below from the Rockset console and get a sense of some of the events flowing in. We can run full SQL over it - including all types of filters, joins, etc. Querying Data We can now start asking some interesting questions from our cluster and get an understanding of cluster health. One question that we wanted to ask was - how often are we deploying new images into production. We operated on a strict release schedule, but there are times when we rollout and rollback images. With replicasets as ( select e.event.reason as reason, e.event.lastTimestamp as ts, e.event.metadata.name as name, REGEXP_EXTRACT(e.event.message, 'Created pod: (.*)', 1) as pod from commons.eventrouter_events e where e.event.involvedObject.kind = 'ReplicaSet' and e.event.metadata.namespace = 'production' and e.event.reason = 'SuccessfulCreate' ), pods as ( select e.event.reason as reason, e.event.message as message, e.event.lastTimestamp as ts, e.event.involvedObject.name as name, REGEXP_EXTRACT( e.event.message, 'pulling image "imagerepo/folder/(.*?)"', 1 ) as image from commons.eventrouter_events e where e.event.involvedObject.kind = 'Pod' and e.event.metadata.namespace = 'production' and e.event.message like '%pulling image%' and e.event.involvedObject.name like 'aggregator%' ) SELECT * from ( select MAX(p.ts) as ts, MAX(r.pod) as pod, MAX(p.image) as image, r.name from pods p JOIN replicasets r on p.name = r.pod GROUP BY r.name) sq ORDER BY ts DESC limit 100; The above query deals with our deployments, which in turn create replicasets and finds the last date on which we deployed a particular image. +------------------------------------------+----------------------------------------+-----------------------------+----------------+ | image | name | pod | ts | |------------------------------------------+----------------------------------------+-----------------------------+----------------| | leafagg:0.6.14.20190928-58cdee6dd4 | aggregator-c478b597.15c8811219b0c944 | aggregator-c478b597-z8fln | 2019-09-28T04:53:05Z | | leafagg:0.6.14.20190928-58cdee6dd4 | aggregator-c478b597.15c881077898d3e0 | aggregator-c478b597-wvbdb | 2019-09-28T04:52:20Z | | leafagg:0.6.14.20190928-58cdee6dd4 | aggregator-c478b597.15c880742e034671 | aggregator-c478b597-j7jjt | 2019-09-28T04:41:47Z | | leafagg:0.6.14.20190926-a553e0af68 | aggregator-587f77c45c.15c8162d63e918ec | aggregator-587f77c45c-qjkm7 | 2019-09-26T20:14:15Z | | leafagg:0.6.14.20190926-a553e0af68 | aggregator-587f77c45c.15c8160fefed6631 | aggregator-587f77c45c-9c47j | 2019-09-26T20:12:08Z | | leafagg:0.6.14.20190926-a553e0af68 | aggregator-587f77c45c.15c815f341a24725 | aggregator-587f77c45c-2pg6l | 2019-09-26T20:10:05Z | | leafagg:0.6.14.20190924-b2e6a85445 | aggregator-58d76b8459.15c77b4c1c32c387 | aggregator-58d76b8459-4gkml | 2019-09-24T20:56:02Z | | leafagg:0.6.14.20190924-b2e6a85445 | aggregator-58d76b8459.15c77b2ee78d6d43 | aggregator-58d76b8459-jb257 | 2019-09-24T20:53:57Z | | leafagg:0.6.14.20190924-b2e6a85445 | aggregator-58d76b8459.15c77b131e353ed6 | aggregator-58d76b8459-rgcln | 2019-09-24T20:51:58Z | +------------------------------------------+----------------------------------------+-----------------------------+----------------+ This excerpt of images and pods, with timestamp, tells us a lot about the last few deploys and when they occurred. Plotting this on a chart would tell us about how consistent we have been with our deploys and how healthy our deployment practices are. Now, moving on to performance of the cluster itself, running our own hand-rolled Kubernetes cluster means we get a lot of control over upgrades and the system setup but it is worth seeing when nodes may have been lost/network partitioned causing them to be marked as unready. The clustering of such events can tell us a lot about the stability of the infrastructure. With nodes as ( select e.event.reason, e.event.message, e.event.lastTimestamp as ts, e.event.metadata.name from commons.eventrouter_events e where e.event.involvedObject.kind = 'Node' AND e.event.type = 'Normal' AND e.event.reason = 'NodeNotReady' ORDER by ts DESC ) select * from nodes Limit 100; This query gives us the times the node status went NotReady and we can try and cluster this data using SQL time functions to understand how often issues are occurring over specific buckets of time. +------------------------------------------------------------------------------+--------------------------------------------------------------+--------------+----------------------+ | message | name | reason | ts | |------------------------------------------------------------------------------+--------------------------------------------------------------+--------------+----------------------| |:14:20-xx.us-xxxxxx.compute.internal status is now: NodeNotReady | ip-xx-xxx-xx-xx.us-xxxxxx.compute.internal.yyyyyyyyyyyyyyyy | NodeNotReady | 2019-09-30T00:10:11Z | +------------------------------------------------------------------------------+--------------------------------------------------------------+--------------+----------------------+ We can additionally look for pod and container level events like when they get OOMKilled and correlate that with other events happening in the system. Compared to a time series database like prometheus, the power of SQL lets us write and JOIN different types of events to try and piece together different things that occurred around a particular time interval, which may be causal. For visualizing events, we built a simple tool that uses React that we use internally to look through and do some basic clustering of Kubernetes events and errors occurring in them. We’re releasing this dashboard into open source and would love to see what the community might use this for. There are two main aspects to the visualization of Kubernetes events. First is a high-level overview of the cluster at a per-resource granularity. This allows us to see a realtime event stream from our deployments and pods, and to see at what state every single resource in our Kubernetes system is. There is also an option to filter by namespace - because certain sets of services run in their own namespace, this allows us to drill down into a specific namespace to look at events. If we are interested in the health and state of any particular resource, each per-resource summary is clickable and opens a page with a detailed overview of the event logs of that resource, with a graph that shows the events and errors over time to provide a holistic picture of how the resource is being managed. The graph in this visualization has adjustable granularity, and the change in time range allows for viewing the events for a given resource over any specified interval. Hovering over a specific bar on the stacked bar chart allows us to see the types of errors occurring during that time period for helpful over-time analytics of what is occurring to a specific resource. The table of events listed below the graph is sorted by event time and also tells contains the same information as the graph - that is, a chronological overview of all the events that happened to this specific k8s resource. The graph and table are helpful ways to understand why a Kubernetes resource has been failing in the past, and any trends over time that may accompany that failure (for example, if it coincides with the release of a new microservice). Conclusion Currently, we are using the real-time visualization of events to investigate our own Kubernetes deployments in both development and production. This tool and data source allows us to see our deployments as they are ongoing without having to wrangle the kubectl interface to see what is broken and why. Additionally, this tool is helpful to get a retrospective look on past incidents. For example - if we spot transient issues, we now have the power to go back in time and take a retrospective look at transient production issues, finding patterns of why it may have occurred, and what we can do to prevent the incident from happening again in the future. The ability to access historical Kubernetes event logs at fine granularity is a powerful abstraction that provides us at Rockset a better understanding of the state of our Kubernetes system than kubectl alone would allow us. This unique data source and visualization allows us to monitor our deployments and resources, as well as look at issues from a historical perspective. We’d love for you to try this, and contribute to it if you find it useful in your own environments! Link: More from Rockset Get started with $300 in free credits. No credit card required.
https://rockset.com/blog/how-we-analyze-and-visualize-kubernetes-events-in-real-time-at-rockset/
CC-MAIN-2022-21
refinedweb
2,544
55.64
On Scala, Functional Programming and Type-Classes I’ve been following the excellent Coursera course on Functional Programming Principles in Scala led by Martin Odersky. This was not my first encounter with Scala as I’ve been using it including for my day job. In parallel, because I felt the need for a Javascript replacement, I’ve been learning Clojure too, because of the excellent ClojureScript. I’ve fallen in love with both and I can’t really pick a favorite. For what is worth this document represents my (rookie) experience with Scala, being complete yack shaving on my part, or you could call it the intellectual masturbation of a fool. UPDATE: as if the article wasn’t long enough, I’ve added to it some more stuff (like a couple of times :-) 1. Functional Programming for the Win # It’s not a silver bullet, but on the whole it’s awesome. You really have to experience it, while leaving aside the preconceptions and biases you’ve been building up by honing those imperative skills for years. Students learn functional programing more easily, fresh as they are, otherwise the learning experience can be painful. But we haven’t evolved much in the last 200,000 years and so our brain finds pleasure mostly in the things that appeal to our inner-animal, being interested in the means to get laid, eat food, sleep and escape wild beasts. Learning can be a pleasure, but not when you’re venturing to unfamiliar grounds, so if you start, hang in there. We need some definitions though. Functional programming … - deals with computation by evaluating functions with referential transparency as a property (i.e. functions behave like mathematical functions, for the same input you must always get the same output) - the final output of a computation is composed out of multiple transformations of your input data, instead of building that solution by mutating state A functional programming language is one that: - treats functions as first-class objects, meaning that dealing with higher-order functions is not only possible, but comfortable - gives you the tools needed for composing functions and types By that definition languages like Ruby and Javascript can be considered decent functional languages and they are. However I would also add: - has a rich collection of immutable/persistent data-structures (in general if you want to assess the viability of any programming language, disregarding the platform it runs on, it’s perfectly characterized by its basic primitives and data-structures; e.g. think of C++, Java, or Javascript) - exposes a type-system that deals efficiently with the expression problem; Rich Hickey calls this “polymorphism a la carte” You can also go to the extreme of specifying that all side-effects must be modeled with monadic types, but that’s a little too much IMHO, as only one mostly-mainstream language fits that bill (Haskell). 2. Is Scala a Functional Programming Language? # Yes it is. You only need to follow the excellent (I mentioned above) Coursera course and solve the assignments to realize that Scala is indeed a very FP language. The course was a little short, but a follow-up is planned. Now move along … 3. Polymorphism À la Carte # This is a term that I’ve been hearing from Rich Hickey, when he talks about open type-systems, referring primarily to Clojure’s Protocols and Haskell’s Type-Classes. These mechanisms for polymorphisms are good solutions for dealing with the expression problem being in stark contrast with Object-Oriented Programming as we’ve come to know it from Java and C++. OOP is often a closed type-system, especially as used in static languages. Adding new classes into an existing hierarchy, adding new functions that operate on the whole hierarchy, adding new abstract members to interfaces, making built-in types to behave in a certain way - all of these cases are cumbersome. Haskell deals with it through Type Classes. Clojure deals with this through Multi-Methods and protocols, protocols being the dynamic equivalent for type-classes in a dynamic type-system. 4. Yes Virginia, Scala has Type-Classes # So what’s a type class? It’s like an interface in Java, except that you can make any existing types conform to it without modifying the implementation of that type. As an example, what if we wanted a generic function that can add things up … you know, like a foldLeft() or a sum(), but rather than specifying how to fold, you want the environment to know how to do that for each particular type. There are several problems with doing this in Java or C#: - there is no interface defined for “ +” on types that support addition (like Integers, BigInteger, BigDecimal, floating-point numbers, strings, etc…) - we need to start from some zero (the list of elements you want to fold could be empty) Well, you can define a type-class, like so: trait CanFold[-T, R] { def sum(acc: R, elem: T): R def zero: R } But wait, isn’t this just a simple Java-like interface? Well yes, yes it is. That’s the awesome thing about Scala - in Scala every instance is an object and every type is a class. So what makes this interface a type-class? Objects in combination with implicit parameters of course. Let’s look at how we’ll implement our sum() function that uses this: def sum[A, B](list: Traversable[A])(implicit adder: CanFold[A, B]): B = list.foldLeft(adder.zero)((acc,e) => adder.sum(acc, e)) So if the Scala compiler can find an implicit CanFold in scope that’s defined for type A, then it uses it to return a type B. This is awesomeness on multiple levels: - the implicit defined in scope for type A are establishing the return type B - you can define a CanFold for any type you want, integers, strings, lists, whatever Implicits are also scoped so you have to import them. If you want default implicits for certain types (globally available) you have to define them in the companion object of the trait CanFold, like this: object CanFold { // default implementation for integers implicit object CanFoldInts extends CanFold[Int, Long] { def sum(acc: Long, e: Int) = acc + e def zero = 0 } } And usage is as expected: // notice how the result of summing Integers is a Long sum(1 :: 2 :: 3 :: Nil) //=> Long = 6 I’m not going to lie to you as this stuff gets hard to learn and while learning how to do this, you’ll end-up pulling your hair out wishing for dynamic typing where all of this is not a concern. However you should distinguish between hard and complex (the former is relative and subjective, the later is absolute and objective). One issue with our implementation is when you want to provide a default implementation for base types. That’s why we’ve made the type parameter T contravariant in the CanFold[-T,R] definition. What contravariance means is precisely this: if B inherits from A (B <: A), then CanFold[A, _] inherits from CanFold[B, _] (CanFold[A,_] <: CanFold[B,_]) This allows us to define a CanFold for any Traversable and it will work for any Seq / Vector / List and so on. implicit object CanFoldSeqs extends CanFold[Traversable[_], Traversable[_]] { def sum(x: Traversable[_], y: Traversable[_]) = x ++ y def zero = Traversable() } So this can sum up any kind of Traversable. The problem is that it loses the type parameter in the process: sum(List(1,2,3) :: List(4, 5) :: Nil) //=> Traversable[Any] = List(1, 2, 3, 4, 5) And the reason for why I mentioned this is hard is because after pulling my hair out, I had to ask on StackOverflow on how to get a Traversable[Int] back. So instead of a concrete implicit object, you can provide an implicit def that can do the right thing, helping the compiler to see the type embedded in that container: implicit def CanFoldSeqs[A] = new CanFold[Traversable[A], Traversable[A]] { def sum(x: Traversable[A], y: Traversable[A]) = x ++ y def zero = Traversable() } sum(List(1, 2, 3) :: List(4, 5) :: Nil) //=> Traversable[Int] = List(1, 2, 3, 4, 5) Implicits are even more flexible than meets the eye. Apparently the compiler can also work with functions that return the instance you want, instead of concrete instances. As a side-note, what I did above is difficult to do, even in Haskell, because sub-typing is involved, although doing it in Clojure is easy because you simply do not care about the returned types. NOTE: the above code is not bullet-proof, as conflicts can happen Say in addition to a CanFold[Traversable,_] you also define something for Sets (which are also traversable) … implicit def CanFoldSets[A] = new CanFold[Set[A], Set[A]] { def sum(x: Set[A], y: Set[A]) = x ++ y def zero = Set.empty[A] } sum(Set(1,2) :: Set(3,4) :: Nil) This will generate a conflict error and I’m still looking for a solution that makes the compiler use the most specific type it can find, while still keeping that nice contra-variance we’ve got going (hey, I’m just getting started). The error message looks like this: both method CanFoldSeqs in object ... and method CanFoldSets in object ... match expected type CanFold[Set[Int], B] That’s not bad at all as far as error messages go. You could just avoid being too general and in case you want to override the default behavior in the current scope, you can shadow the conflicting definitions: { // shadowing the more general definition // (notice the block, representing its own scope, // so shadowing is local) def CanFoldSeqs = null // this now works sum(Set(1,2) :: Set(3,4) :: Nil) //=> Set[Int] = Set(1, 2, 3, 4) } Another solution that CanBuildFrom uses is to define implicits on multiple levels, such that some implicits take priority over others, likes so: trait LowLevelImplicits { implicit def CanFoldSeqs[A] = new CanFold[Traversable[A], Traversable[A]] { def sum(x: Traversable[A], y: Traversable[A]) = x ++ y def zero = Traversable() } } object CanFold extends LowLevelImplicits { // higher precedence over the above implicit def CanFoldSets[A] = new CanFold[Set[A], Set[A]] { def sum(x: Set[A], y: Set[A]) = x ++ y def zero = Set.empty[A] } } And yeah, it will do the right thing. A little ugly though, as it means you have to have specific knowledge about how these implicits are prioritized. In essence, this is heavy stuff already and a little complex too. Good design can make for kick-ass libraries though. 5. Scala’s Collections Library is Awesome # So what does the above buy you anyway? The following are some examples from Scala’s own collections library. You can sum things up in sequences, as long as you have an implementation of type-class Numeric[T] in scope: List(1,2,3,4).sum //=> Int = 10 You can sort things, as long as you have an implementation of type-class Ordering[T] in scope: List("d", "c", "e", "a", "b").sorted //=> List[java.lang.String] = List(a, b, c, d, e) A collection will always do the right thing, returning the same kind of collection when doing a map() or a flatMap() or a filter() over it. For instance to revert the keys and values of a Map: Map(1 -> 2, 3 -> 4).map{ case (k,v) => (v,k) } //=> scala.collection.immutable.Map[Int,Int] = Map(2 -> 1, 4 -> 3) However, if the function you give to map() above does not return a pair, then the result is converted to an iterable: Map(1 -> 2, 3 -> 4).map{ case (k,v) => v * 2 } //=> scala.collection.immutable.Iterable[Int] = List(4, 8) Even more awesome than this, take for example the BitSet which is a compressed Set of integers (so it’s optimized for storing integers): import collection.immutable.BitSet BitSet(1,2,3,4).map(_ + 2) //=> BitSet = BitSet(3, 4, 5, 6) Mapping over it still returns a BitSet, as expected. However, look at what happens when the mapping function returns Strings: BitSet(1,2,3,4).map(x => "number " + x.toString) //=> Set[java.lang.String] = Set(number 1, number 2, number 3, number 4) Again, it did the right thing, because you can’t store Strings in a BitSet, as BitSets are for integers. So it returned a plain Set of strings. How is this possible, you may ask? The answer is in the CanBuildFrom pattern. The signature of map() used above is a bit of a mouthful: def map[B, That](f: (Int) => B)(implicit bf: CanBuildFrom[BitSet, B, That]): That So, similar to my example with CanFold: - the compiler takes type B from the mapping function f: (Int) => Bthat’s provided as an argument - searches for an implicit in scope of type CanBuildFrom[BitSet, B, _] - the return type is established as the third type parameter of the implicit that is used - the actual building of the result is externalized; the BitSet does not need to know how to build Sets of Strings So basically, if you define your own types like so: class People extends Traversable[Person] { /* yada yada... */ } case class Person(id: Int) Then if you want the mapping (or flatMapping) of a BitSet to return a People collection in case the function returns Person, then you have to implement an implicit object of this type: CanBuildFrom[BitSet, Person, People] And then this will work: BitSet(1,2,3,4).map(x => Person(x)) //=> People = People(Person(1), Person(2), Person(3), Person(4)) So what’s great is that the provided implicits for CanBuildFrom can be overridden by your own implementations and you can provide CanBuildFrom implementations for your own types, etc… (as a side note, Clojure cannot do conversions based on the given mapping function, even if the Seq protocol is awesome nonetheless and doing something akin to CanBuildFrom in Haskell is difficult from what I’ve been told) If you want a lazy Iterator (like if you want to wrap JDBC result-sets), you only need to wrap the JDBC result-set in an Iterator by implementing next() and hasNext. You then get filter()/ map()/ flatMap() for free, but with a twist - Iterators are lazy and can only be traversed once. Applying filter/map/flatMap will not traverse the Iterator, being lazy operations. To convert this into a lazy sequence that also memoizes (stores) the results for multiple traversals, you only need to do iterator.toStream, or to get all the results at once iterator.toList. Streams in Scala are lazy sequences. You can easily implement infinite lists of things, like Fibonacci numbers or the digits of PI or something. But Streams are not the only lazy collections, Scala also has Views and you can transform any collection into a corresponding view, including Maps. But that’s not all. Scala also has implementations of collections that do things in parallel. Here’s how to calculate if a number is prime, sequentially: import math._ def isPrime(n: Int) = { val range = 2 to sqrt(abs(n)).toInt ! range.exists(x => n % x == 0) } If you have multiple cores around doing nothing, here’s how to calculate it by putting those extra cores at work: def isPrime(n: Int) = { val range = 2 to sqrt(abs(n)).toInt ! range.par.exists(x => n % x == 0) } Notice the difference? 6. Is this complex? # I mentioned above that this stuff is not complex, it’s just hard. Scala does have complexities when it comes to really advanced use-cases, as can be seen in this article: True Scala Complexity It’s worth mentioning however that, as Martin Odersky noted in the Hacker News thread of that article, the author tries to accomplish something that’s not possible in most languages out there, while a solution is still possible in Scala (albeit with small limitations). 7. Are OOP Features Getting in the Way? # I happen to disagree and I actually love the blend of OOP with functional features. Martin Odersky claims that OOP is orthogonal to functional programming. But if you pay attention, you’ll notice it’s not only orthogonal, but complementary in an elegant way. I’m indicating below instances where I think OOP helps, but as a clear example of what the combination can do, consider Scala’s Set. A Set[T] can be viewed as a function that takes a parameter of type T and returns either True if the value is in the Set, or False otherwise. This means you can do this: val primaryColors = Set("red", "green", "blue") val colors = List("red", "purple", "yellow", "vanilla", "white", "black", "blue") colors.filter(primaryColors) This is possible because our set is in fact a subtype of Function1[String, Boolean], so you can pass it to any higher-order function that expects that signature. But the similarity goes deeper than simple resemblance and syntactic sugar. If you remember from school, a mathematical Set can be perfectly described by what is called a characteristic function, so Sets are interchangeable with functions in mathematics. This means operations on Sets like unions, intersections, complements, Cartesian products and so on can be replaced with operations on functions and that’s exactly what boolean algebra is about. In mathematical terms, these mathematical structures (sets and functions that take an argument and return 0/1) are equivalent (indistinguishable) because there exists an isomorphism between them, savvy? :-) And I don’t know how Haskell handles this for Data.Set, or if it handles it at all, but OOP subtyping seems like the easiest way to model something like this in a static language … - for one, the hierarchy is simple to understand, simple to model, as subtyping is something that OOP simply does - you just inherit from Function1[-T, +R]- and you’re done - downcasting to a function is something OOP simply does - you just pass your object to something that expects a function and you can forget the original type of that value This is just a small and insignificant example of course, like most examples I’m giving here, but to me properly done OOP (where every type is modeled with classes and every value is some kind of object) just feels right … I like this principle of “turtles all the way down”, even if you could probably point to things that aren’t “turtles”, but this also happens in languages that are the epitome of kick-ass turtles-recursion, like Scheme or Smalltalk. 8. Scala versus Haskell # Scala’s static type-system is sometimes less expressive than that of Haskell. In particular Haskell supports rank-2 polymorphism, while Scala only rank-1. One point that Scala wins over Haskell is definitely this one: List(1,2,3,4,5).flatMap(x => Option(x)) //=> List[Int] = List(1, 2, 3, 4, 5) Doing the above in Haskell (using the bind operator) triggers a compile-time error, because the return type of the mapping function is expected to be of type List and the Maybe type (the equivalent of Option) is not a List. Option in Scala is not a collection, but it is viewable as a collection of either 0 or 1 elements. As a consequence, because of good design decisions, the monadic types defined in Scala’s collection library are more composable. EDIT: this example is simple and shallow. As pointed out in the comments, it’s easy to make the conversion by yourself, however I’m talking about the design choices of Scala’s library and the awesomeness of implicits. As a result, the standard monadic types provided by Scala (all collections, Futures, Promises, everything that has a filter/map/flatMap, etc…) are inherently more composable and friendlier. It’s also worth pointing out that Scala’s collections library is so awesome precisely because OOP plays a part and there are cases where doing similar things in Haskell require experimental GHC extensions. For instance, all of the collections in Scala share code in one way or another. If you want to build your own Traversable you only have to implement that trait with the abstract foreach(), but you get all other methods, including filter()/ map()/ flatMap() for free. As a side-effect your collection will be a monadic type by default. Haskell is lazy by default. This is good for many problems. In Scala lazyness is a choice. In Haskell this lazyness is awesome, but in my experience while playing with it, it gets very hard to reason about the resulting performance. Sometimes it’s fast without you doing anything, other times - well, profiling and fixing performance issues in Haskell is not for mortals. Scala is more predictable, being strict and lazy when needed. It also has at its disposal the awesome JVM ecosystem for profiling and monitoring. 9. Scala versus F# / Ocaml # F# is good if you want to use C# 2020. But F# has rough edges inherited from Ocaml, while it has not inherited all the benefits. F# has nominative typing, instead of structural typing for OOP (as Ocaml). And you really start wishing for an ad-hoc polymorphism mechanism in which the types are open. In regards to how one implements CanFold F# takes the crown as the ugly ducklin’ as it follows the (really screwed) C# conventions of defining “ +” as static functions on classes (a reminiscence of C++ btw), so even if you know that a T is an Integer, you can’t sum 2 Integers based on the interface definition alone, because the compiler cannot make the connection to T + T, as in OOP interfaces/subtyping only applies to instances, not classes and “static members”. This is why they had to extend the language. Take a look at the signature for List.sum in F#: List.sum : ^T list -> ^T (requires ^T with static member (+) and ^T with static member Zero) First of all, this is bad from all perspectives, as it uses the (really fucked up) notion of “static members” that should have never happened in OOP. It’s also not a type-class as it is not open - you cannot modify a built-in type to have the required static members, being the same problem you get with classic OOP inheritance of interfaces. You also cannot override the implementation, as you’d wish in certain contexts. In Scala there is no such thing as “static members”, “ +” operations being plain polymorphic instance methods. The one thing I really like about F# are quotations, which give you .NET LINQ, with the difference that quotations in F# are more potent than what C# can do. In simple words, quotations in F# give you the possibility of repurposing/recompiling pieces of code at runtime (e.g. macros). But macros support is an upcoming feature of Scala 2.10, which is already at RC1 and you can play around with the up-coming Scala version of LINQ right now. Ocaml goes a long way with its structural typing for OOP. Ocaml has the most advanced type-inferencer out of the popular functional languages, being more advanced than the one in Haskell. It’s a potent language, but sadly it has no equivalent for type-classes. The right way to implement CanFold in Ocaml/SML would be to explicitly pass a dictionary of pointers around, as described here: Typeclass overloading and bounded polymorphism in ML. Scala, unlike Ocaml and F#, does not have 2 type-systems in the same language, as Scala follows the “uniform access principle”. Type-classes and algebraic data-types are still modeled by means of OOP classes and objects. Why does it matter? If you ever worked with C++ you can understand this - if OOP is pervasive in your language and not just something completely optional, then every type in the system should be (or considered) polymorphic and extending from some Object, otherwise you’ll end up with lots and lots of pain. It’s also a matter of having to make choices. In Scala the code is indeed more verbose, but it reduces complexity a lot because a big part of learning Ocaml is learning when OOP is appropriate, or not, as you have to pick from the get-go and combining approaches is very cumbersome. Take for instance the definition of an immutable and persistent List. A List can be defined efficiently as an algebraic data-type, being either an Empty List, or a Pair of 2 elements, the head and the tail, right? In Ocaml: type 'a my_list = Nil | List of 'a * 'a my_list Extremely elegant and simple. And in Scala: sealed abstract class List[+T] case class Pair[+t](head: T, tail: List[T]) extends List[T] case object Nil extends List[Nothing] What a mouthful. One difference should immediately be noticeable, our List has covariant behavior, meaning that a List[String] is also a List[Any], or a List[j.u.HashMap] is also a List[j.u.AbstractMap]. Arrays in Java have the same behavior and this leads to lots of gotchas, but if our List is immutable, then this is not a problem, but a bonus. For instance this gives you polymorphic behavior without needing type parameters or higher-kinded types or other mechanisms, just plain OOP subtyping relationships: def length(list: List[Any]) = list match { case Pair(head, tail) = 1 + length(tail) case Nil => 0 } However, that’s not efficient. A much better approach is to make length() polymorphic (in the OOP sense), after all length() is a defining property of Lists, so there’s no reason for why it shouldn’t be there: sealed abstract class List[+T] { // abstract definition def length: Int } case class Pair[+T](head: T, tail: List[T]) extends List[T] { val length = 1 + tail.length } case object Nil extends List[Nothing] { val length = 0 } Now, isn’t that nice? What would it take to turn this into a lazy list? case class Pair[+T](head: T, tail: () => List[T]) extends List[T] { lazy val length = 1 + tail().length } You can see how length hasn’t changed for either List[T] or for Nil, just for Pair, which makes it a good candidate for OOP. So why not model this with OOP in Ocaml? Because for algebraic data-types, the compiler helps you, like this: def sum(list: List[Int]): Int = list match { case Pair(head, tail) => head + sum(tail) //-> oops, no termination } //-> output from the compiler ... warning: match is not exhaustive! missing combination Nil def sum(list: List[Int]): Int = list match { ^ Did I mention Scala also has structural typing if you want it? Yes it can (albeit, without the awesome type-inferencing that Ocaml is capable of and it’s mostly based on runtime reflection): type Closeable = { def close():Unit } def using[A, B <: Closeable](closable: B)(f: B => A): A = try { f(closable) } finally { closable.close() } This comparisson isn’t really fair btw, because I’ve been fixating on issues that Scala does really well. Ocaml is great, however I personally find it limiting and awkward at the edges of the 2 type systems it contains. Or maybe I’m just a spoiled brat. 10. Static-type versus Dynamic-type Systems # Static versus dynamic is what polarizes developers most in separate camps. It’s like a never-ending flamewar, with healthy dosages of religiosity. At its core, a static type system helps you by providing proof at compile-time that the types you’re using behave as you expect them to behave (note I’m speaking of types, not instances). This is good, because you need all the help you can get and static typing can eliminate a lot of errors. This is a doubly-edged sword though. By definition a static type system will reject pieces of code that are perfectly correct. Also, it’s not a silver bullet, as Rich Hickey said in his excellent Simple Made Easy talk: “What’s the common thing that all bugs in the wild share? They passed the type-checker, they passed all the tests!” I’ve seen opinions that “structural typing” or “type-inference” are as good as “duck typing”. That couldn’t be further from the truth - the real power of duck typing comes from the ability to create / modify types and functions on the fly at runtime. In other words you can make shit up and as long as it’s correct, then it works. In contrast, a static type system actively rejects pieces of code if it can’t prove that the types you’re using support the computation you’re trying to do, so no matter how smart the type system is, you’ll always end up in lots of instances where you have to spoon-feed the compiler to allow you to do what you mean (n.b. not all compilers are equal). This is not to say that static typing is bad. Well, it is bad in languages where the type system is designed to help the IDE and not the developer (e.g. Java, Delphi, Visual Basic). Otherwise, especially in combination with referential transparency, it really eliminates a whole class of errors. Here we define an error as being an incorrect state of the computation or corrupted output that takes the developers by surprise. An exceptional state that’s being controlled is not an error. This is why Haskell makes such a big fuss out of dealing with side-effects by means of monadic types - because it makes you think about exceptional state and either deal with it, or make it somebody else’s problem. Thinking of Scala versus Clojure and Haskell, in regards to its static-type system Scala sits somewhere in the middle. This is both good and bad. On one hand Scala does not have the same (static) expressive capabilities of Haskell, being a poor substitute for it when working with higher-kinded types. On the other hand you can drill holes in that static-type system to make it do what you want, which I think is a good trade-off. I personally lean towards dynamic type systems, however the tradeoffs I end up making in Scala are worth it for the extra type safety it brings. On the other hand Clojure, because of its support for multi-methods and protocols and macros, is a dynamic language that’s more expressive than most other languages, including dynamic ones, especially the mainstream, like Python, Ruby, Perl, Javascript or PHP. 11. Performance # I don’t have any experience or proof on this, just personal feelings :-) Scala runs on top of the JVM. When using closures or immutable data-structures, it is wasteful. However there are a few things to consider: - Scala can be as low-level and as efficient as Java for the hot codepaths and low-level Scala code is still higher-level than Java (for instance the pimp-my-library pattern will have 0 overhead starting with Scala 2.10, while implicit parameters are compile-time) - the built-in immutable data-structures are optimized to be versioned / to reuse memory of prior states - just as when adding a new element to a List the old reference gets used as the tail, this also happens with Vectors and Maps - they are still less efficient than Java’s collections, but it’s a good tradeoff as these data-structures can be used without read-locks, so bye, bye lock-contention of threads - Scala creates lots of short lived objects. This can stress the garbage collector, but on the other hand the JVM has the most advanced garbage collectors available, so you shouldn’t worry about it unless profiling tools tell you to … for instance on the JVM heap allocation is as cheap as stack allocation, it can also do some escape analysis to get rid of some locks and to allocate some short-lived objects on the stack and deallocation of short-lived objects is cheap, because the GC is generational so it deallocates whole chucks of memory at once instead of individual references … so why worry about it? - the only instance to be concerned about is if you’re building on top of Android, as Android does not have a JVM - but even there, Scala is workable (or so I’ve heard) 12. Tools of the Trade # I have a love/hate relationship with SBT, the defacto builds manager for Scala, the replacement for Maven, the slayer of XML files. The syntax is really weird and leads to cargo-culting. It broke compatibility and so many examples available online are out of date. When you’re reading the Getting Started tome, it describes something about immutable data-structures, settings options that are either lazy or strict, how to transform values with a ~= operator, something about another operator written as <<= and so on. Comparing this to how you work with Ruby Gems / Rake and Bundler is simply not fun. Only a mother could love this syntax. Then I’ve already had problems with its Ivy integration, not being able to solve some dependencies. Thankfully I could find a fix. On the other hand it’s really pragmatic and I prefer it over Maven, even if the Scala Maven plugin is in really good shape right now. Here are some highlights of SBT: - it can do cross-builds between multiple Scala versions; as is well known, major Scala versions are breaking binary compatibility, so if you want your library to support multiple Scala versions then SBT is a must, as it makes cross-building a breeze (it’s almost too easy) - it’s well integrated with ScalaTest, being able of continous compilation and testing, with output in colors - a really good tool for TDD - it makes it easy to deal with multiple sub-projects in the same root project, sub-projects that can be worked-on, tested or published individually or as a whole - all Scala projects have instructions for SBT first, Maven second and missing instructions for everything else - this is particularly painful if you’re dealing with plugins (like doing precompilation of templates with Scalate or something) I use Emacs. IDEs are not on the same level as Java. But I tried out IntelliJ IDEA’s Scala plugin and it’s quite decent, with refactoring, intellisense and everything nice. An Eclipse plugin is also available, developed now by TypeSafe, however last time I tried, it was unstable. So IDEs for Scala are in a worst shape than for Java, but on the other hand these IDEs are functional and completely awesome when compared to what you get by picking other functional languages, except maybe F#. With Scala you can use all the profiling and monitoring tools and classpath reloading tricks that you can use with Java. Nothing’s stopping you, as every tool meant for the JVM also works with Scala. 13. Concurrency and Parallelism # It’s enough to say that Scala doesn’t restrict you in any way: - Light-weight actors that can process tons of messages (Erlang-style) and that work either on the same machine, in a single process, or distributed over a network - Futures and Promises, which in contrast to other languages (* cough * javascript / jquery * cough *) are properly implemented as monadic types - Software transactional memory, as in Clojure - Parallel collections - Async/await as in C#, though it requires a compiler plugin - The awesome Java NIO, along with Netty, Mina and the whole ecosystem for async I/O (you don’t know what pleasure feels like until you wrap Async-Http-Client in Akka Promises which you can combine in for-comprehensions) Basically Scala has it all. This may seem like a curse, but what other languages define as built-in / hard to change / hard to evolve features, Scala defines as libraries. So there are definitely upsides ;-) 14. Learning Resources # I’ve found the following to be good resources for learning Scala (note that Amazon links have my affiliate tag, but if you want the eBook version don’t buy from Amazon, prefer buying directly from the publisher, as you’ll get both a DRM-free Kindle version and a PDF): Functional Programming Principles in Scala, already mentioned, is an excellent course provided by Coursera / EPFL, taught by Martin Odersky. The course is almost over, but the material will be left online, which means you can follow the lectures and do the assignments and I’m pretty sure many students that attended will remain on that forum for answering questions. Scala School: a freely available online tutorial by Twitter, which is very friendly to newbies. I’ve read it and it’s pretty good. Scala Documentation Project: definitely checkout this website, as they aggregate everything good here. If you want to learn more about Scala’s library, especially the collections, this is the place to learn from. Ninety-Nine Scala Problems: a collection of 99 problems to be solved with Scala. If you get stuck, you can view a solution which is often idiomatic. See also this GitHub project that gives you a complete test-suite, to spare you of the effort. (like I just did). The PDF for the first part (out of 3) is available from the Typesafe website. Scala in Depth by Joshua Suereth D. - this is an advanced book on Scala, with many insights into how functional idioms work in it. I’ve yet to finish reading, as it’s not really an easy lecture. But it’s a good book. Get the eBook straight from Manning. The End, Finally # A sequel on what makes Clojure great will follow when I have the time or patience for it (or once I finish reading the Joy of Clojure, great book btw).
https://alexn.org/blog/2012/11/02/scala-functional-programming-type-classes/
CC-MAIN-2022-33
refinedweb
6,295
55.78
Azure Function fails to find file I have an azure function that uses the Azure context. When I execute my function from visual studio 2019 on my machine, it executes correctly. However when I publish this to my Azure account, I get an error that the my.azureauth file cannot be found. Could not find file 'D:\Program Files (x86)\SiteExtensions\Functions\2.0.12950\32bit\my.azureauth' The code that is used: var authFilePath = "my.azureauth"; Console.WriteLine($"Authenticating with Azure using credentials in file at {authFilePath}"); azure = Azure.Authenticate(authFilePath).WithDefaultSubscription(); sub = azure.GetCurrentSubscription(); Console.WriteLine($"Authenticated with subscription '{sub.DisplayName}' (ID: {sub.SubscriptionId})"); This is code that I found on one of the Microsoft tutorials. I have set my my.azureauth file to "Copy Always". Could anyone point my in the right direction? You are get this file path because the Directory.GetCurrentDirectory() would return D:\Program Files (x86)\SiteExtensions\Functions\2.0.12950\32bit instead of D:\home\site\wwwroot\ or D:\home\site\wwwroot\FunctionName. And if you want to get the wwwroot folder or the function app directory you should use ExecutionContext. Further more information you could refer to this wiki doc. So the right file path should be context.FunctionDirectory+"\my.azureauth" or context.FunctionAppDirectory+"\my.azureauth", which one to use depends on where your file is stored. Azure Function can't find file on D:\ - MSDN, But new stuff will not. Edit: If I use d:\local\temp, then check and create d:\local\ temp\mca, ftp files to the mca folder, the functions can read the� Slow file copying to and from Azure Files in Windows. You might see slow performance when you try to transfer files to the Azure File service. If you don't have a specific minimum I/O size requirement, we recommend that you use 1 MiB as the I/O size for optimal performance. Welcome to Stackoverflow. Firstly, I'd recommend strongly against using file-based authentication as shown in your question. From notes: Note, file-based authentication is an experimental feature that may or may not be available in later releases. The file format it relies on is subject to change as well. Instead, I would personally store the connection string details (AzureCredentials) in the config file (Web/SiteSettings) and use the provided constructor... Again, the below are taken from the documentation notes: Similarly to the file-based approach, this method requires a service principal registration, but instead of storing the credentials in a local file, the required inputs can be supplied directly via an instance of the AzureCredentials class: var creds = new AzureCredentialsFactory().FromServicePrincipal(client, key, tenant, AzureEnvironment.AzureGlobalCloud); var azure = Azure.Authenticate(creds).WithSubscription(subscriptionId); or var creds = new AzureCredentialsFactory().FromServicePrincipal(client, pfxCertificatePath, password, tenant, AzureEnvironment.AzureGlobalCloud); var azure = Azure.Authenticate(creds).WithSubscription(subscriptionId); where client, tenant, subscriptionId, and key or pfxCertificatePath and password are strings with the required pieces of information about your service principal and subscription. The last parameter, AzureEnvironment.AzureGlobalCloud represents the Azure worldwide public cloud. You can use a different value out of the currently supported alternatives in the AzureEnvironment enum. The first example is most likely the one you should be looking at. The notes I got this information from can be accessed here. How to view Azure Function files deployed, You'll find the ZIP files in D:\home\data\SitePackages . They're timestamped so it should be easy enough to see which is the latest, but you can� Azure function guys have a little mess here :D and looks like tools and sdk are not fully in sync. So, the thing is you got a dependency on some dll: Microsoft.AspNetCore.Mvc.Abstractions, Version=2.0.2.0 But the actual host that runs the function is not in your project, but in here: C:\Users\<user>\AppData\Roaming pm ode_modules\azure-functions-core-tools\bin , and there you MUST have the I have found that Kudu is extremely useful in seeing what has been deployed to Azure. Navigate to your function in the Azure portal. The instructions here will help get to the kudu console. From there you can browse the files which have been deployed into your function's file system. If you add " , ExecutionContext context)" at the end of the function's run entry point, you can then get the folder which your function is running from with "var path = context.FunctionAppDirectory; PS apologies for any formatting I am editing this on my phone. Relative file paths don't work as expected in Azure Functions � Issue , Suppose you create an Azure function which opens a config file in the Seems to pop up very frequently as users don't find the current pattern intuitive. HttpTrigger' (Failed, Id=44ab374c-5429-44aa-a4d1-2cbbc1cf0b5a)� It’s been working great, but last night it failed. So how can you find out what went wrong with your Azure Function? In the Portal. Well, the easiest way is to navigate to your function app in the portal, select the function, and go to the Monitor tab. In here we see a nice breakdown of when the function ran, and how long it ran for: If you have some problems with AAD, these screenshots may help you. Client ID: Key: Please note that the Key value can only be copied when it is created, after which it will be hidden. Hope this helps you get started with AAD quickly. Runtime Exception in 1.0.13, Runtime Exception in 1.0.13 - "Could not find file function.json" #196 Azure. WebJobs.Host; namespace FunctionApp1 { public static class� Develop more efficiently with Functions, an event-driven serverless compute platform that can also solve complex orchestration problems. Build and debug locally without additional setup, deploy and operate at scale in the cloud, and integrate services using triggers and bindings. 1.0.11-1.0.12: Azure Function Host Fails to Initialize � Issue #745 , Could not find or load a specific file. (Exception from HRESULT: 0x80131621). System.Private.CoreLib: Could not load file or assembly 'Microsoft. I've written about how to serve a single HTML page or a single Swagger file with Azure Functions before. But it hasn't really been easy or even possible to serve an entire site with Azure Functions. With the release of a new feature called Azure Functions Proxies a couple of weeks ago, we can now create a pretty capable HTTP static file server using Azure Functions. # Azure Functions localsettings file local.settings.json If you couldn't tell by the name, Microsoft has intended for this local.settings.json file to be for local development purposes only. It is not intended to be committed to a source control repository and it is not intended to be deployed to an Azure environment.. - That's really useful, thank you. I am doing some reading into the AzureCredentialsFactory now. I've managed to find my tenant id (by going to Azure AD and then 'Default Directory', but how do I get the client and key? - @James87262 Sorry, I am not entirely sure, I'd start by looking here though. - @James87262 I took some screenshots, hoping to help you get started quickly.
http://thetopsites.net/article/59535993.shtml
CC-MAIN-2020-45
refinedweb
1,203
57.98
I was terrified by lambda functions when I first saw them in Python and assumed they were only for senior Pythonistas. In fact, beginner python tutorials praise the language’s intelligible syntax, but lambdas didn’t appear to be particularly user-friendly. Using them became less intimidating once I grasped the general syntax and looked at some easy use cases. A lambda function is similar to any other Python function in terms of syntax. However, it is defined without a name and is contained in a single line of code. A lambda function can be based be described as an anonymous function. Usually, it takes a varied count of arguments though it can only have one expression. Using Lambda in Python The syntax of a lambda function is as follows. For a given argument, a lambda function evaluates an expression. You provide a value (argument) to the function and then the operation (expression). Lambda must be the first keyword. The argument and the expression are separated by a full colon (:). - lambda argument(s): expression - After the expression is executed, the result is returned. Contrasting a normal Python Function and a Lambda Function The argument, a, is the argument in the example code below, and the expression a+a is the expression. # Normal python function def normalFunction(a): return a+a # Lambda function lambda a: a+a Example 1: We intend to add 50 to a given argument x and return the resultant result in this example. a = lambda x : x + 50 print(a(20)) Example 2: In this example, we multiply argument x with argument y and consequently return the results. a= lambda x, y: x * y print(x(10, 20)) Example 3: This example demonstrates using arguments x, y, and z to summarise and return the given results. lamb_val =lambda a, b, c : a + b+ c print(lamb_val(5, 6, 2)) Lambda functions, like def functions, accept any argument. - Keyword Arguments: In a function call, a keyword argument is an argument followed by an identifier (e.g., name=). Named Arguments: Example (lambda x, y=3, z=5: x*y*z)(7) Variable list of Arguments: Example (lambda x, y=3, z=5: x*y*z)(x=7) Variable list of keyword arguments: Example (lambda *args : sum(args))(3,5,7) - Non-keyword arguments (also called positional arguments): A non-keyword argument is not a keyword argument. (lambda x,y,z : x*y*z)(3,5,7) Why should you use a Lambda Function? The best use of a lambda function is using it as an anonymous function within another function. For instance, if your function needs one argument and the given argument is multiplied by a number, that is unknown. def newFunc(a): return lambda b : b * n Using the above function signature, we can create a function that doubles any number given as the argument. def newFunc(a): return lambda b : b * a double_val = newFunc(2) print(double_val(24)) Alternatively, you can use the exact definition of the function to come up with a function that quadruples the number provided as follows. def newFunc(a): return lambda b : b * a quadruple_val = newFunc(4) print(quadruple_val(3)) You can use the exact function definition in the same program to create both functions above to double and quadruple the provided value. def newFunc(a): return lambda b : b * a quadruple_val = newFunc(4) double_val = newFunc(2) print(double_val (5)) print(quadruple_val (5)) Let’s get into some details about what the Python community considers good and negative about lambda functions. Pros Suitable for straightforward, easy-to-understand logical procedures. It also improves the readability of the code. When you only need a function once, this is a good option. Cons They can only make one expression at a time. Multiple separate operations cannot be combined into a single lambda function. In a regular def function, operations that span more than one line are wrong, such as nested conditional operations. Use a named function instead if you need a minute or two to understand the code. In addition, it isn’t good because, unlike a typical def function, you can’t use a doc-string to explain all the inputs, operations, and outputs. When should Lambda not be used? In a production environment, you should never write sophisticated lambda functions. Decrypting your code will be extremely tough for coders who maintain it. If you frequently write sophisticated one-liner expressions, defining a proper function is a much better approach. Remember that simple code is always preferable to complex code as a recommended practice. Regular functions vs lambdas Lambdas, as previously stated, are essentially functions that don’t have an identification attached to them. In other words, they are anonymous functions (hence, anonymous). The following shows the differences between lambdas and standard functions in Python. lambda b : b + b regular function def (a) : return a + a - In the body of a lambda function, there can only be one expression. - The body of a regular function can contain several expressions and statements. - Lambdas don’t have a name attached to them. As a result, they’re sometimes referred to as anonymous functions. - A name and signature are required for regular functions. - Because the body is automatically returned, lambdas do not have a return statement. - A return statement should be included in functions that require returning a value. What are the differences? The main distinction between a lambda and a standard function is that the Lambda evaluates only one expression and returns a function object. Consequently, we may name the lambda function’s result and utilize it in our program, just as we did in the previous example. For the given an example, a regular function might look like this. def adder (x, y): return x + y print (adder (1, 2)) We must give the function a name that will return the result when we call it. A return statement isn’t used in a lambda function because it only has one expression, always returned by default. You don’t even need to assign a lambda because it can be called right away. When we employ lambdas with Python’s built-in functions, they become even more powerful. You may still be perplexed about how lambdas vary from a function that returns a single expression. There isn’t much of a difference at the interpreter level. The interpreter treats any lambda function you define in Python as a regular function, which may surprise you. When converted to bytecode, the two definitions are treated the same way by the python interpreter, as shown in the diagram. Because Python reserves the name lambda, you can’t use it, but any other function name will produce the same bytecode. When to use Lambda functions? Consider when lambda functions should be used. Note that lambda functions are frequently used with Python classes that accept a function as an argument, such as map() and filter(). The other name for these kinds of functions is Higher-order functions. scalar data It refers to when a lambda function is applied to a single value. (lambda y: y*6)(5) The function was created and then immediately executed in the code above. It is an example of an instantaneously invoked function expression or IIFE. Lists Filter() is a Python built-in library that only returns values that meet specific requirements. The syntax of this function is as follows. filter (function,iterable). Any sequence, such as a list, set, or series object, can be used as the iterable. The example below searches for even numbers in a list. The filter method returns a ‘Filter object,’ which must be encapsulated with a list to return the values. Example 1: list_vals = [1,2,3,4,5,6,7,8,9] filter(lambda x: x%2==0, list_vals) # output list(filter(lambda y: y%2==0, list_vals)) # output Example 2: ages = [13, 90, 17, 59, 21, 60, 5] adults = list(filter(lambda age: age>18, ages)) print(adults) Map() is a built-in Python library that has the following syntax: map (function, iterable) It produces a modified list in which a function has changed each value in the original list. Every integer in the list is quadrupled in the example below. list_vals = [1,2,3,4,5,6,7,8,9] quad_vals = map(lambda y: pow(y,4), list_vals) list(quad_vals) lambdas in reduce() Reduce is similar to map() in that it applies an operation to each element in a sequence. The reduce() method performs a repeating operation on the list’s pairs of elements. Reduce() will take the lambda function and the list as arguments. Its process, however, differs from that of the map. The reduce() method takes the following steps to compute an output: Step 1: Apply the defined operation to the sequence’s first two items. Step 2: Save the outcome Step 3) Use the recorded result and the next element in the sequence to complete the operation. Step 4) Continue until there are no more elements. It also has two additional parameters: A function that specifies the action to be taken. a series of events (any iterator like lists, tuples, etc.) Here’s an example of a program that returns the product of all the elements in a list. Example 1: from functools import reduce sequences = [3,4,5,6,7] product = reduce (lambda a, b: a*b, sequences) print(product) Example 2: Using lambda inside reduce from functools import reduce list1 = [1,2,3,4,5,6,7,8,9] sum = reduce((lambda x,y: x+y), list1) print(sum) Explanation of Code: Reduce from the functools module should be imported. Here, we create a sequences list, which has specific numbers. We make a variable called product to keep track of the reduced value. A lambda function executes each list item. As with the last result, it will yield the product of that number. The outcome of the reduction function should be printed. Lambda Functions for Conditional Statements Conditional statements, such as “if… else”, are likewise supported by Lambda functions. Lambda functions are powerful as a result of this. Let’s imagine we need to label people in the family dataframe as ‘Adult’ or ‘Child.’ We may do this by applying the lambda function to our dataframe: df['category']=df['age'].apply(lambda x: 'Adult' if x>=18 else 'Child') Lambda can be used to write higher-order functions Another function can be passed as an argument to a lambda function. Consider a nested lambda function, which is a lambda function inside another lambda function. # Define a lambda function that can take another lambda function (func1). high_order = lambda x, lmbfunc: x*lmbfunc(x) # The inner lambda function is defined when calling the high_order. high_order(10, lambda x : x*x) #> 1000 Python Lambda with Multiple Statements Multiple statements are not allowed in lambda functions, but we can build two lambda functions and then call the second lambda function as a parameter to the first function. Let’s use Lambda to discover the second maximum element. List = [[2,3,4],[1, 4, 16, 64],[3, 6, 9, 12]] # Sort each sublist sortList = lambda x: (sorted(i) for i in x) # Get the second largest element secondLargest = lambda x, f : [y[len(y)-2] for y in f(x)] res = secondLargest(List, sortList) print(res) We’ve constructed a lambda function that sorts each sublist of the given list in the example above. The second lambda function takes this list as an argument and returns the n-2 member from the sorted list, where n is the length of the sublist. series object A Series object is a data frame column, or, to put it another way, a succession of values with matching indices. Inside a Pandas dataframe, lambda functions can be used to alter values. Let’s make a dummy dataframe with family members. 'Name': ['Luke','Gina','Sam','Emma'], 'Status': ['Father', 'Mother', 'Son', 'Daughter'], 'Birthyear': [1976, 1984, 2013, 2016], }) Pandas’ Lambda with the Apply() function This function performs an operation on each column element. We deduct each member’s birth year from the current year to determine their current age. The expression 2021(current year) minus the value is used in the lambda function below. a refers to a value in the birthyear column, and the expression is 2021(current year) minus the value. df['age'] = df['Birthyear'].apply(lambda a: 2021-a) Lambda with Python’s Filter() function Python’s Filter() method can be used with Lambda. It accepts two arguments: one is a lambda function with a condition expression, and the other is iterable, a series object in our case. It gives you a list of values that meet the criteria. list(filter(lambda a: a>20, df['age'])) ###Output [45, 37] Lambda with Map() function by Pandas In the same way, as apply() alters the values of a column based on the expression, Map modifies the values of a column. # Double the age of everyone df['double_age'] = df['age'].map(lambda x: x*2) Lambda on Dataframe object Unless we wish to edit the entire data frame with a single expression, we usually utilize Lambda functions on specific columns (series objects) rather than the whole data frame. For example, if all values have to be rounded to one decimal place, all columns must be float or int datatypes because round() does not operate on strings. df2.apply(lambda x:round(x,1)) # Returns an error if some # columns are not numeric We apply it to a dataframe and select the columns to edit in the Lambda function in the example below. Note that we must use axis=1 to apply the equation column-by-column. # convert to lower-case df[['Name','Status']] =df.apply(lambda x: x[['Name','Status']].str.lower(), axis=1) scenarios that have been discouraged When a Lambda function is given a name The PEP8 python style standard discourages this since Lambda produces an anonymous function that isn’t meant to be stored. If you want to save the operation for later usage, use a regular def function instead. # sample bad application triple = lambda a: a*3 # sample good application def triple(a): return a*3 Another Example: import pandas as pd df = pd.DataFrame([[1,2,3],[4,5,6]],columns = ['First','Second','Third']) df['Forth']= df.apply(lambda row: row['First']row['Second'] row['Third'], axis=1) df Using Lambda functions to provide functions to other Lambda functions Using processes that only accept one number-argument, such as abs, is no longer essential with Lambda because you can feed the operation directly into map() or apply(). #Bad map(lambda y:abs(y), list_vals) #Good map(abs, list_vals) #Good map(lambda y: pow(y, 3), float_nums) Functions within lambda functions should, in theory, take two or more parameters. Pow(number,power) and round(number, ndigit) are two examples. You can try out different built-in Python functions to check which ones require Lambda functions in this situation. When numerous lines of code are more readable, avoid using Lambda functions. For instance, When you use if-else statements inside a lambda function. In this tutorial, we utilized the example below. # Conditional Lambda statement df['Gender'] = df['Status'].map(lambda x: 'Male' if x=='father' or x=='son' else 'Female') With the code below, you may get the same outcomes. It is our preferred method because you may have an infinite number of conditions, and the code is easy to understand. df['Gender'] ='' df.loc[(df['Status'] == 'father') | (df['Status'] =='son'), 'Gender'] ='Male' df.loc[(df['Status'] == 'mother') | (df['Status'] == 'daughter'), 'Gender']='Femele' Conclusion Many programmers who dislike Lambdas believe that more clear list comprehensions, built-in functions, and standard libraries can be used instead. Alternatives to the map() and filter() functions include generator expressions akin to list comprehensions. Whether or not you use Lambda functions in your code, you should know what they are and how they work because you will undoubtedly encounter them in other people’s code.
https://www.codeunderscored.com/how-to-use-lambda-in-python/
CC-MAIN-2022-21
refinedweb
2,671
54.02
This is your resource to discuss support topics with your peers, and learn from each other. 03-10-2012 10:50 AM Okay, so I switched from Momentics to QTCreator, following various howto's and such, just trying to deploy a simple hello world app, but when I run it on the device(not the simulator), I am getting this in my app log on the device : QBB: failed to open Locale pps, errno=13 QFontDatabase: Cannot find font directory /home/<username>/bbndk-2.0.0/Qt/stage/nto/armle-v7 Seems as though it's trying to find fonts, which of course there are none of the device(though it's referencing the paths on my local machine). Do I need to deploy them and set the path w/ an enviroment variable, or am I doing something wrong? Thank you, 03-10-2012 11:39 AM 03-10-2012 11:47 AM Blackberry's GIT... I think I may have gotten past that issue by adding : <env var="QT_QPA_FONTDIR" value="/usr/fonts/font_repository/liberation"/> into the bar-descriptor.xml.. Only thing I would LOVE to figure out now is how to be able to use the NDK as well as Qt in QtCreator... You can certainly use the creator to make the gui's and such, but I don't think you can still use NDK features, as it always says "include file not found.. "..Would love to be able to use some of the libraries and includes within Qt, but I don't think you can at this point add -L and -I to the compile scripts, and ever if you did, you will lose the sim, as it's looking for a N900, wrong architecture... Though I am atleast at a point that I can do something. Use QtCreator to set myself up, then from there, vi and the command line. haha... Just like the good old days. 03-10-2012 12:15 PM 03-10-2012 12:22 PM No I'm sorry I haven't... What was the title of the post? 03-10-2012 01:02 PM - edited 03-10-2012 01:04 PM It came up around here:- (The forum search feature was more helpful this time than I thought it would be...) 03-10-2012 02:03 PM ..... And I'm off.. haha.. git cloning now... Yea, I tried the search, but it's pretty painful.. I'm assuming that I am just going to clone this guy, then basically follow the instructions here : I did also do a build of RIMs qtcreator, so I will give that a whirl as well, see what I can do. I have successfully built and installed a few Qt Apps with not many issues, but as soon as I added anything from the standard NDK, all hell broke loose. Hopeing this somewhat fixes that. Thanks again for all your help again man, really appreciate it, 03-10-2012 03:36 PM 03-10-2012 04:17 PM Yup, just finished compiling and installing. Going to play now. I used your most recent configure line, so I should be good to go there. Thanks again, I'll be on IRC probably next week a little more.. Have a newborn baby that I like to spend time with on the weekends. 03-10-2012 04:45 PM It does the same thing, there isn't anyway that I can find in Qt Creator to be able to tell it that your including files that are outside ot Qt. Example, I am trying to include this : #include <bps/bps.h> #include <bps/audiomixer.h> #include <mm/renderer.h> And it basically says no. Not a big deal, as I can always just use QtCreator to create the UI, then take it out to compile and deploy/test. Just slows things down a bit.
https://supportforums.blackberry.com/t5/Native-Development/Qt-Creator-issue-with-fonts/m-p/1614421
CC-MAIN-2016-44
refinedweb
645
79.8
Mono-Readline 0.0.1 reviewDownload Mono-Readline is a simple little assembly for .Net (specifically Mono) that provides support for GNU Readline support within Mono app Mono-Readline is a simple little assembly for .Net (specifically Mono) that provides support for GNU Readline support within Mono applications. Mono-Readline project is based on the code of Martin Baulig in the Mono debugger. I just took it and made it all nice and autoconf/automake enabled. It's pretty straight forward, but here is a short sample program: using Mono.ReadLine; using System; using System.Reflection; public class Test { public static void Main(string[] args) { GnuReadLine readline = new GnuReadLine(); Console.WriteLine("Monkeys!"); string the_prompt = "This is a test: "; string result; while (true) { result = readline.ReadLine(the_prompt); if (result != null) { readline.AddHistory(result); } else { break; } } } } You should be able to compile this with mcs -r:mono.readline test.cs and get a little executable program that keeps going until you hit CTRL-D. There is lots of other fun you could do such as setting up continuation prompts and what not. Basically, most of this is ripped from Martin's code in the mono debugger. But wait, odds are you're going to get some funky error saying it can't find the package or something like that. If that's the case, make sure you have MONO_PATH="/usr/local/lib" set before running the program and compiling. For example to compile run: MONO_PATH="/usr/local/lib" mcs -r:mono.readline test.cs And then to run type: MONO_PATH="/usr/local/lib" mono test.exe I'm not a real Mono pro, but my hope is that this could possibly help someone else out. I'm thinking that in the future I may also include a patch for IronPython. As always, if you have comments or patches, please let me know. Mono-Readline 0.0.1 search tags
https://nixbit.com/software/mono-readline-review/
CC-MAIN-2021-17
refinedweb
317
67.25
I made this project for my Physics 308L class. It is not yet completed but the whole idea is here for anyone to replicate. You can create most of these parts from their cheaper components, but I chose to use pre-made parts like the DFrobot LCD shield for Arduino and accelerometers pre-soldered to boards. This project is a hand held g-meter that constantly outputs acceleration on a screen. It measures the acceleration along three axes (Linear and Lateral g as well a Vertical g), which can be changed between by pressing buttons. I am planning on using this device in many cars to measure acceleration, calculate real torque put to the wheels, and even estimate real brake horsepower. (It will just be an estimate because the main car I will be using does not have an ECU and therefore I cannot measure real engine RPM.) Here is a link to my Physics Lab Notebook with more details on what I did: Materials you will need: - Arduino Uno R3 Microcontroller - DFrobot LCD shield - MMA7361 Accelerometer (or any other accelerometer) - (Car/USB adapter) optional - Cable Step 1: Attach your DFrobot LCD shield to your arduino. (Or wire an LCD screen yourself to the microcontroller) Make sure it works by uploading the following sketch (code for Arduino): //Sample using LiquidCrystal library #include <LiquidCrystal.h> /******************************************************* This program was originally created by Mark Bramwell, July 2010 It was then changed for an accelerometer project by Brandon Middleton, April 2012 ********************************************************/ //("ACCELERATION:"); // print a simple message } void loop() { lcd.setCursor(0,1); // move to the begining of the second line lcd_key = read_LCD_buttons(); // read the buttons switch (lcd_key) // depending on which button was pushed, we perform an action { case btnRIGHT: { lcd.print("Y-AXIS:."); lcd.setCursor(8,1); // move cursor to second line "1" and 9 spaces over lcd.print(analogRead(A2)); // display number between 0-1023 corresponding to voltage lcd.setCursor(11,1); lcd.print("g"); delay(300); break; } case btnLEFT: { lcd.print("Y-AXIS:."); lcd.setCursor(8,1); // move cursor to second line "1" and 9 spaces over lcd.print(analogRead(A2)); lcd.setCursor(11,1); lcd.print("g"); delay(300); break; } case btnUP: { lcd.print("Z-AXIS:."); lcd.setCursor(8,1); // move cursor to second line "1" and 9 spaces over lcd.print(analogRead(A1)); lcd.setCursor(11,1); lcd.print("g"); delay(300); break; } case btnDOWN: { lcd.print("Z-AXIS:."); lcd.setCursor(8,1); // move cursor to second line "1" and 9 spaces over lcd.print(analogRead(A1) ); lcd.setCursor(11,1); lcd.print("g"); delay(300); break; } case btnSELECT: { lcd.print("PAUSE "); delay(300); break; } case btnNONE: { lcd.print("X-AXIS:."); lcd.setCursor(8,1); // move cursor to second line "1" and 8 spaces over lcd.print(analogRead(A3)); lcd.setCursor(11,1); lcd.print("g"); delay(300); break; } } } Step 2: Attach accelerometer to Arduino. This is the step I messed up twice! (note: most accelerometers can only be connected to 3.3V! Luckily there is a 3.3V source on the Arduino Uno r3.) To make the accelerometer more compact I wanted to solder wires directly to the board so I could easily connect them to the shield. Accelerometers easily overheat so only touch the soldering iron to the chip for 2 seconds max! I did not realize this and bought a cheap soldering iron which did not get hot at the tip. I had to touch it for long periods of time to solder the wires and I am sure this is what broke my accelerometer (ADXL330 and ADXL335). I now have ordered an even easier accelerometer: MMA7361 with cable attachments also from DFrobot. This works MUCH better because it has a 3.3V voltage regulator and female adapters that fit pins on the LCD shield. You also do not have to solder with this option. The other option is very bulky; you can wire the accelerometer on a breadboard to the Arduino. Outputs on Arduino: There are three rows of pins on the bottom of the LCD shield (each row has 5 pins) The top row, marked 5V are each 5V pins. The second row are all ground pins. The third and last row is marked S, but they are the Analog outputs of the Arduino. They start on the left with A1 and go through A5. (the A0 pin is used by the LCD shield) If you need the 3.3V source (for accelerometers without voltage regulators) it is located on the bottom of the shield as a hole. It is directly to the left of the 5V hole. If you are still unsure you can easily tell which one is the 3.3V by removing the shield and it is marked on the Arduino. If you have the MMA7361 attach each V to a 5V pin, each Gnd to a Ground pin and Z-axis to A1 pin Y-Axis to A2 and X-axis to A3. If you are using and ADXLxxx accelerometer connect Vs to 3.3V gnd to Ground Z-axis to A1 Y-Axis to A2 and X-axis to A3. Step 3: Make a box for your hand-held system. I made my box out of ultra-pro hard playing card cases and tape. First I cut out holes in my cases to let the buttons, pins and screen fit through. I made two of these and taped them together to make the face sturdier. I then cut the other five sides to the right size and taped two cases together per side to strengthen the box. This was my finished box: I also cut a hole for the charger: and these are the materials: Step 4: Fine tuning and Calibration. I have not had the chance to do this step yet because I have not yet received my latest accelerometer. Basically once you have your device reading the Voltages from the A1-A3 analog pins, you have to figure out what your output voltage is from the accelerometer when it measures no acceleration. The easiest way to do this is to chose one axis at a time and tilt the accelerometer so that axis is either straight up or straight down relative to the ground. Record those voltages and add them together then divide by 2. This is 0g acceleration for your accelerometer. Repeat for the other two axes. Now take the value when your accelerometer axis was pointing downwards towards the ground (this is 1g accelation) and subtract your zero g value. Take that and divide 1 by it. That is how many g's each value from (0-1023) the analogRead() function is. I will call this value num_per_g in the following code. Repeat for each axis. Lastly, in the code in replace analogRead() by: (analogRead() - (zero_g_val))*(num_per_g) This will be the fraction of g your accelerometer is measuring. This works because most accelerometers are ratiometric meaning they output voltages proportionally to the input voltage and the acceleration. I have not actually done all of this yet so there might be problems. One possible one is that you might need to use 'float' instead of 'int' in the code for decimals. Another problem that I'm not sure I understand yet is if the numbers 0-1023 will correspond to 5V nomatter what. This would reduce accuracy of accelerometer. This works because most accelerometers are ratiometric meaning they output voltages proportionally to the input voltage and the acceleration. (Notice that the numbers the LCD prints from analogRead() is a number between 0-1023. This corresponds to your input voltage (in most cases is 3.3V) with 0 being 0V and 1023 being 3.3V. It is a good idea to measure your voltage from your arduino pins for more accuracy. (my arduino 3.3V pin produced 3.210V) You do not really need to know the actual voltage though, most of the time you can use the 0-1023 value since the accelerometer is ratiometric anyway.) Step 5: Keep working on your accelerometer and enjoy! Here is a link to my Physics Lab Notebook for more details of what I did: [torque (low speeds) ~ acceleration(multiply decimal by 32.2ft/sec^2)*(car weight (lbs) * tire radius (ft))/(gear ratio*final drive ratio)] [HP = torque*(engine RPM)/5252] 2 Discussions 5 years ago on Introduction Very nicely done. I'm going to build this because it looks cool as hell and very useful. I'll be able to see how many G's I'm pulling when I take a curve at 80mph ;-) Thanks! 6 years ago on Introduction You are the first person for me to comment on instructables. The reason for the prestigious honor is I was quite impressed with your work. Very precise and logical explanation throughout. I will be keen to keep an eye on anything else you make. Cheers
https://www.instructables.com/id/Arduino-Car-g-Meter-Display/
CC-MAIN-2019-18
refinedweb
1,477
72.76
- Advertisement janosideMember Content Count147 Joined Last visited Community Reputation214 Neutral About janoside - RankMember w00t! Todo 3.0 beta is out! Get it while it's hot... janoside replied to Moe's topic in Your AnnouncementsLooks good. One feature suggestion I have is to allow sorting of tasks in the main window by all of the fields. Currently you have sorting by task name, details, and date (by clicking on the corresponding column header), and you should allow this for all fields. I see that you allow sorting by others through the "Tasks" menu, but that is difficult to use quickly. Skybox "popping" janoside replied to treeway's topic in Graphics and GPU ProgrammingThe shader is very simple and doesn't seem to have any glaring issues. I would make sure that you are passing the correct transformation information from your application. I strongly suspect this is the issue. mdx2 is it real or vapor? janoside replied to devronious's topic in Graphics and GPU ProgrammingLast time I tried to use it (before the December 06 DXSDK) MDX2 would throw a TimeBombException every time I tried to run my application. Needless to say that prompted me to move back to MDX1. I don't know if it will be supported in the future, but I wouldn't recommend starting to use it right now. MDX Replacing DrawSubset janoside posted a topic in Graphics and GPU ProgrammingIn order to perform instancing of Direct3D Meshes the way I want to, I'd like to replace the DrawSubset method with my custom implementation. I have looked through the forums and saw a couple of implementations which are very similar to what I have. Unfortunately, when I render my scene with this replacement implementation, none of the meshes are visible. I ran NVPerfHUD on the application and all of the draw calls are still being made (evidenced also by an identical framerate for either implementation). Does anyone have any idea why my custom implementation would result in nothing being rendered? My implementation: AttributeRange attribRange = mesh.GetAttributeTable()[id]; device.VertexFormat = mesh.VertexFormat; device.SetStreamSource(0, mesh.VertexBuffer, 0); device.Indices = mesh.IndexBuffer; device.DrawIndexedPrimitives( PrimitiveType.TriangleList, 0, attribRange.VertexStart, attribRange.VertexCount, 3 * attribRange.FaceStart, attribRange.FaceCount); Any ideas are appreciated. [.net] C# expression evaluation janoside replied to janoside's topic in General and Gameplay ProgrammingThanks [.net] C# expression evaluation janoside posted a topic in General and Gameplay ProgrammingAre standard C# compilers required to evaluate conditional expressions within an "if" from left to right? For example, is it possible for the following code segment to throw a NullReferenceException (because of the .ToString() call)? object x = null; if ( (x != null) && (x.ToString() == "string") ) { // do something } what can you tell me about this PhysX thing? janoside replied to adventchild's topic in Math and PhysicsSearch the forums. There's already a lot of discussion on the topic. [.net] C# sorting an array of strings janoside replied to unknownProdigy's topic in General and Gameplay ProgrammingCreate a custom IComparer<string> type. It should look something like this: public class StringLengthComparer : IComparer<string> { public int Compare(string s1, string s2) { if ( s1.Length > s2.Length ) { return -1; } else if ( s1.Length < s2.Length ) { return 1; } else { return 0; } } } (Sorry for the crappy formatting). Then, when you want to sort the array, call Array.Sort (a static method of System.Array) and pass it an instance of your StringLengthComparer. Another newbie in need of guidance. janoside replied to Savaroth's topic in For Beginners's ForumI haven't heard of or read that book, so I'm only qualified to answer the last question. The compiler that comes with VC# 2005 Express is good. There are not many C# compilers that I know of, the one made by Microsoft for a language they developed is sure to be good. Although I don't know about the book, I'm sure it will be of use if you have no experience. Hopefully it has some really basic tutorials that just help you run your first program. From there I recommend experimenting a lot. Change the code, see if it runs, what happens when it runs, etc. Try to work your way through the book as you experiment, and don't forget about these forums if something has you stuck. It can be confusing when you first start programming, but it can be a very fun and rewarding hobby. Good luck Please answer my questionnaire janoside replied to Valkyrie4896's topic in General and Gameplay ProgrammingSection A (For everyone) : 1. Have you ever heard of Python programming language? If yes, do you like it? Yes, I have used it a little and I do not like it. 2. Do you think it is possible/feasible to develop a 3D engine alone within 6 months? Depends on the scope/size of the engine and the performance requirements. 3. What do you think of game development hobbyists? Uhhh, I like them, I guess. I am one. Everyone here is one, and I generally like the people on GameDev. 4. Do you recommend developing a 3D engine for your own? Depends on your goals. I am doing it and I find it to be a very rewarding experience in terms of understanding the complexities of such a system. If you just want to get a game out the door, probably not. Section B (For those with 3D programming experience) 1. What is your programming language of choice for 3D programming? C# 2. What is your API of choice for 3D programming? DirectX 3. Have you created an open world environment to move around? Yes 4. how did you learn about 3D programming? Online research and trial and error. 5. Do you enjoy 3D programming? Very much. 6. Please list out any 3D Engine (that is not developed by your own) you used before. I have looked at OGRE, Axiom, and Irrlicht but not used any of them extensively. Section C (For those without 3D programming experience) 1. Are you interested in learning 3D programming? 2. Are you interested in learning Python programming language? [java] Applet Security Problem janoside replied to janoside's topic in General and Gameplay ProgrammingThanks bleb, that really helps. I didn't realize it was running on the user's computer. If anyone knows of a good demo showing an applet loading server-side files I would appreciate a link. Thanks [java] Applet Security Problem janoside posted a topic in General and Gameplay ProgrammingI'm new to Applets and I would like to make an applet that will allow visitors to my site to view a slideshow of images. I want the applet to load all image files that are in the same directory as the applet (on my server). How can I do it? I understand that applets have a lot of security implications, but it seems like I should be able to read a local file. Currently I am getting the following error message: java.security.AccessControlException: access denied (java.util.PropertyPermission user.dir read). Any help is appreciated. What do you think about my program? janoside replied to TriKri's topic in Graphics and GPU ProgrammingQuote:Well, then I don't understand why anyone ever would like to code in assembly! These days, most people wouldn't. Compilers have become very good at producing good low level compilations of high-level languages. As swiftcoder says, it's algorithmic improvements that will give meaningful performance gains. After all, you can only convert your program to assembly once. If the performance does not satisfy you then, what will you do? Point Sprite Sizing? janoside posted a topic in Graphics and GPU ProgrammingHow should I set the sizing parameters in DirectX to make particles size the same way as other three-dimensional objects (i.e. get bigger closer and smaller farther away)? I know what each of the three sizing parameters (A, B, and C) are supposed to do, but what are reasonable values for them? I have copied the values from several demos, but my particles never seem to size correctly with camera distance. Specifically, the particles become very small when the viewer is close to them, and quickly grow to a maximum size as the viewer moves away from them. I set the sizing parameters to the same values used in the CodeSampler point sprite demo. Any help is greayly apprecitated. [Edited by - janoside on April 20, 2006 4:52:27 PM] [.net] C# inheritance janoside replied to Calin's topic in General and Gameplay ProgrammingMark the base class's method "virtual". You can then mark the derived class's implementation as "override" and still call the base class implementation using "base.MethodName()". - Advertisement
https://www.gamedev.net/profile/77296-janoside/
CC-MAIN-2018-43
refinedweb
1,452
66.23
CGI::Utils - Utilities for retrieving information through the Common Gateway Interface use CGI::Utils; my $utils = CGI::Utils->new; my $fields = $utils->vars; # or $utils->Vars my $field1 = $$fields{field1}; or my $field1 = $utils->param('field1'); # File uploads my $file_handle = $utils->param('file0'); # or $$fields{file0}; my $file_name = "$file_handle"; This module can be used almost as a drop-in replacement for CGI.pm for those of you who do not use the HTML generating features of CGI.pm This module provides an object-oriented interface for retrieving information provided by the Common Gateway Interface, as well as url-encoding and decoding values, and parsing CGI parameters. For example, CGI has a utility for escaping HTML, but no public interface for url-encoding a value or for taking a hash of values and returning a url-encoded query string suitable for passing to a CGI script. This module does that, as well as provide methods for creating a self-referencing url, converting relative urls to absolute, adding CGI parameters to the end of a url, etc. Please see the METHODS section below for more detailed descriptions of functionality provided by this module. File uploads via the multipart/form-data encoding are supported. The parameter for the field name corresponding to the file is a file handle that, when evaluated in string context, returns the name of the file uploaded. To get the contents of the file, just read from the file handle. mod_perl is supported if a value for apache_request is passed to new(), or if the apache request object is available via Apache->request, or if running under HTML::Mason. See the documentation for the new() method for details. If not running in a mod_perl or CGI environment, @ARGV will be searched for key/value pairs in the format key1=val1 key2=val2 If all command-line arguments are in this format, the key/value pairs will be available as if they were passed via a CGI or mod_perl interface. Returns a new CGI::Utils object. Parameters are optional. CGI::Utils supports mod_perl if the Apache request object is passed as $params{apache_request}, or if it is available via Apache->request (or Apache2::RequestUtil->request), or if running under HTML::Mason. You may also pass max_post_size in %params. Returns the fully URL-encoded version of the given string. It does not convert space characters to '+' characters. Aliases: url_encode() Returns the fully URL-encoded version of the given string as unicode characters. It does not convert space characters to '+' characters. Aliases: url_unicode_encode() Returns the decoded version of the given URL-encoded string. Aliases: url_decode() Returns the decoded version of the given URL-encoded string, with unicode support. Aliases: url_unicode_decode() Takes a hash of name/value pairs and returns a fully URL-encoded query string suitable for passing in a URL. By default, uses the newer separator, a semicolon, as recommended by the W3C. If you pass in a second argument, it is used as the separator between key/value pairs. Aliases: url_encode_vars() Takes a URL-encoded query string, decodes it, and returns a reference to a hash of name/value pairs. For multivalued fields, the value is an array of values. If called in array context, it returns a reference to a hash of name/value pairs, and a reference to an array of field names in the order they appear in the query string. Aliases: url_decode_vars() Escapes the given text so that it is not interpreted as HTML. &, <, >, and " characters are escaped. Aliases: escape_html() Escapes the given text so that it is valid to put in a form field. Aliases: escape_html_form_value() Returns a url referencing top level directory in the current domain, e.g., Aliases: get_self_ref_host_url() Returns a url referencing the current script (without any query string). Aliases: get_self_ref_url Returns the current URI. Aliases: get_self_ref_uri() Returns a url referencing the current script along with any query string parameters passed via a GET method. Aliases: get_self_ref_url_with_query() Returns a url reference the current script along with the given hash of parameters added onto the end of url as a query string. If the optional $sep parameter is passed, it is used as the parameter separator instead of ';', unless the URL already contains '&' chars, in which case it will use '&' for the separator. Aliases: get_self_ref_url_with_params() Returns a url referencing the directory part of the current url. Aliases: get_self_ref_url_dir() Converts a relative URL to an absolute one based on the current URL, then adds the parameters in the given hash $params as a query string. If the optional $sep parameter is passed, it is used as the parameter separator instead of ';', unless the URL already contains '&' chars, in which case it will use '&' for the separator. Aliases: convertRelativeUrlWithArgs(), convert_relative_url_with_params(), convert_relative_url_with_args() Takes a url and reference to a hash of parameters to be added onto the url as a query string and returns a url with those parameters. It checks whether or not the url already contains a query string and modifies it accordingly. If you want to add a multivalued parameter, pass it as a reference to an array containing all the values. If the optional $sep parameter is passed, it is used as the parameter separator instead of ';', unless the URL already contains '&' chars, in which case it will use '&' for the separator. Aliases: add_params_to_url() Parses the cookies passed to the server. Returns a hash of key/value pairs representing the cookie names and values. Aliases: get_parsed_cookies Returns the CGI parameter with name $name. If called in array context, it returns an array. In scalar context, it returns an array reference for multivalued fields, and a scalar for single-valued fields. Also Vars() to be compatible with CGI.pm. Returns a reference to a tied hash containing key/value pairs corresponding to each CGI parameter. For multivalued fields, the value is an array ref, with each element being one of the values. If you pass in a value for the delimiter, multivalued fields will be returned as a string of values delimited by the delimiter you passed in. Aliases: vars(), Vars(), get_args(), args() # Other information provided by the CGI environment Returns additional virtual path information from the URL (if any) after your script. Returns the dotted decimal representation of the remote client's IP address. Returns the name of the remote host, or its IP address if the name is unavailable. Returns the name of the host in the URL being accessed. This is sent as the Host header by the web browser. Returns the referring URL. Returns the protocol, i.e., http or https. Returns the request method, i.e., GET, POST, HEAD, or PUT. Returns the content type. Returns the physical path information if provided in the CGI environment. Returns a query string created from the current parameters. Generates HTTP headers. Standard arguments are content_type, cookie, target, expires, and charset. These should be passed as name/value pairs. If only one argument is passed, it is assumed to be the 'content_type' argument. If no values are passed, the content type is assumed to be 'text/html'. The charset defaults to ISO-8859-1. A hash reference can also be passed. E.g., print $cgi_obj->getHeader({ content_type => 'text/html', expires => '+3d' }); The names 'content-type', and 'type' are aliases for 'content_type'. The arguments may also be passed CGI.pm style with a '-' in front, e.g. print $cgi_obj->getHeader( -content_type => 'text/html', -expires => '+3d' ); Cookies may be passed with the 'cookies' key either as a string, a hash ref, or as a CGI::Cookies object, e.g. my $cookie = { name => 'my_cookie', value => 'cookie_val' }; print $cgi_obj->getHeader(cookies => $cookie); You may also pass an array of cookies, e.g., print $cgi_obj->getHeader(cookies => [ $cookie1, $cookie2 ]); Aliases: header(), get_header Like getHeader() above, except sends it. Under mod_perl, this sends the header(s) via the Apache request object. In a CGI environment, this prints the header(s) to STDOUT. Aliases: send_header() Returns the header required to do a redirect. This method also accepts named arguments, e.g., print $cgi_obj->getRedirect(url => $url, status => 302, cookie => \%cookie_params); You may also pass a cookies argument as in getHeader(). Aliases: redirect() Like getRedirect(), but in a CGI environment the output is sent to STDOUT, and in a mod_perl environment, the appropriate headers are set. The return value is 1 for a CGI environment when successful, and Apache::Constants::REDIRECT in a mod_perl environment, so you can do something like return $utils->sendRedirect($url) n a mod_perl handler. Aliases: send_redirect() Like getRedirect(), except that the redirect URL is converted from relative to absolute, including the host. Returns a string to pass as the value of a 'Set-Cookie' header. Returns a string to pass as the 'Set-Cookie' header(s), including the line ending(s). Also accepts a simple hash with key/value pairs. Sets the cookie generated by getCookieString. That is, in a mod_perl environment, it adds an outgoing header to set the cookie. In a CGI environment, it prints the value of getSetCookieString to STDOUT (including the end-of-line sequence). Returns a reference to a hash containing the header information sent along with a file upload. Shortcut methods are provided for returning Apache constants under mod_perl. The methods figure out if they are running under mod_perl 1 or 2 and make the appropriate call to get the right constant back, e.g., Apache::Constants::OK() versus Apache::OK(). The methods are created on the fly using AUTOLOAD. The method names are in the format apache_$name where $name is the lowercased constant name, e.g., $utils->apache_ok, $utils->apache_forbidden. See for a list of constants available. You can export methods into your namespace in the usual way. All of the util methods are available for export, e.g., getSelfRefUrl(), addParamsToUrl(), etc. Beware, however, that these methods expect to be called as methods. You can also use the tag :all_utils to import all of the util methods into your namespace. This allows for incorporating these methods into your class without having to inherit from CGI::Utils. Other people who have contributed ideas and/or code for this module: Kevin Wilson Don Owens <don@regexguy.com> All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. 0.12
http://search.cpan.org/~dowens/CGI-Utils-0.12/lib/CGI/Utils.pm
CC-MAIN-2016-26
refinedweb
1,713
56.45
How to Create a Vocabulary for NLP Tasks in Python This post will walkthrough a Python implementation of a vocabulary class for storing processed text data and related metadata in a manner useful for subsequently performing NLP tasks. When performing a natural language processing task, our text data transformation proceeds more or less in this manner: raw text corpus → processed text → tokenized text → corpus vocabulary → text representation Keep in mind that this all happens prior to the actual NLP task even beginning. The corpus vocabulary is a holding area for processed text before it is transformed into some representation for the impending task, be it classification, or language modeling, or something else. The vocabulary serves a few primary purposes: - help in the preprocessing of the corpus text - serve as storage location in memory for processed text corpus - collect and store metadata about the corpus - allow for pre-task munging, exploration, and experimentation The vocabulary serves a few related purposes and can be thought of in a few different ways, but the main takeaway is that, once a corpus has made its way to the vocabulary, the text has been processed and any relevant metadata should be collected and stored. This post will take a step by step look at a Python implementation of a useful vocabulary class, showing what is happening in the code, why we are doing what we are doing, and some sample usage. We will start with some code from this PyTorch tutorial, and will make a few modifications as we go. Though this won't be terribly programming heavy, if you are wholly unfamiliar with Python object oriented programming, I recommend you first look here. The first thing to do is to create values for our start of sentence, end of sentence, and sentence padding special tokens. When we tokenize text (split text into its atomic constituent pieces), we need special tokens to delineate both the beginning and end of a sentence, as well as to pad sentence (or some other text chunk) storage structures when sentences are shorter then the maximum allowable space. More on this later. PAD_token = 0 # Used for padding short sentences SOS_token = 1 # Start-of-sentence token EOS_token = 2 # End-of-sentence token What the above states is that our stat of sentence token (literally 'SOS', below) will take index spot '1' in our token lookup table once we make it. Likewise, end of sentence ('EOS') will take index spot '2', while the sentence padding token ('PAD') will take index spot '0'. The next thing we will do is create a constructor for our Vocabulary class: def __init__(self, name): self.name = name self.word2index = {} self.word2count = {} self.index2word = {PAD_token: "PAD", SOS_token: "SOS", EOS_token: "EOS"} self.num_words = 3 self.num_sentences = 0 self.longest_sentence = 0 The first line is our __init__() declaration, which requires 'self' as its first parameter (again, see this link), and takes a Vocabulary 'name' as its second. Line by line, here's what the object variable initializations are doing self.name = name→ this is instantiated to the name passed to the constructor, as something by which to refer to our Vocabulary object self.word2index = {}→ a dictionary to hold word token to corresponding word index values, eventually in the form of 'the': 7, for example self.word2count = {}→ a dictionary to hold individual word counts (tokens, actually) in the corpus self.index2word = {PAD_token: "PAD", SOS_token: "SOS", EOS_token: "EOS"}→ a dictionary holding the reverse of word2index(word index keys to word token values); special tokens added right away self.num_words = 3→ this will be a count of the number of words (tokens, actually) in the corpus self.num_sentences = 0→ this will be a count of the number of sentences (text chunks of any indiscriminate length, actually) in the corpus self.longest_sentence = 0→ this will be the length of the longest corpus sentence by number of tokens From the above, you should be able to see what metadata about our corpus we are concerned with at this point. Try and think of some additional corpus-related data you might want to keep track of, which we are not. Since we have defined that metadata which we are interested in collecting and storing, we can move on to performing the work to do so. A basic unit of work we will need to do to fill up our vocabulary is to add words to it. def add_word(self, word): if word not in self.word2index: # First entry of word into vocabulary self.word2index[word] = self.num_words self.word2count[word] = 1 self.index2word[self.num_words] = word self.num_words += 1 else: # Word exists; increase word count self.word2count[word] += 1 As you can see, there are 2 scenarios we can encounter when trying to add a word token to our vocabulary; either it does not already exists in the vocabulary ( if word not in self.word2index:) or it does ( else:). If the word does not exist in our vocabulary, we want to add it to our word2index dict, instantiate our count of that word to 1, add the index of the word (the next available number in the counter) to the index2word dict, and increment our overall word count by 1. On the other hand, if the word already exists in the vocabulary, simply increment the counter for that word by 1. How are we going to add words to the vocabulary? We will do so by feeding sentences in and tokenizing them as well go, processing the resulting tokens one by one. Note, again, that these need not be sentences, and naming these 2 functions add_token and add_chunk may be more appropriate than add_word and add_sentence, respectively. We will leave the renaming for another day. def add_sentence(self, sentence): sentence_len = 0 for word in sentence.split(' '): sentence_len += 1 self.add_word(word) if sentence_len > self.longest_sentence: # This is the longest sentence self.longest_sentence = sentence_len # Count the number of sentences self.num_sentences += 1 This function takes a chunk of text, a single string, and splits it on whitespace for tokenization purposes. This is not robust tokenization, and is not good practice, but will suffice for our purposes at the moment. We will revisit this in a follow-up post and build a better approach to tokenization into our vocabulary class. In the meantime, you can read more on text data preprocessing here and here. After splitting our sentence on whitespace, we then increment our sentence length counter by one for each word we pass to the add_word function for processing and addition to our vocabulary (see above). We then check to see if this sentence is longer than other sentences we have processed; if it is, we make note. We also increment our count of corpus sentences we have added to the vocabulary thus far. We will then add a pair of helper functions to help us more easily access 2 of our most important lookup tables: def to_word(self, index): return self.index2word[index] def to_index(self, word): return self.word2index[word] The first of these functions performs the index to word lookup in the appropriate dictionary for a given index; the other performs the reverse lookup for a given word. This is essential functionality, as once we get our processed text into the vocabulary object, we will want to get it back out at some point, as well as perform lookups and reference metadata. These 2 functions will be handy for much of this. Putting this all together, we get the following. Let's see how this works. First, let's create an empty vocabulary object: voc = Vocabulary('test') print(voc) <__main__.Vocabulary object at 0x7f80a071c470> Then we create a simple corpus: corpus = ['This is the first sentence.', 'This is the second.', 'There is no sentence in this corpus longer than this one.', 'My dog is named Patrick.'] print(corpus) ['This is the first sentence.', 'This is the second.', 'There is no sentence in this corpus longer than this one.', 'My dog is named Patrick.'] Let's loop through the sentences in our corpus and add the words in each to our vocabulary. Remember that add_sentence makes calls to add_word: for sent in corpus: voc.add_sentence(sent) Now let's test what we've done: print('Token 4 corresponds to token:', voc.to_word(4)) print('Token "this" corresponds to index:', voc.to_index('this')) This is the output, which seems to work well. Token 4 corresponds to token: is Token "this" corresponds to index: 13 Since our corpus is so small, let's print out the entire vocabulary of tokens. Note that since we have not yet implemented any sort of useful tokenization beyond splitting on white space, we have some tokens with capitlized first letters, and others with trailing punctuation. Again, we will deal with this more appropriately in a follow-up. for word in range(voc.num_words): print(voc.to_word(word)) PAD SOS EOS This is the first sentence. second. There no sentence in this corpus longer than one. My dog named Patrick. Let's create and print out lists of corresponding tokens and indexes of a particular sentence. Note this time that we have not yet trimmed the vocabulary, nor have we added padding or used the SOS or EOS tokens. We add this to the list of items to take care of next time. sent_tkns = [] sent_idxs = [] for word in corpus[3].split(' '): sent_tkns.append(word) sent_idxs.append(voc.to_index(word)) print(sent_tkns) print(sent_idxs) ['My', 'dog', 'is', 'named', 'Patrick.'] [18, 19, 4, 20, 21] And there you go. It seems that, even with our numerous noted shortcomings, we have a vocabulary that might end up being useful, given that it exhibits much of the core necessary functionality which would make it eventually useful. A review of the items we must take care of next time include: - perform normalization of our text data (force all to lowercase, deal with punctuation, etc.) - properly tokenize chunks of text - make use of SOS, EOS, and PAD tokens - trim our vocabulary (minimum number of token occurrences before stored permanently in our vocabulary) Next time we will implement this functionality, and test our Python vocabulary implementation on a more robust corpus. We will then move data from our vocabulary object into a useful data representation for NLP tasks. Finally, we will get to performing an NLP task on the data we have gone to the trouble of so aptly preparing. Related: - Data Representation for Natural Language Processing Tasks - The Main Approaches to Natural Language Processing Tasks - A Framework for Approaching Textual Data Science Tasks
https://www.kdnuggets.com/2019/11/create-vocabulary-nlp-tasks-python.html
CC-MAIN-2022-40
refinedweb
1,756
61.87