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
>>>>> "Eugen" == Eugen Leitl <eugen@leitl.org> writes: >> If you are saying that you will allocate /80s to each vserver, >> but actually they will not be layer-2 isolated from each other, >> this is just an administrative partition, then I think it's a >> good idea. Eugen> The Linux vserver patch is a very lightweight Eugen> virtualization. It doesn't share the network stack, shares Eugen> the physical NIC MAC and only recently were the vserver Eugen> guests given 127.0.0.1 that is distinct from the host's Eugen> localhost -- as far as I known ::1 hasn't been given that Eugen> treatment yet. Yes, I know it well, because it added lots of namespace arguments inside the kernel to lots of network code (like IPsec). The list of IP addresses is per-vserver, but the list of interfaces is not. Do the containers share the same mac address? I think so, right? Or do you have a virtual interface adapter per vserver with a fake mac address? Eugen> How much autoconfig do I need? Each physical host will be Eugen> given a private /64 (out of the /56 I have total), just the Eugen> guests will be given an /80, allocated from a different /64. I think you can just give out a seperate /80, and since you won't care about privacy extensions for a link that nobody can see or use, you leave them off, and arrange for bit 6 to always be 0. Allocate your /80s out of the prefix:0000::/71. Is 512 vservers per physical host enough? Eugen> I'm not really familiar with IPv6 advanced uses, at the Eugen> moment I'm treating it just like a bigger version of IPv4, at Eugen> least as far as guests are concerned. I don't really know Eugen> what users would want to run on their own /80s If I had such a system, I'd want to put each of my HTTP 1.1 virtual hosts on a seperate IPv6 address, assuming that I didn't have seperate vservers already. Why? Because it sure makes it easier to host different sensitivities of content (adult vs child friendly). I'd want the mail, pop3, imap, ftp, and ssh targets to be different, because that would like me move them around as it might make sense. And of course, SSL port 443 (and IMAPS, and SMTPS and...) can now have sensible CNs that match the name in DNS. >> Permitting autoconfig to work seems like a nice thing to retain. Eugen> If the guests can all use the host's (different) /64, will Eugen> that work? I think that you just want autoconfig to work well enough so that if you install a new machine in the rack, it can autoconfig up an address easily, and you can finish the install via ssh :-) -- ].
https://lists.debian.org/debian-ipv6/2011/05/msg00040.html
CC-MAIN-2017-26
refinedweb
477
69.92
UDL: /* block comment in one line, error */ @Eko-palypse There were 2 problems. “\Notepad++\plugins\PythonScript.dll” instead of “\Notepad++\plugins\PythonScript\PythonScript.dll”. Wrong path packed in “PythonScript_Full_1.0.8.0.7z”. PythonScript is 32-bit and I had npp 64-bit. Solved. @Meta-Chuh I have saved the script under \Notepad++\plugins\Config\PythonScript\scripts. Initialization placed on ATSTARTUP. Click the script in the menu. Nothing. No red color to see. I have to learn python. self.lexer_name = ‘DSM_Sprache_gk_1902’ does not work too. This is the name of the imported language file. The configured toolbar icon is not displayed. Even the preview in “Toolbar Icons” is empty. With activated console and call from the menu Traceback (most recent call last): File "D:\Daten\PortableApps\Notepad++\plugins\Config\PythonScript\scripts\DSM_block-comment.py", line 10, in <module> EnhanceUDLLexer().main() File "D:\Daten\PortableApps\Notepad++\plugins\Config\PythonScript\scripts\DSM_block-comment.py", line 24, in __call__ cls._instance = super(SingletonEnhanceUDLLexer, cls).__call__(*args, **kwargs) File "D:\Daten\PortableApps\Notepad++\plugins\Config\PythonScript\scripts\DSM_block-comment.py", line 117, in __init__ self.configure() File "D:\Daten\PortableApps\Notepad++\plugins\Config\PythonScript\scripts\DSM_block-comment.py", line 70, in configure editor1.indicSetStyle(0, INDICATORSTYLE.TEXTFORE) AttributeError: type object 'INDICATORSTYLE' has no attribute 'TEXTFORE' And in PythonScript 1.0.8.0 documentation is missing TEXTFORE at INDICATORSTYLE @Gerald-Kirchner said: PythonScript_Full_1.0.8.0.7 overlooked this one, current version is 1.3 error is most probably related to not having the current version installed. I go to NPP -> ? -> Get More Plugins -> -> Python Script -> Latest Version 1.0.8.0 No indication for newer versions. Please change the link to the newer version. Now with v1.3.0 Traceback (most recent call last): File "D:\Daten\PortableApps\Notepad++\plugins\Config\PythonScript\scripts\DSM_block-comment.py", line 4, in <module> import ctypes ImportError: No module named ctypes May I ask you which PythonScript package you installed? - Eko palypse last edited by Eko palypse It looks like the minimum package does not contain the ctypes module. I would propose to install the full package. hi @Gerald-Kirchner @Eko-palypse @PeterJones and all, sorry i was offline for a while. here is the correct guide to install the latest 1.3.0.0 pythonscript on notepad++ according to your last debug info: download and extract PythonScript_Full_1.3.0.0_x64.zip from >>> here <<< (do not use any other release type except this zip). copy PythonScript.dll from the plugins folder of this zip to: D:\Daten\PortableApps\Notepad++\plugins\PythonScript\PythonScript.dll copy python27.dll to: D:\Daten\PortableApps\Notepad++\python27.dll copy the folders scriptscontaining machine level scripts and libcontaining python libraries, from the zip’s plugins\PythonScript folder to: D:\Daten\PortableApps\Notepad++\plugins\PythonScript\lib\ D:\Daten\PortableApps\Notepad++\plugins\PythonScript\scripts\ note: for a pythonscript installation guide on your installed notepad++ version, i would need another debug info of it, as it has to be adapted acordingly. PythonScript_Min_1.3.0.0 changed to PythonScript_Full_1.3.0.0. I stay at 32-bit first. (Also in PythonScript_Full_1.3.0.0_x64.zip the PythonScript.dll is in the wrong folder.) Now it works for manual execution. Is there a way to automate that? “import DSM_block-comment” in startup.py not working It also does not work if I write the complete code to the end of startup.py (Initialization placed on ATSTARTUP). one more thing that might be helpful to you: to edit startup.py or any other script from the gui, instead of searching for it in an explorer window: go to plugins > python script > scriptsand hold [ctrl] while clicking on a script. Also in PythonScript_Full_1.3.0.0_x64.zip the PythonScript.dll is in the wrong folder. yes, all pythonscript releases have the wrong (old) folders. that’s why we copy the files manually to their correct locations. Now it works for manual execution. Is there a way to automate that? i’m glad you’ve managed to get it running as an extra user script. i’ll have a look at why the auto startup does not work. Now it works for manual execution. Is there a way to automate that? “import DSM_block-comment” in startup.py not working It also does not work if I write the complete code to the end of startup.py (Initialization placed on ATSTARTUP). i’ve noticed, that 1.3.0.0 has startup.py disabled by default. please go to plugins > python script > configurationand recheck initialisationto ATSTARTUPinstead of LAZY. (you have already done that, but just make sure) after you have done that, the script should work immediately on notepad++ startup, when added eg. below the last line of the original startup.py script, as you have correctly done before, unless startup.py itself is not visible at the plugins > python script > scriptsdropdown menu. we then have to recheck where it has been copied to. easy way to check if startup works: paste : print "hello world" below the line: sys.stdout = console of a default startup.py. the text hello world should be visible when you open the python script console. I recommend creating a new startup.py via the python script plugin menu New Script instead of using the default one, simply because the default one gets overwritten when a new version of python script gets installed. I had to rename because “-” resulted in an error in the file name. In \Notepad++\plugins\Config\PythonScript\scripts\startup.py import DSM4COMblockComment and then in DSM4COMblockComment.py start the line print "hello DSM4COMblockComment" to. It is visible in console. Now, the coloring does not work manually anymore. After removing the print, works it. That would be done. Now I have to find a way to distribute this solution to my colleagues. But that is a new topic. Solved.
https://community.notepad-plus-plus.org/topic/17084/udl-block-comment-in-one-line-error/22
CC-MAIN-2019-51
refinedweb
972
54.18
If you have been using Visual Studio for a while you may have some experience with Code Snippets. If you are not familiar with Code Snippets, it’s when you type a predetermined short cut and use tab to auto complete a more complex code structure. For instance if you are in a JavaScript file in Visual Studio and type try and press tab Visual Studio will auto complete a try catch for you. Typing try and pressing tab in a JavaScript File You can also use Code Snippets by using the right click context menu and selecting Insert Snippet... or Surround With... Right Click Context Menu Insert Snippet... Now with this basic understanding of Code Snippets you could look thought the options in the context menu to learn what treasures lay buried behind your right click and learn the short cuts to those treasures. Hint: the shortcut is the name of the snippet in the context menu. But the Title Said Creating And so it did. I haven’t found a built in way to create new Snippets. There is a Menu that can be accessed under Tools called the Code Snippet Manager... Access the Code Snippet Manager In the Code Snippet Manager you can select a language from the drop down and see a list of available snippets that can be used. If you select a snippet it gives you greater details such as a description the short cut and the type of snippet it is. Code Snippet Manager There are even buttons to Add.. and Import... more snippets. Unfortunately bot the add and import implies you already have snippets ready and there is no button for Create so how do we make a new snippet? Enter the XML To create a new Code Snippet you will need to create a new XML file with a file extension of .snippet. The following expert will get you started with the bare minimum of a code snippet that you can use your Insert Snippet... context menu to find. Very Basic Code Snippet <?xml version="1.0" encoding="utf-8"?> <CodeSnippets xmlns=""> <CodeSnippet Format="1.0.0"> <Header> <Title></Title> </Header> <Snippet> <Code Language=""> <![CDATA[]]> </Code> </Snippet> </CodeSnippet> </CodeSnippets> In the Title node you add the name of your snippet, for this demo I will call it hello. On the Code node’s Language attribute you enter the Language you are creating a snippet for, in this case I will enter JavaScript. In the CDATA[] brackets you add what you want inserted, so I will add a console.log('hello');. In the Header node I will also add a Shortcut node with the value of hello so we can access our snippet by typing our shortcut, hello, and pressing tab. It should now look like this: hello Snippet <?xml version="1.0" encoding="utf-8"?> <CodeSnippets xmlns=""> <CodeSnippet Format="1.0.0"> <Header> <Title>hello</Title> <Shortcut>hello</Shortcut> </Header> <Snippet> <Code Language="JavaScript"> <![CDATA[console.log('hello');]]> </Code> </Snippet> </CodeSnippet> </CodeSnippets> Now in a JavaScript file I should be able to insert my snippet snippet by typing our shortcut, hello, and pressing tab. Like so: Custom Snippet in Action You can create Code Snippets for VB, CSharp, CPP, XML, JavaScript, SQL, and HTML. And more information, like what other Header nodes can be used, about Code Snippets can be found on the MSDN.
https://wipdeveloper.com/creating-code-snippets-in-visual-studio/
CC-MAIN-2019-39
refinedweb
563
70.84
I am trying to write a simple program where the user enters a number and the computer tries to guess it. I wanted to make it a bit smarter, so that the program knows if its guess it higher or lower than what the users number are, and make the next guess with using that information But it dont work. Could someone please help me out a bit? ThanksThanksCode:#include <iostream> #include <cstdlib> #include <ctime> using namespace std; int main() { int myRandNo; int compNo = 50; int randNo = 0; cout << "Welcome to the guessing game" << endl; cout << "Please enter a number between 1 and 100: "; cin >> myRandNo; while (compNo != myRandNo) { //seed the rand srand(time(0)); //guess was to low if (compNo < myRandNo) { randNo = rand(); compNo = (randNo % 100) + currentGuess; //cout << compNo << "CompNo is smallest" << endl; } //guess was to high if (compNo > myRandNo) { randNo = rand(); compNo = (randNo % currentGuess) + 1; //cout <<compNo << "CompNo is biggest" << endl; } //cout <<"wrong" << endl; } cout <<"right"; system("pause"); return 0; }
https://cboard.cprogramming.com/cplusplus-programming/84977-guess-my-number-game-simple-ai.html
CC-MAIN-2017-51
refinedweb
162
56.32
class Standard collides with wpf namespace Standard In PresentationFramework from .NET 4.5 a namespace called Standard has been added. Admittedly, there might not be too many out there using occt from c++/cli (or are there?), but for those which do and also use the PF, this will clash with the class Standard in the global namespace from occt. Looking at the occt roadmap, this certainly is not the most important issue but in the long term i think the project would benefit if all very common names, no matter if they are types, macros or namespaces, would be refactored to become more unique. In the special case of the class Standard, i tried this to see how complex it is and it turns out moving it in a namespace called opencascade and changing about 100 places (including help) where this is directly used took me about 10 minutes (excluding compilation and tests). I'm aware that such a change would probably require many users to change their code as well, but putting a using namespace opencascade in some global header(s) would solve that hackishly and global replace also wouldn't take too long. I would be happy to post my changes to but hope to get some opinions first. Re: class Standard collides with wpf namespace Standard I don't think that renaming something in OCCT is a good idea to workaround name collisions with .NET. In such a way OCCT should rename a plenty of other APIs - you may find that standard system headers for WinAPI and XLib already define many common names as macros introducing weird collisions. Renaming everything that collides might be too painful and unreasonable. I haven't worked on this issue, but I believe there should be other ways to workaround collisions, which should be tried first, before affecting OCCT C++ source code.
https://dev.opencascade.org/index.php?q=node/1210
CC-MAIN-2020-45
refinedweb
311
62.72
: Awhile back I posted about not being able to get the perspective effect working on my openSUSE 10.2 system. No one replied back to me. Probably because it didn't look like an easy fix or perhaps I'm the only opneSUSE user. Anyway, I stumbled across a post somewhere on the Internet and turned up a repo specifically for openSUSE 10.2 users with the required packages to get the perspective effect to work. This is the error that I was getting when trying to use the perspective effect with python-numpy, blas, and lapack that was installed on my system: File “”, line 1, in File “/usr/lib/python2.5/site-packages/numpy/__init__.py”, line 43, in import linalg File “/usr/lib/python2.5/site-packages/numpy/linalg/__init__.py”, line 4, in from linalg import * File “/usr/lib/python2.5/site-packages/numpy/linalg/linalg.py”, line 25, in from numpy.linalg import lapack_lite ImportError: /usr/lib/libblas.so.3: undefined symbol: _gfortran_st_write_done Here’s the issue: ).” This was posted by a fellow name “David”. This guy has a repo with blas, lapack, and numpy specifically for openSUSE 10.2 users. Here is his repository: Anyway, I installed his packages and now perspective works in Inkacape v0.45-1. I don’t know who “David” is but he has been a life saver for me. I just wanted to pass along this information in case other opneSUSE users are having trouble. heathenx I agree to receive quotes, newsletters and other information from sourceforge.net and its partners regarding IT services and products. I understand that I can withdraw my consent at any time. Please refer to our Privacy Policy or Contact Us for more details
https://sourceforge.net/p/inkscape/mailman/inkscape-user/thread/46DAC564.3040004@gmail.com/
CC-MAIN-2017-17
refinedweb
289
67.35
This post is a complete guide to the SIM900 GSM GPRS Shield with the Arduino. Learn how to send and receive SMS and how to make and receive phone calls with Arduino. In this guide we’ll cover: - Introducing the SIM900 GSM GPRS Shield - SIM900 GSM GPRS Shield Hardware - SIM900 AT Commands - Testing the shield - Sending and receiving SMS – example - Making and answering phone calls – example Introducing the SIM900 GSM GPRS Shield The SIM900 GSM GPRS Shield is shown in figure below. GSM stands for Global System for Mobile Communications and is the global standard for mobile communications. GPRS stands for General Packet Radio Service. GPRS is a mobile service on the 2G and 3G cellular communication. Applications: The GSM GPRS shield is particularly useful as it allows to: - Connect to the Internet over GPRS network - Send and receive SMS - Place and receive phones calls Its capabilities make it perfect for projects with Arduino like: - Remote control of electronic appliances – sending an SMS to turn something on; - Receive notifications – send SMS to your cell phone if movement is detected in your house; - Receive sensor data – send periodic SMS to your cell phone with daily weather data. Features Here’s some of the most important features of the shield: - Compatible with Arduino and clones - Based on SIM900 module from SIMCOM - Allows you to send SMS, MMS, GPRS and Audio via UART using AT commands. - It has 12 GPIOs, 2 PWMs and buit-in ADC of the SIM900 module - Quad Band: 850; 900; 1800 and 1900 MHZ, so it should work in all countries with GSM (2G) networks - Control via AT commands - Supports RTC (real time clock) – it has a holder for a 3V CR1220 battery at the back - Has microphone and headphone jacks for phone calls Where to buy? You can check the SIM900 GSM GPRS shield on Maker Advisor and find the best price. You can use the preceding links or go directly to MakerAdvisor.com/tools to find all the parts for your projects at the best price! Preliminary steps Before getting started with your SIM900 GSM GPRS module, you need to consider some aspects about the SIM card and the shield power supply. GSM coverage Ensure you have coverage on a GSM 850 MHz, GSM 900 MHz, DCS 1800 MHz or PCS 1900 MHz network. By GSM we mean 2G. needed to go through: Settings > Advanced Settings > Security > SIM lock and turn off the lock sim card with pin. Getting the right power supply The shield has a DC socket for power as shown in figure below.. To power up the shield, it is advisable to use a 5V power supply that can provide 2A as the one shown below. It can also be powered with 9V 1A, or 12V 1A. You can find the right power adapter for this shield here. Make sure you select the model with 5V and 2A. SIM900 GSM GPRS Shield Hardware The figure below shows the back of the shield. It has a holder for the SIM card and for a 3V CR1220 battery for the RTC (real time clock). The figure below shows the shield most important components on the board that you need to pay attention to. Getting started 1) Insert the SIM card into the SIM card holder – make sure you’ve read the preliminary steps in the previous section.2) Make sure the antenna is well connected. 3) On the serial port select, make sure the jumper cap is connected as shown in figure below to use software serial. 4) Power the shield using an external 5V power supply. Make sure you select the external power source with the toggle switch next to the DC jack.. Note: you can automatically turn on the shield via software. See how to do that in the Automatically turn on the shield section, after the code examples. 7) You can test if the shield is working properly by sending AT commands from the Arduino IDE using an FTDI programmer – as we’ll shown later in this guide. SIM900 AT commands - set the SIM900 to text mode: AT+CMGF=1\r - send SMS to a number: AT+CMGS=PHONE_NUMBER (in international format) - read the first SMS from the inbox: AT+CMGR=1\r - read the second SMS from the inbox: AT+CMGR=2\r - read all SMS from the inbox: AT+CMGR=ALL\r - call to a number: ATDP+ PHONE_NUMBER (in international format) - hang up a call: ATH - receive an incoming call: ATA For more information, you can check the SIM900 AT commands manual here. Testing the Shield with FTDI programmer To test if everything is working properly, you can test the shield by sending AT commands from the Arduino IDE serial monitor. For that, you need an FTDI programmer as the one shown in figure below. You can get an FTDI programmer like this here.. Connecting the Shield to Arduino Connect the shield to the Arduino as shown in the schematics below. Sending an SMS To send an SMS, upload the code below to your Arduino board. /*********); // Send the SMS sendSMS(); } void loop() { } void sendSMS() { // AT command to set SIM900 to SMS mode SIM900.print("AT+CMGF=1\r"); delay(100); // REPLACE THE X's WITH THE RECIPIENT'S MOBILE NUMBER // USE INTERNATIONAL FORMAT CODE FOR MOBILE NUMBERS SIM900.println("AT+CMGS=\"+XXXXXXXXXXXX\""); delay(100); // REPLACE WITH YOUR OWN SMS MESSAGE CONTENT SIM900.println("Message example from Arduino Uno."); delay(100); // End AT command with a ^Z, ASCII code 26 SIM900.println((char)26); delay(100); SIM900.println(); // Give module time to send SMS delay(5000); } In this code, you start by including the SoftwareSerial.h library and create a software serial port on pins 7 and 8. (Pin 7 is being set as RX and 8 as TX) #include <SoftwareSerial.h> SoftwareSerial SIM900(7, 8); The sendSMS() function created is what actually sends the SMS. This function uses the AT commands: AT+CMGF=1\r and AT + CMGS. You need to change the recipient’s mobile number at: (replace the X‘s with the recipient’s phone number) SIM900.println("AT + CMGS = \"++++++++++++++""); The recipient’s mobile number should be in international format. Then, at the following line you can edit the text you want to send. // REPLACE WITH YOUR OWN SMS MESSAGE CONTENT SIM900.println("Message example from Arduino Uno.") Reading received SMS To read incoming SMS, upload the code below to your Arduino. After uploading, wait 20 seconds for the shield to establish communication. Then, test the script by sending an SMS to the shield SIM card number. The SMS is shown on the Arduino serial monitor – baud rate: 19200. /********* Complete project details at *********/ #include <SoftwareSerial.h> // Configure software serial port SoftwareSerial SIM900(7, 8); //Variable to save incoming SMS characters char incoming_char=0; void setup() { // Arduino communicates with SIM900 GSM shield at a baud rate of 19200 // Make sure that corresponds to the baud rate of your module SIM900.begin(19200); // For serial monitor Serial.begin(19200); // Give time to your GSM shield log on to network delay(20000); //() { // Display any text that the GSM shield sends out on the serial monitor if(SIM900.available() >0) { //Get the character from the cellular serial port incoming_char=SIM900.read(); //Print the incoming character to the terminal Serial.print(incoming_char); } } In this code, you set the module to send the SMS data to the serial output: SIM900.print("AT+CNMI=2,2,0,0,0\r"); You store the incoming characters from the SMS message on the incoming_char variable. You read the chars using the SIM900.read() function. Making a phone call To make a phone call, upload the following code to your Arduino. Don’t forget to edit the code with the phone number you want to call. /*********); // Make the phone call callSomeone(); } void loop() { } void callSomeone() { // REPLACE THE X's WITH THE NUMER YOU WANT TO DIAL // USE INTERNATIONAL FORMAT CODE FOR MOBILE NUMBERS SIM900.println("ATD + +XXXXXXXXX;"); delay(100); SIM900.println(); // In this example, the call only last 30 seconds // You can edit the phone call duration in the delay time delay(30000); // AT command to hang up SIM900.println("ATH"); // hang up } To make the call, you use the callSomeone() function that uses the ATD command. SIM900.println("ATD + +XXXXXXXXX;"); You need to replace the X‘s (highlighted in red) with the phone number you want to call. Don’t forget to connect a microphone and earphones to make the call. In this code example, the call is hang up after 30 seconds, using the ATH command: SIM900.println("ATH"); Hanging up after 30 seconds is not very useful, but it works well for an example. The idea is that you use the ATH command when an event is triggered. For example, connect a push button to the Arduino, that when pressed sends the ATH command to hang up the phone. Answering incoming phone calls The following code answers incoming calls. /********* Complete project details at *********/ #include <SoftwareSerial.h> // Configure software serial port SoftwareSerial SIM900(7, 8); char incoming_char=0; void setup() { // Arduino communicates with SIM900 GSM shield at a baud rate of 19200 // Make sure that corresponds to the baud rate of your module SIM900.begin(19200); // for GSM shield // For serial monitor Serial.begin(19200); // Give time to log on to network. delay(20000); SIM900.print("AT+CLIP=1\r"); // turn on caller ID notification delay(100); } void loop() { // Display any text that the GSM shield sends out on the serial monitor if(SIM900.available() >0) { // Get the character from the cellular serial por // With an incomming call, a "RING" message is sent out incoming_char=SIM900.read(); // Check if the shield is sending a "RING" message if (incoming_char=='R') { delay(10); Serial.print(incoming_char); incoming_char=SIM900.read(); if (incoming_char =='I') { delay(10); Serial.print(incoming_char); incoming_char=SIM900.read(); if (incoming_char=='N') { delay(10); Serial.print(incoming_char); incoming_char=SIM900.read(); if (incoming_char=='G') { delay(10); Serial.print(incoming_char); // If the message received from the shield is RING // Send ATA commands to answer the phone SIM900.print("ATA\r"); } } } } } } When someone calls the SIM900 number, it sends a message saying “RING”. To know if someone is calling you, you can wait for incoming characters from the SIM900 and then, compare if it was a RING message. That’s what is done in this code. When it receives a RING message, you send the ATA command to answer the phone. Automatically turn on the shield Instead of manually pressing the “power” key to turn on the shield, you can automatically turn on the shield via software. 1) First, you need to solder R13 connections on the shield as shown in the figure below – highlighted in red. 2) Connect D9 on the shield to the D9 Arduino pin as shown in the schematic below. 3) Add the following code snippet in the setup() function. This is the equivalent of pressing the shield “power” button. digitalWrite(9, HIGH); delay(1000); digitalWrite(9, LOW); delay(5000); Troubleshooting Shield. Cannot see messages in the serial monitor To see the messages in the serial monitor, the shield and the Arduino’s serial port baud rate should be the same. The SIM900 GSM GPRS shield Wrapping up This tutorial shows you how to send and receive SMS and making and receiving phone calls with the Arduino. You can apply the concepts learned in this tutorial to build your own projects to communicate over a cell network. We have other projects that use GSM, check them below: If you like Arduino projects, make sure you check our latest Arduino: Arduino Step-by-step Projects – Build 25 Projects We hope you’ve found this guide useful. Thanks for reading. 164 thoughts on “Guide to SIM900 GSM GPRS Shield with Arduino” Waouw. Great tutorial ! Thank you so much ! You’re welcome 🙂 This is great Can you post the tutorial for connecting sim 900 to internet (server) through GPRS Hi. Maybe we’ll do that in the future. Thanks for the suggestion. Verry good tutorial! I am also interested in connecting SIM 900 to internet (server) through GPRS. I saw the question from September 14, 2017. Is anything more known about this? Best regards. Hi. We have a similar tutorial, but not exactly what you’re looking for. See this example: I think you can use the same library we used with that shield. Regards, Sara Do you have any tutorial about using SIM7100e or SIM5320 with arduino or ESP to send/receive HTTP data from server using 3G/4G communication. Thanks Hi. Unfortunately, we don’t have any tutorials about those modules. Regards, Sara Hi fantastic, thank you Great Tuto. but i prefert M590 or A6 module. cheaper and less space. It is great tutorial as all You project !! Thank so much for You! Mike Great tutorial ! Thanks, just what I need. Do you know if it is possible to feed the 5 volts from the Arduino ? It seems a bit odd to me to use 2 separate powersupplies. Does the GPRS shield use 2 Amps ? Hi. It is not recommend to power up the shield using the 5V from Arduino as it won’t provide enough current, and the shield won’t work properly. Yes, it is advisable to use an external 5V power supply that can provide 2A with the GSM shield. Great tutorial! Is it possible to enable this shield from arduino, without pressing to the button? Thank you. Hi. Yes. There is a way to use software trigger, so you don’t need to use the button to enable the shield. In this specific module, accordingly to the data sheet, you need to connect D9 on the shield to D9 of the arduino and add the following snippet to your code, at the setup(), that is equivalent of pressing the power button: digitalWrite(9, HIGH); delay(1000); digitalWrite(9, LOW); delay(5000); I hope this helps. Regards. Thank you. Hi again. I forgot to mention that you need to solder the R13 connection in some shields. I added a section regard that subject in the guide – Automatically turn on the shield. I hope this helps. I read that issue with R13, but even with the photo it is not clear to me what to solder. Is it possible to give a better description or a more detailed photo. Second question, what do recommend as batty power supply. I like to use these 18650 accus. My project is to change an old rotary dial phone into a mobile just for fun. Hello from Germany Hi. There are two tiny pins inside the R13 label. You should solder those pins to each other. I haven’t tested using a battery to power up the shield, but I think those batteries should work. However, keep in mind that if you have your shield always on, the batteries will drain in no time. So, you need to keep the shield off, and turned it on, only when it needs to send a message, or make a phone call, etc… I hope this helps 🙂 Great tutorial! Is there a way to make an internet connection with the GSM module? For example, currently I use WiFi to connect my ESP8266 to a variety of servers such as Blynk and Thingspeak. I would like to use the GSM card to do the same without needing to connect to a WiFi access point. Is this possible? Great Tutorial! It work for me. Thank you so much. – Malaysia Is this GSM SIM900 works in Malaysia, I tried to run the AT commands but it not give response “OK”, please help me This is very interesting and useful tutorial that I have ever seen. HI, I would like to ask if somebody could post the pdf link of the datasheet for the SIM 9000 module. I have not been able to find on-line !. Hi Fredy. You can find a link to download at the SIM900 product page on Banggood. Check the following link: files.banggood.com/2016/10/SKU191995%20.zip more than tutorial, Sara my God bless you Thanks 🙂 thank you for the great tutorial. it is working with calls . but not sending messages Hi. If it is working great with the calls, I have no idea why it doesn’t work with messages 🙁 Everything worked just fine for us. Does it work with other versions of SIM900 like SIM900A and SIM900D? Hi Angelo! We haven’t tested with those boards, but everything should be compatible. Hi, i like this awesome tutorial. But it gives me some idea, please can you tell me if it may be possible to send one sms to a big number of phone numbers throught data bases? Hi. I think it should be possible as long as your SIM card allows it. But we don’t have any example on that subject. Regards, Sara Can you give examples of SIM cards that work with your system? When I type in the IMEI number from the figure into a T-Mobile reseller’s website, an “incompatible” message appears. Hi. I used SIM card from Vodafone. I haven’t tested with other providers. Regards, Sara beatiful Thank you, it is great tutorial Thanks 🙂 Is the FTDI required?? Is thought that when connecting GSM module to Arduino Uno and then go to the serial monitor is fine to give AT commands. I ordered a GSM900 as shown in your pictures, but no FTDI, since I did not know about it. Jan Hi Jan. You don’t need an FTDI programmer to work with the shield. It will work just fine with the Arduino. In the tutorial, we show how to send AT commands using the FTDI programmer, but you can also use the Arduino and Serial Monitor. I bought a GSM900a in first place, but that one did nothing at all. So I’m waiting for a long time… hope that I can forget about the FTDI therefore 😉 Sis , i followed all off your tutorial start from hardware interfacing until whole of the program written , but here i found a problem that my SIM900 shield didn’t work properly even i get OK response from AT COMMAND. i try to call someone with AT COMMAND in first 3 second serial monitor give me OK but after several second the other response show NO CARRIER. I tried to change my SIM card but it still happen. could you give me solution about it? Thanks Hi. If you get an OK response, your shield should be working properly. So, I can’t tell you why it is not working. Maybe you’re not using the phone number correctly. Please make sure you’re using the phone number in international format. I hope this helps. Regards, Sara Hi, thanks for the tutorial, it’s great, and worked for me right the first time. My only problem is, when i call someone, the phone shows “unknown number” (Private number). The sim card with a phone, showing the number, but when i call with the shield it’s hiding the phone number. Sorry for my english, hope you understand what is the problem. :/ Hi Peter. I understand your problem. Unfortunately, I don’t know why that happens. I’ve tried to search for someone with the same problem but I was unable to find any information regarding that specific problem. Very helpfull .Great tutorial. Thank you. I’m looking for the frizing part of this shield, but after searching everywhere, I didn’t find it. May be you have it ? Hi. Unfortunately we don’t have that fritzing part. Thanks for beautiful guide. I’m now able to send and receive sms as i needed. The only thing is that i can not send and receive sms with Extended characters. How can i send and receive sms eith ąčęėįšųūž letters? Hi Arnas. I think you need to convert the characters to ASCII. Take a look at this tutorial: playground.arduino.cc/Main/Utf8ascii However, I’m not sure if this will work when sending the characters on an SMS. I hope this helps, though. please could someone help me how to replace SIM900.println(“Message example from Arduino Uno.”) so i could send with sms the temperature read from a sensor Hi. You need to create a variable to hold your temperature. Then, you need to convert that variable into a String. Finally, you just need to send that variable using the SIM900.println(). For example: imagine you save the temperature on the Temp variable. You just need to do as follows: SIM900.println(String(Temp)); I hope this helps. Hi, I have problems getting the SIM900 shield to operate. I have checked that the SIM is without PIN code, and I have checked that it works by using it in my mobile phone. The SIM is a prepaid card from Telenor in Norway. I power the SIM900 from a separate 60W power supply Trying to get the card to connect to the network, eveything is as described after pressing power on. However, it looks like the cards stops when it connects to the network. The NetLight turns off and does not blink anymore. I then have to remove power and start over for the power key to work again. -any idea what might be the problem? -should the AT commands work before I press the power key and get it connected? Hi Tor. When the card connects to the network, the NetLight LED should be blinking every three seconds (that indicates it is properly connected to the network). To power up the shield you should press the power key for about 2 seconds. Then, the Status LED will light up and the NetLight LED will blink every 800 ms until it finds the network. When it finds the network, the NetLight LED will start blinking every three seconds. If it is not connecting to the network, it may be a problem with your card, or with your GSM shield. The GSM shield should be connected to the network before sending the AT commands. I hope this helps. Regards, Sara 🙂 Hi, i recently got a Sim900 module, i understand all the AT commands, and functions, ( this guide also helped me ) But i got a problem, the first step! My net light only blinks once per second, and it stays that way for long time… which means it cant acquire network, i dont know why? My module is connected to a 9v 1a power supply, The Sim card is in correct position. Ive read that sometimes, the Ant pin is not soldered properly, or also if the Manufacturer its from china, it wont with america signals. Do you know what could be happening? Hi. I don’t know what can be wrong. Does you location support 2G network? The SIM900 is a 2G network device. It looks like you have the same problems as I have, see above. When the SIM900 does not connect to the network, its impossible to debug what the problem is as the AT commands does not work I’m pretty sure 2G is supported bu my provider here, but it does not connect. Please tell if you find a way to get a status from the shield without a network connection. Look for an AT-command-list like –SIM900_AT.pdf– and find out more about signal quality, connections etc.. You can start by checking the signal quality with a command like — SIM900.println(“AT+CSQ”) — (and feed the output back the serial port). Also check the commands AT+COPS? and AT+CREG? in different variations… This will tell you if your antenna is working (CSQ) and if there are carriers you can connect to or are connected to. You can find out a lot more about your board and connection with AT commands, even without (or before ) a network connection ! And I admit, it’s still difficult to connect these boards … but you will learn a lot more about your board by trying these commands 🙂 Hi Gerrit. Thank you so much for this information. This will be very useful for many of our readers 🙂 Hi, Although i managed to send an sms from the gsm shield, i cannot read the sms. i followed the steps you described about setting the baud rate to the correct value etc but still the read sms doesn’t send out anything to the serial out port. can you help? thnaks Make sure you SIM has not a PIN set (that’s a common mistake). When i connect the GSM module with my 9V battery after few blink the status LED and the NetLight LED just wen5 OFF.. What is the issue i have no clue. Please help. A 9V battery shouldn’t have enough power to make the GSM module work reliably… You need to use an external power source or a power adaptor. Any clue on how to use the RTC on this board? Hi. Unfortunately, we don’t have any tutorial on that subject. Regards, Sara 🙂 Nice work guys, keep it up I wanted to ask could you please help me to sending my sensor data over the internet? I wanted to transmit my data using internet and gsm module, I did it using esp8266 but now I wanted to transmit using gsm sim900 shield. Thanks in advance Hi. Unfortunately, we don’t have any tutorial on that exact subject. Thanks for reading, Regards, Sara 🙂 Hey, I am trying to make a program in which I execute certain actions based on the SMS I receive. However I don’t know how to only store the SMS text in a variable (to later compare it) without the phone number of the sender etc… Hi Matteo. We have a tutorial that executes actions based on the SMS received. This tutorial may help you with your project: – Control a 12V Lamp via SMS with Arduino This tutorial shows how to send SMS to make the arduino do something (in this case it turns a lamp on, but you can do any other action) I hope this helps 🙂 Great Tutorial! Can please post the tutorial how to find out the location, Latitude,Longitude using Arduino and SIM900 only? Thanks for the suggestion, but we don’t have any tutorials on that exact subject Thank you for this complete tutorial. I haven’t received my SIM900 module yet but I found this recent documentation on AT commands including GPRS commands: simcom.ee/documents/SIM900/SIM900_AT%20Command%20Manual_V1.11.pdf Hi. Thank you for sharing! That’s a great documentation. Regards, Sara 🙂 Hi there, Nice tutorial! I wanted to open my gate gate by calling into the Arduino (with a saved number in the Arduino). The Arduino should switch on a relai and after a couple of seconds switch it back off. Is it possible to do something like this? Greets Gijs Hi. It is possible. When you call the Arduino, it triggers a function that turns on a relay. When you call the shield, it receives a “RING” message. So, you can check whether it received that message and then, turn on the relay. Take a look at the “Answering incoming phone calls” section. You may also find useful the following tutorial, in which we control a 12V lamp using a relay via SMS: – I hope these tips help you. Regards, Sara 🙂 If I use SIM808, all that is explained in this guide remains good? Thank you and greetings. Hi Alberto. We haven’t tested with the SIM808. But I think it should work similarly. Just take into account the serial pins location and how to properly power your board. I think the AT commands should also work with that board. Regards, Sara HI, sorry one small question, when we do automatically on/off via PIN D9, that means if electricity switch off and come back again, after starting Arduino will start also the shield without pressing manual button??. Many thanks. Hi. Yes, it should start the shield automatically because the snipet of code to automatically turn on the shield is in the setup(). So, when the Arduino restarts, it will run the setup(), and automatically turn on the shield. Regards, Sara 🙂 Hello Ms. Sara, This is really a splendid tutorial; I would not have made my project work if it were not for you. Thank you so much. I was trying to make a PIR-triggered-SMS alarm. My shield which is identical to yours kind a works ONLY without the auto-on snippet(so, I deleted this from the code and unplugged the D9 wire); however, in some 20 minutes, the shield turns off by itself. My intention is to manually switch it ON and leave it ON for a longer period of time (days). Would you know how to? Hi Jonathan. Thank you for you kind words. I was not aware of that problem, but after searching for a while it seems to be a power issue. Can you read the solution #13 on this thread: and see if it helps? Regards, Sara 🙂 Hi Sara, would you mind to help me? I purchased the same Shield as your and followed all the passages but It doesnt work! I read that the Baudrate is too fast but im not sure! Could you help me? Maybe contact me via mail or here? I will explain all my steps. Thank you Hi Nocolo. What exactly doesn’t work? Does the shield respond with OK when experimenting with the AT commands? Regards, Sara 🙂 Hi sir, I am facing a problem in sending a message using GSM AT commands for Serial.print(“AT+CMGS=\”6361066623\”\r”); here instead of my number I am using a variable which has a mobile number. So the command I used looks like Serial.print(“AT+CMGS=\”” + myNum + “\””); or Serial.print(“AT+CMGS=\””); Serial.print(myNum); Serial.print(“\””); but the problem is the code gets compiled but I am not receiving any messages for that number stored in the variable ‘myNum’. I am using Arduino UNO board, Please help me to solve this problem Hi Jeevan. Try the following line: SIM900.println(“AT + CMGS = \” + myNum + “\”); I hope it works, Regards, Sara 🙂 This works in my code: Serial.print(“AT+CMGS=”); //send sms message Serial.println(phoneNR); delay(100); Serial.println(F(“Your message content…”));//the content of the message delay(100); Serial.println((char)26);//Close message–the ASCII code of the ctrl+z is 26 delay(100); Serial.println(); Guess this will solve your problem. Regards, Gerrit Hey I saw the input voltage of the SIM900 should be between 4.1 – 4.8 in the datasheet, Is it ok to use 9V/1A or 12V/1A??? Is that not a problem for the SIM900 components? Hi Jerom. It depends on your specific SIM900 module/shield. The module we’re using here recommends the voltage we specify on the article. You should note that there are different modules that use the SIM900. Therefore, they might need different power requirements. Regards, Sara 🙂 Hey Sara amazing tutorial! Any chance to have a HTTP GET/POST tutorial? Can’t really find anything useful around and yours has been the only working tutorial so far.. Hi Juan. Thank you for your kind words. At the moment, I don’t have any tutorials about what you’re asking. Regards, Sara 🙂 Hello Sara, Will a SainSmart GSM900 shield work with your project? I already have one and wouldn’t have to purchase the larger development board you list. sainsmart.com/products/sim900-gprs-gsm-board-quad-band-module-kit-for-arduino Hi Jeff. It uses the SIM900 module. So, it should work with this tutorial. You just need to make sure you wire the shield properly. Regards, Sara 🙂 Sara my gsm sheild 900a not work not show at command on serial moniter it show the nmbr to which ‘ send the msg not send msg Awsome, The solution to having a phone that makes you look smart and doesn’t cost heaps of money! hello, excellent guide I have a problem: after switching on the card, the two LEDs light up, but after a few seconds they turn off again. can you help me? thank you But what’s the problem? Is the example working for you? I think on the code examples you miss the // import the GSM library #include Hi Michael. Those examples use the SoftwareSerial library to communicate with the SIM900 via serial. There’s no need to include other library. Regards, Sara Would it be possible for this module to trigger an Arduino port when it receives a call from a previously registered number? Yes, you can definitely modify it to do that. You need an if statement that compares the number that is calling with the number stored, then you can do whatever you want. Unfortunately I don’t have any examples with that exact subject… Thank you very much. Can I also use PIN 0 and PIN 1 instead of PIN 7,8 . If this is true, do I still have to use the softwareSerial library? I am using an Arduino UNO R3. Hi Max. If you use pin 0 and pin 1, you are using hardware serial. So, you don’t need that library. If you’re going to use hardware serial, you need to change the shield jumper caps to use hardware serial. This image shows the jumper caps to use software serial ( you should change that to use hardware serial. Regards, Sara Sara my gsm sheild 900a not work not show at command on serial moniter it show the nmbr to which ‘ send the msg not send msg What is hardware serial and connecting pinout diagram Bonjour et merci Sarah pour ce tuto très complet et bien expliqué. Peut on se servir de ce tuto pour exploiter la sim 800? Merci Hi Gaspard. I’m sorry but we don’t have any tutorial about the SIM800. Regards, Sara Hi, I search the diagram of the card and the function of the pins of the connectors. thank you if you can transmit it or the address of the site. Emmanuel bonjour, je recherche le schéma de la carte et la fonction des broches des connecteurs. merci si vous pouvez le transmettre ou l’adresse du site. Emmanuel Hi Emmanuel. Take a look at the following link: stackoverflow.com/questions/42549537/sim-900-gprs-shield-pinout I think it might help you out. Regards, Sara 🙂 Thanks Sara for the great Tutorial. I’m working on a home automation project with Raspberry, Openhabian and relay boards. And my “failover” project will include this GSM shield just in case the network wouldn’t be available. Tomorrow I will get the GSM shield. I will make you know about my experience with this. I’m eager to test it and see how it works! Thanks and keep up the good work !! Richard Hi Richard. Great! Then let me know how your project went. Regards, Sara Hello, I have two doubts: -In my card, there is a resistance 0 in R13 position… i think that I do not have to modify anything for the D9 pin to work. Is this correct? (but sometimes D9 don’t work and sometimes D9 work OK. Sometimes Q2 don’t conmute with D9 High Level. I don’t know why?) Someone else happens? -which is the function of J20 and J3 Jumpers? (GND // VCC5 and GND // 4.1V) Thanks a Lot Pedro Hi Pedro. It seems that you shield behaves differently than mine. So, I can’t advise much. If D9 works, it is probably already connected. As for the jumpers, I don’t know their functions :\ I’m sorry that I can’t help much. Regards, Sara OK. Thanks a Lot Pedro. The information was very useful. Kindly can I get the REACH statement for the manufacturer SIMCOM with the manufacturer part number SIM 900.. Hi. I didn’t have that problem with my SIM900. But you can learn more about the SIM900 sleep mode here: raviyp.com/embedded/223-sim900-sim800-sleep-mode-at-commands Regards, Sara Hello Sara Thanks for your quick reply and suggestion. Now I am using same Gsm 900 module. When power up module(12v 1amp), status led turn on & netlight start blinking(3sec). But why status led blink automatically after 18 second. When status led blink netlight again start blinking for network and network connection established. This process happen three times then after status led and netlight led turn on continuously and network connection failed. Bonsoir juste savoir si le bouclier sim900 peut se connecter au reseau gsm 4G Hi Alain. SIm900 doesn’t work with 4G. You need other module like SIM800C. Regards, Sara hi sara can you help me? i have the right code. but the receiver did not receive a message. Hi. Without further information, it is impossible to understand what is going on. Make sure the SIM card is working properly and it is able to send SMS/make phone calls. Also, make sure that your country support 2G (used by the SIM900 module). Regards, Sara how to connect GSM shield to arduino uno without external supply ie providing supply directly from arduino to it? I have a SIM800L module instead of SIM900 how do i please ?? Hi. I’m sorry, but we don’t have any resources about SIM800L module. Regards, Sara hi , Can you help me with just sending a message from gsm sim 900a with if condition ! Hi. What is your question? Regards, Sara You just have to call the sendSMS() function after your if statement. This tutorial help me a lot! Thank you so much… hey Sara, great tutorial, Please what is a jumper cap , what does it do ? I searched google, but did not find intersting results. thx Hi. A jumper cap is usually a small piece of plastic outside and metal inside that connects two pins together. Regards, Sara Does SIM900 module need any programme to be uploaded to it before connecting to the arduino UNO? Hi. No, you just need to upload the code to the Arduino. Regards, Sara hi, great information. i want to ask how i can filter phone number from received sms so that i can program it later to recieive sms from specific phone number and not from any number To check the number that send the SMS, I think you can use the following AT command: “AT&CNUM=? Try a quick google search for SIM900 AT commands. Regards, Sara Hello, beautiful project !!! I wanted to know, I am in possession of the 800l sim module and apart from the esp 32 board I can use them in this project? Can you show me links and the sketch is modified or not?. good code great work Thank you for this tutorial. I got it working with SMS sending, and have some additional advice. You may not need an extra power supply, if you are close to a base station. Arduino takes just a small part of the current that your PC can deliver to USB port. The rest may be enough to the GSM shield. Just connect +5V from Arduino to +5V of the shield. That is an easy trial, and it worked for me. When you have your code ready, you can replace PC with an USB power bank. If your code is waiting for something to happen, you should use sleep mode inside the waiting loop and put also the shield to sleep mode. You can get easily over one month waiting time. Thanks for the tip. Regards, Sara 😀 Hello again. I haven’t found anywhere information about in what state is the shield after connecting the power but not powering up with the button or by software. I wanted to keep it waiting in a low current state, but is that the lowest I can reach? Can you help me in this? Our SIM Card is a 3G. Could this be the problem You can use a 3G SIM card, but your country needs to support 2G network. How do you get SIM card number? I see the ‘unlock pin’ thats easy and clear, but no where on the internet does it show how to get the SIM card # if you call straight talk, you need the IME or SN numbers, to activate the SIM but then i would think they contain your cellphone # and not a different new one for the SIM so if i activate the new SIM i would be calling my own phone # It must be a real, real simple process because there is so much confusion and people unable to run their device over SIM issues like to run your GF-07 GPS- Tracker… Please what are the steps to “use a SIM card” presume nothing and please leave nothing out. i did buy your camera tutorial and hope to build one soon, and the GPIO controller using a server based database. and i am playing with the GSM900 from youtubes website. hello i want to ask that can you help me on a project that is home security using gsm 900A and a pir sensor? Hi I’m starting to develop a project with a GSM module, first I read your tutorial an let me tell you is very,very good. I wonder if I can put any type of SIMCard, as you know , the operators sells you a SIMcard to 2G Networks and a UsimCard to 3G/4G Networks It will be work with either of SIMCard type? Thanks in Advanve Best regards Marcos Hi Marcos. It works with any SIM card type. For example, you can use a 3G or 4G card. But the module will just work if your area supports 2G network. Regards, Sara thanks for this tutorial ! this is very helpful Great tutorial but it stops right when you get to what’s really needed. I have searched all over the internet and this is the same tutorial that I find. It works great. I need the next steps on how to have the arduino read an incoming text and have it trigger a function. Please do a part 2. Hello. Great tutorial. It is working perfectly. I am testing to see if it presents any problem: I turned it on and left it there for about 3 hours, then I decided to press the button to see if it would send me a SMS – the shield showed it was connected to the network ( LED blinking every 3 seconds) , but it did not send the SMS. What could it be? Grato Hello, I’m working on a similar project. I’m wondering if I can use your code and try to adapt it to my project, which consists of sending a text message to a cell phone number. Please answer me. Hi. Yes, you can use it and modify it as long as you reference our project. Regards, Sara hi sara … Can I communicate with you personally other than here by e-mail or WhatsApp … to help me with several problems .. Thank you very much Hi. I’m sorry, but we don’t do that kind of job. Regards, Sara Great tutorial. Please can you help me with connecting gprs with arduino mega board. Regards. Good day. Please i want to know whether i can send SMS and at the same time send data using GPRS SIM900. assuming i want to send a message to a particular number. example. sending “HELLO ” and at the same time sending data like sensor value to the same number. thank you so much Hello, I am working on a similar project using SIM808 GSM/GPRS/GPS Shield (B) and Arduino Uno. I want to send sms notification. Any insights of how to go about it. It seems the shield I bought has not yet been posted by anyone. I’m stuck! Hello, Fantastic!! Great tutorial. Please could you help me with code for: 1) Send SMS to 5 different number, 2) Make Call to 5 different number. Thanks. Hello Sara, i want to make some automated calls and after pick up a recording should play. Is there a way the arduino knows when a call is picked up? Thank you very much Andrei Hi. Yes. Check the section that says “Answering incoming phone calls”. Regards, Sara Hi Sara, That part is for the incoming call, i want to make an outgoing call, i dont know the event which is telling me that the phone was picked up. my question was misleading. i want to make some automated calls (from arduino) to a person and after person is picking up a recording should play. is there some event which tells me about answering outgoing call Thank you very much Hi. I think this issue provides information about your question: stackoverflow.com/questions/63240900/sim900-gsm-module-how-to-check-if-the-outgoing-call-is-answered I hope this helps. Regards, Sara I have completed my two basic projects with your help. your article helps a lot me.thanks I really want to get started using these modules BUT I am unable or unsure which SIM Card to get… I tried carriers like mint mobile but no service… I’d like to get a card that does not expire as I don’t play with this stuff everyday and can be reloaded with min/text… Anyone have any ideas…thanks Lets say youre monitoring something and you need to invoke a call when a certain condition is met. How do you go about it? How do you program that function?
https://randomnerdtutorials.com/sim900-gsm-gprs-shield-arduino/?replytocom=405310
CC-MAIN-2022-21
refinedweb
7,626
73.78
- Articles - Documentation - Distributions - Forums - Sponsor Solutions There are literally dozens of window managers that you can use with your favorite desktop environment to get a beautiful and appealing desktop. If you want to fine-tune your window manager, here are two programs that can help you control everything from application window size to pinning an application to all workspaces to fixing a position for your application windows to resizing desktops. One, wmctrl, works with any window managers that adheres to the Extended Window Manager Hints (EWMH), while Devil's Pie is a window-matching utility, which means it can configure application windows based on defined rules. wmctrl is a command-line utility that can be used to manipulate or control various aspects of application windows and the desktop environment. Fedora and Ubuntu users can use yum or apt-get respectively to install wmctrl on their machines, or you can grab the compressed tarball from the software's Web site. According to the site, wmctrl is known to work with IceWM, Blackbox, Metacity, Openbox, Kwin, Enlightenment, and several other window managers. There isn't much documentation for wmctrl, but the detailed man page is enough to start you in the right direction. The command wmctrl -m will print out details about the desktop environment and the window manager. You can use the -l switch to get a list of all the active windows (applications) in space-separated columns. The first column is a hexadecimal number, which is unique for each window. The second is the desktop number, or the workspace -- 0 means the first workspace, 1 means the second, and so on. The machine name is listed in the third column, and the last column contains the window title: wmctrl -l 0x03400175 0 localhost.localdomain XChat: linuxlala @ FreeNode (formerly OpenProjects.net) / #fedora (+tncrRL) 0x0240007e 0 localhost.localdomain Gmail - Inbox (33) - Mozilla Firefox 0x03c00035 0 localhost.localdomain wmctrl_devilspie_article (~/Desktop) - gedit 0x03e0001e 0 localhost.localdomain linuxlala@localhost:~ To manipulate any window, you need to know its title. The command, wmctrl -a gedit will make the Gedit window active. This is most useful when you have several windows open in various workspaces. But what happens if you are simultaneously working with several Gedit windows? You can easily retitle any window with the command wmctrl -r :SELECT: -T "cool feature". The :SELECT: option enables you to select the application window whose title you wish to change by clicking on it -- though not by using the Alt-Tab key combination. When you click on any window, its title immediately changes to the one specified. You can specify the current title of the window instead of using the :SELECT: option. For example, wmctrl -r XChat -T "IRC" would retitle my XChat window to IRC. You can also resize windows with wmctrl using the -r and the -e switches. The -r switch specifies a window and the -e switch resizes a window already specified. wmctrl -r gedit -e 1,20,30,750,1200 would resize the Gedit application window. For this to work, the application window must not be in a maximized state. The -e swtich expects five values: gravity, X-position, Y-position, width, and height. The X and Y positions respectively describe the position of the window from the left and top of the screen. Gravity is used to specify the position of the window's frame and it can be any value from 1 to 9. Each value maps to a position on the screen. The values it can take are northwest (1), north (2), northeast (3), west (4), center (5), east (6), southwest (7), south (8), and southeast (9). Devil's Pie can perform all of the same functions as wmctrl, but it's actually a more powerful tool for manipulating windows. Being a window matching utility, Devil's Pie works on a set of defined rules. As new application windows are created, Devil's Pie looks through the defined rules to see if any are defined for the window being created and then, based on the defined rules, it models the window. Devil's Pie was created to incorporate window matching into Metacity, the default window manager on the GNOME desktop environment. The rules for each window are defined as a set of S-Expressions. To install Devil's Pie, simply grab the compressed tarball from its Web site, or use yum or apt-get depending on the distribution running on your machine. Rules for each window are defined in individual files with a .ds extension and stored in the ~/.devilspie directory. The first file you should create is the debug.ds file. Open a text editor and type debug. Save this file as ~/.devilspie/debug.ds. When you now run Devil's Pie, it will display on the screen the application name, window name, window class, and various other properties of all the open windows. You should always refer to your applications with the correct names to make Devil's Pie perform correctly. Let's create a rule that forces the Gedit text editor to always open in the second workspace: (if (is (application_name) "gedit") (begin (set_workspace 2) ) ) Save this as gedit.ds in ~/.devilspie. Open a terminal, type devilspie, and press Enter. Now when you launch Gedit, it will automatically shift to the second workspace no matter what workspace you launch it from. You can use regular expressions when writing rules. For example, if you have two active instances of gnome-terminal, you can use regular expressions to write a rule for each: (if (matches (application_name) "linuxlala") (begin (set_workspace 3) ) ) The above rule applies to the default gnome-terminal. With the matches keyword, you can make Devil's Pie look for partial matches. Suppose you have another gnome-terminal window within which you've browsed to the /etc directory. To refer to this window, you can use (matches (application_name) "etc". If you wish to make use of regular expressions, you must also use the matches keyword in place of is. You can similarly write rules to make your applications open as maximized or in a certain position of the screen. You can also use pin to make sure the application is available on all workspaces. This can be helpful for IM or chat programs that you might want in all workspaces so as to not miss an important message. You can even perform multiple actions on an application by adding them within the begin structure. (if (matches (application_name) "linuxlala") (begin (set_workspace 3) (maximize) (undecorate) ) ) To add Devil's Pie to your startup programs list, click System -> Preferences -> Personal -> Sessions. Click New and type Devil's Pie in the Name field and /usr/bin/devilspie in the Command field. Now every time you log into your machine, Devil's Pie will run automatically and manipulate the applications as described in the rules. wmctrl and Devil's Pie put you in charge of your windowed applications by giving you complete control over all their aspects. Shashank Sharma specializes in writing about free and open source software for new users and moderates the Linux.com forum boards. He is the coauthor of Beginning Fedora, published by Apress. Commentson Take charge of your window manager with WMCTRL and Devil's Pie Note: Comments are owned by the poster. We are not responsible for their content. TypoPosted by: Anonymous [ip: 91.84.213.104] on December 21, 2007 10:03 AM # wmctrl in action and X11::GUITestPosted by: suso_banderas on December 21, 2007 12:41 PM Another thing you can use for automation is the perl module X11::GUITest. You can control the mouse and stuff. I used it once to automate making a large mosaic map from several Mapquest and Google satellite images. But I can also use it to do stuff like automatically scroll down a web page after I switch to a desktop. So if you need to control the mouse and keyboard, X11::GUITest is something to look into. # Take charge of your window manager with WMCTRL and Devil's PiePosted by: Anonymous [ip: 89.136.186.184] on December 21, 2007 04:35 PM The biggest limitation in wmctrl is that it was left incomplete and cannot perform all the hints that the full spec allows for. And for both wmctrl and Devil's Pie is true that they left out clearing certain flags -- you can set the "skip the pager" flag, but you can't clear it! For keyboard and mouse control I also recommend xmacro and Xnee, as well as irexec if you have a remote. Together with xmodmap you can do some pretty nifty stuff. # Take charge of your window manager with WMCTRL and Devil's PiePosted by: Anonymous [ip: 68.192.12.60] on December 21, 2007 05:05 PM # Python anyone?Posted by: Anonymous [ip: 76.195.2.194] on December 23, 2007 08:05 PM import dp p = dp.pie() p.application_name = "whatever" p.set_workspace=3 p.undecorate=True p.tell_daemon() # end of script This would not in itself would make it easier for end users but guis could be written for all devils pie functions. This also means that you don't have to maintain your own interpreter, config file format etc and can rely on a fairly simple existing language. Just a thought. # This story has been archived. Comments can no longer be posted.
http://www.linux.com/archive/feature/122471
crawl-002
refinedweb
1,561
54.83
Dec 14, 2007 01:36 PM|dmtr|LINK Hi, I installed MVCToolkit and played with tutorials. I tried to create some Product object (Linq To Sql) in an action method: But encoding for string values in Request.Form didn't happen and I successfully saved javascript code as product name :( [ControllerAction] public void CreateNew() { Product prod = new Product(); prod.UpdateFrom(Request.Form); northwind.AddProduct(prod); northwind.SubmitChanges(); ..... }What do I need to do to have encoding UpdateFrom Dec 14, 2007 02:20 PM|SteveSanderson|LINK If you need to apply custom logic to the data that's assigned, the current UpdateFrom() method might not be a good approach to you. There isn't a way to control programmatically any encoding or access restrictions (besides passing an array of property names). If would be nice if, in future, there was an extended version of UpdateFrom() that would take a delegate to call back some custom logic to handle each member. It could look like this: // Defined by the framework public class UpdateMemberData { public object Value { get; set; } public bool AllowUpdate { get; set; } } public delegate void UpdateMemberDelegate(Object targetObject, MemberInfo targetMember, UpdateMemberData data); public static void UpdateFrom(this T obj, NameValueCollection values, UpdateMemberDelegate callback) { ... } // Called by the user myObject.UpdateFrom(Request.Form, delegate(Object targetObject, MemberInfo targetMember, UpdateMemberData data) { switch (targetMember.Name) { case "SomeProperty": case "SomeOtherProperty": data.Value = HttpUtility.HtmlEncode((string)data.Value); break; case "UnprotectedProperty": break; // Allow unescaped data default: data.AllowUpdate = false; // Block access to any other members break; } data.AllowUpdate = false; }); Not really sure how advantageous this is anyway, as some type-safety is lost. Dec 14, 2007 02:52 PM|slynch|LINK How the javascript getting into the form fields? Dec 14, 2007 02:56 PM|dmtr|LINK I found an acceptable solution (for me :) ): In BindingHelpers.cs file of MVCToolkit solution I added some code to UpdateForm method (at line number 100)... ... string strValue = value as string; if (strValue != null) value = HttpUtility.HtmlEncode(strValue); ... Dec 14, 2007 03:50 PM|slynch|LINK{ And then call it like: prod.UpdateFrom(Request.Form,c=>HttpUtility.HtmlEndoce(c)); Dec 14, 2007 05:11 PM|robconery|LINK Thanks for the feedback - we're going to make two changes to the helpers in the next drop: 1) Encoding will be ON by default 2) There will be an override to turn it off (if you use an RTE for instance) The other alternative (as you've seen above) is to override what we're doing with your own method for now. I should have done it this way in the first place :). Dec 14, 2007 05:25 PM|shinakuma|LINK quick question, I'm a little confused, but why would want to by default HtmlEncode an input and stuff that into your DomainObject and ultimately into the database? shouldn't it be the other way around, you HtmlEncode it for displaying purpose, and store it as is? Dec 14, 2007 05:27 PM|robconery|LINK It can be either way - but the safest bet is "protect inbound" since you never know where that info will turn up again. For instance if you're object is a ProductReview and you forget to encode the output. It happens. Also - it's not a very expensive operation, but it is string manipulation and therefore has a cost to it. If you encode on every output it can add up and hurts scaling. Dec 14, 2007 06:08 PM|dmtr|LINK slynch{ public static class CustomBindingHelperExtentions{ public static void UpdateFrom(this object obj, NameValueCollection values, Expression<Func<string, string>> encoder, params string[] keys) { NameValueCollection encodedValues = new NameValueCollection(); Func<string, string> encodeFunc = encoder.Compile(); foreach (string key in values.Keys) encodedValues.Add(key, encodeFunc(values[key])); if (keys.Length > 0) obj.UpdateFrom(encodedValues, keys); else obj.UpdateFrom(encodedValues); } } } And then call it like: prod.UpdateFrom(Request.Form,c=>HttpUtility.HtmlEndoce(c)); Thank you, it's the best solution for now Dec 16, 2007 05:59 PM|SteveSanderson1|LINK Rob, please tell me you're not serious about HTML-encoding all input by default. I appreciate that you're trying to protect people from their own ignorance or forgetfulness, but as shinakuma indicated, this causes more problems than it solves. [1]. What about when I'm not outputting to HTML (e.g. when rendering to a plain-text email, WinForms app, or 3rd party system) - do I have to unescape it first? Yuck! [2] It leads to more serious security vulnerabilities. You say it's safer to "protect inbound", but here the opposite is true. Remember that by saying "we'll protect inbound", you're also saying "you must not protect outbound" (otherwise you'll double-escape and & will render as &). So now we are forced to trust that all systems writing to the DB remember to encode all strings exactly once, and any single vulnerability spreads to all parts of the system because nothing protects outbound. "Perimiter security" is not safer when it actually prevents you from adding real security. [3] It's inconsistent with how decent ASP.NET controls work. Well-written controls take responsibility for HTML-encoding their own output, so pre-escaped strings would cause display problems. [4] It's inconsistent with how other aspects of the MVC framework work. You're not pre-escaping all values passed to IHttpRequest.Form, so myObject.Value = form['key'] would behave differently to myObject.UpdateFrom(form). If someone on my team encoded strings before putting them into the DB, then depended on that when rendering them later, I'd have to tell them off and ask them to change it. Please don't encourage this behaviour! Dec 16, 2007 08:54 PM|SteveSanderson1|LINK Um... maybe that was an excessive rant - I do really like the MVC framework so far! Good work [:)] Dec 17, 2007 11:02 PM|robconery|LINK ScottGu and I talked a bit about this and HTMLEncoding a security concern so we have to take this into consideration when deciding how to deal with these things. SteveSanderson1. In terms of it's "place" - I highly disagree. Anything that is being reported back to a web front end (usually a browser) should, at some level, be checked so that you don't inadvertantly sabotage your user. Database, flatfile, cache - the storage medium has nothing to do with this :). FullText indexing ignores anything in <>. One thing you can do here is to Encode on the way out - but again that's a perf thing you'd need to think about. I hear you though about the other readability issues, and we can have an override to turn it off. SteveSanderson1"Perimiter security" is not safer when it actually prevents you from adding real security. Yep. Security comes at a cost at some level and I agree with you in principle here. However you're talking about a 1% issue at best (shared DB input) and many architects would completely cringe at sharing a DB with a web site for this very reason. However your point is valid and again - we'll provide an override so the decision to turn this off if you need. SteveSanderson1It's inconsistent with how other aspects of the MVC framework work. Hopefully not - but if we're not encoding properly we need to take a look at that. Ultimately it boils down to line of responsibility - should Microsoft, by default, disable security or should you, as the developer, disable it for yourself? I'm all for trying to find a better answer here - would another route be acceptable - something like "UpdateFromEncode(Request.Form)"? The thing is - and I'm going to stick to this - the decision to turn encoding off needs to be the developer's. --Iniviting ScottGu and DamienG to this thread - it's a good one and it's important. Dec 17, 2007 11:15 PM|abombss|LINK We are talking about Encoding not Decoding.... The name alone dictates the direction. What if I am not even outputting html but some other format. Now I need to ensure that all my input is not encoded? On by default is just confusing. I would change the method names all together so it is explicit what is going on. Dec 17, 2007 11:42 PM|shinakuma|LINK WebForms by default validates the request for injection attacks, it does NOT however by default html encode everything to be passed along "securely" into your DB. It's unreasonable to assume that your data will be in a silo consumed only by your web frontend when dealing with enterprise applications. I don't want to have to worry about html decoding when I import these data into my warehouse or sync over to a legacy system, or like someone said output to a non-html format. That is just backwards. The default behavior should be you encode for display, not for storage. Dec 17, 2007 11:48 PM|damieng|LINK Any helper functions that output HTML should encode values using HttpUtility.HtmlEncode for literals and HttpUtility.HtmlAttributeEncode for attributes such as value on input tags. If users want to output unencoded HTML then let them do that themselves without a helper as it's not easy to deal with. Where you are bringing data back for processing through a form you don't need to do anything - the request variable will contain it unencoded.. Dec 18, 2007 12:41 AM|damieng|LINK I have a new post up on my blog entitled 5 signs your ASP.NET application may be vulnerable to HTML injection if anyone is interested in the subject (it affects WebForms and HtmlControls too). Dec 18, 2007 08:46 AM|SteveSanderson|LINK Rob (and the others), thanks for giving this issue such careful consideration. I appreciate that you're trying to do the right thing by "enabling security by default". Many arguments could be made, but for me the key thing is "what kind of a future are you creating". As you're in the priviledged position of designing a Microsoft-endorsed framework, the mindset you take is going to influence countless web developers for many years to come (otherwise, this would just be a minor technicality and I wouldn't really care either way). If. Do you think they are going to behave differently when working with different data sources? It just creates unpredictability, instead of the simple rule: "escape any strings that you don't want to render as HTML". In other words, it only enables an illusion of security, and ultimately causes a greater loss of security (as well as millions of wasted person-hours trying to remember which pieces of data are pre-encoded and which ones aren't). So yes, it does boil down to responsibility - responsibility for our future, and our children's future... ([+o(]) What I would ultimately like, though I appreciate this would turn a few things upside-down, would be to change the meaning of <%= ... %> on MVC ViewPages, so it escapes the strings you pass it. You would force developers to use more keystrokes when they want to avoid escaping (instead of fewer), maybe using <%!= ... %> or even <%= RawHtml(...) %>. robconeryHowever you're talking about a 1% issue at best (shared DB input) and many architects would completely cringe at sharing a DB Considering the other comments posted, the people who hang out on this forum are somewhat architecturally minded - sharing databases, legacy data storage, and interacting with external systems aren't 1% issues for us - it's what we do every day. Perhaps we're not representative of your wider customer base, but we are the opinion shapers. robconeryOne thing you can do here is to Encode on the way out - but again that's a perf thing you'd need to think about Have you done any benchmarking of this? As a quick test, my humble desktop can HTML-encode 1.5 million 30-character strings per second (in which about every 5th character needs encoding), and about half of that processing time goes into allocating a new string on the heap. Compared to the cost of a database query, a few hundred encodings is completely insignificant, and if you're pushing your webserver that hard, I'd hope you're using output caching anyway. robconeryUpdateFromEncode(Request.Form) Yeah, great! Or just, UpdateFrom(Request.Form, Encoding.HtmlEncodeAllFields), as long as the default is not to encode. Dec 18, 2007 09:21 AM|damieng|LINK HTML encoding is an output-only issue - there should NOT be any facility to encode data going into the database. 100%, no exceptions, not even as an option the developer can specify. If you HTML encode data into the database you force web developers into writing unsafe code because if they do HTML encode now it will be double-encoded and will display as a mess of " etc. all over the screen/output/XML/RSS. Of course there are times when HTML is desired in the database - rich text might be one option - but that's a totally different game and in fact requires neither encoding or decoding which would actually break that. In those scenarios you require careful scrubbing to ensure only the tags you wanted in there get kept. You effectively turn what was a simple rule - encode data into the output stream correctly - into a guessing game by doing this. Dec 18, 2007 11:14 PM|nagir|robconery|robconery|damieng|abombss|robconery|abombss|robconery|robconery|abombss. Dec 19, 2007 06:14 PM|robconery|LINK I'm talking to Phil about an operator overload that could do just this - it's a pretty sweeping change but I think it makes sense. So one of the two could happen, we could overload ! to encode everything, leaving = as unencoded, or the opposite. Rails uses "h" as they prefer not to get in the way (it seems). Does anyone have a feeling on this? Dec 19, 2007 06:19 PM|SteveSanderson|LINK Whew, glad we got past all the name-calling! The error-message scenario you mention is a good one to consider, but please recognise this is just a special case. The protection you're proposing isn't going to help if, rather than using UpdateFrom(), the coder has user myObject.Value = Request.Form["something"], nor will it help if they are echoing back something from the querystring, from a cookie, a user-agent string or whatever. These are more common cases. In other words, this is a bigger problem and UpdateFrom()-with-encoding doesn't help, it just muddies the waters and prevents anyone from learning the rule that output should be encoded. I hate the idea of that confusion (not to mention the basic architectural wrongness of it) - pre-encoding sounds like a disaster in the making. There are so many benefits to the encode-on-display method that I hope you don't let this odd special case get in the way. I appreciate your earlier points that you did propose to enable an option not to encode, but what many of us have learned over the years is that the only thing that matters is defaults - this isn't the open-source world where devs make intelligent choices on their own, remember! Coming back to the idea of changing the meaning of <%= ... %>, which would actually solve the problem in a much bigger way, I've written up some ideas in a blog post, including a demo implementation of the behaviour and mechanism for retaining the same MVC Toolkit syntax. Not sure what you meant about <pre> and <code> blocks - could you elaborate? Is a change to <%= ... %> too radical a step, or does the MVC framework give you an opportunity to truly improve matters? Dec 19, 2007 06:51 PM|robconery|LINK For all to know - I've been on an internal discussion for the last day on this, and this thread is being followed :). This discussion means something for all who feel you're not being heard :). SteveSandersonThe protection you're proposing isn't going to help if, rather than using UpdateFrom()... Yes - agreed. SteveSandersonpre-encoding sounds like a disaster in the making Again - I understand this - and I'm suggesting we force anything on anyone. All I want at the end of the day is the most secure solution (primarily) that is as close to acceptable and reasonable as we can get. Security in some ways leads to more work. SteveSandersononly thing that matters is defaults - this isn't the open-source world where devs make intelligent choices on their own, remember! Which is my point entirely. If you default to the secure side, you're safer. I understand (once again) the ramifications of that thought and please know it's part of the ongoing discussion. One solution offered is to not have a default and go with a 50/50 option: UpdateFromEncoded() and UpdateFromRaw() - naming TBD :). SteveSandersonIs a change to <%= ... %> too radical a step, or does the MVC framework give you an opportunity to truly improve matters? Initially I was thinking this might be doable but it actually can be problematic. I've asked Phil to weigh in on it so I'll let him respond. Dec 19, 2007 06:52 PM|damieng|LINK As people have said encoding just in UpdateFrom leaves many other scenarios and avenues open for attack so we need a broader solution. When I argued for <%= %> encoding at MS last month I was told that this would likely be out of scope because it would require work on the ASPX engine. I'm not sure what magic Steve has come up with on this SafeEncodingHelper but it looks like something we should be investigating if it avoids such changes. The ideal scenario I put forth was that: <%= %> should call a method such as Encode(string output) on ViewPage and that a new HtmlViewPage class becomes the default which overrides this to call HttpUtility.HtmlEncode. The advantage is that when writing views to create non-HTML content you could use the same syntax with an alternate encoding mechanism, i.e CsvViewPage that would implement an Encode method to escape double-quotes and commas etc. Dec 19, 2007 07:23 PM|Haacked|LINK I personally agree that incoming data should not be encoded automatically in general. I've worked on multiple systems in which the same data needed to be formatted for multiple outputs, not just HTML. From my experience it's actually quite common. Aside: One crazy idea is to have an encoded column and a raw column for each displayable field. I don't like it personally, but just tossing that out there. So let's focus on the output situation. The question that was asked is if we can override <%= %> to Html Encode output.. There are two approaches I can think of that might not require changes to the underlying ASP.NET forms engine (which would be a huge breaking change).? From this thread, I get the vague sense that people here are saying yes! [;)] One question for you: Would it make more sense to not change the semantics of <%= and introduce <%!= as the encoded version? Or perhaps <%%= (since % is an encoding character and might make more sense semantically?) The reason I bring this up is that <%= has a looooong history in multiple template engines, not just ASP.NET. For example, RoR does not automatically encode <%=. What would cause the least surprise for developers? As for whether we include it in ASP.NET MVC, I'm sure there are issues I haven't even thought about. I personally think it's worth considering if its possible without huge underlying changes. It does seem to adhere to the general security principle of exposing the least surface area and requiring opt-in when exposing something unsafe. ASP.NET MVC Dec 19, 2007 07:35 PM|damieng|LINK I'm for changing <%= default behaviour to cause HTML encoding by default because I believe Microsoft should be secure by default which I thought was their stance since IIS6 - even if it does mean breaking or knowing things (i.e. switching on ASPX ability) If they are worried about breaking existing solutions then switch it on in the web.config as default for new projects via the MVC VS templates. How easy is it to make it contextually aware? I deally if <%= %> is filling in an attribute of a HTML tag it should end up calling HttpUtility.HtmlAttributeEncode rather than ending up at HttpUtility.HtmlEncode. I covered various ASP.NET HTML injection pitfalls at my blog. The proposed solution covers #1 and potentially could cover #2. Microsoft needs to get a patch out for #3 (a bug) and consider a patch for #4/5 (probably by design). [)amien Dec 19, 2007 08:54 PM|shinakuma|LINK HaackedWhat would cause the least surprise for developers? I understand the argument for making it the default (<%= %>), but I think the least amount of surprise will be introducing <%!= %> as encoding, since none of the other frameworks do encoding by default. would be a surprise for someone not to expect that. Dec 19, 2007 09:00 PM|damieng|LINK It would be of both least surprise and of least use letting developers continue unaware and unhindered in developing web applications open to vulnerability. If security is considered nothing more than an inconvenience by all means keep it quiet and out the way. Personally security rates more highly than a 5 minute learning curve. [)amien Dec 19, 2007 09:47 PM|robconery|LINK Good discussion guys - I think we're coming around to the gravity of the whole thing. I wrote a post about it, diving into a bit more of my position on this: I don't want anyone here to think that The thing that we (and our larger developer audience) need to consider is the default stance - and then how to execute it. Let's keep this rolling... Dec 19, 2007 10:07 PM|nagir|LINK I think <%=o.Subject%> is not related in any way to content of the o.Subject. It is only presentation of o.Subject. Nothing more. If we force UI (HTML) related things to o.Subject (via automatic Encoding), the separation of concerns in MVC seems to be broken a bit. Developer should manually control XSS problems and manually encode <%=o.Subject%>. No one framework can handle all XSS problems. Any developer anyway will be able to emit unsafe HTML. I propose having some kind of extension: <%= o.Subject.ToHtmlText()%> Advantages: Disadvantages: Regards, Dmitriy. Dec 19, 2007 11:25 PM|ben2005uk|LINK I've been thinking about this for the a while now. When I looked at Ruby on Rails and security, I was surprised to see that it didn't automatically encode the output. It was a prefect opportunity to start making websites secure by default and sadly even with h() being very simply to implement, in books its still only discussed around chapter 6-7. I'm for secure by default, however it does come at a cost of maybe developers not being aware of the issues involved. However, those developers would also be the developers releasing insecure applications anyway. By having secure by default, we are protecting against those people, or should I say we are protecting users from those people. I also don't think we should be against changing the way <%= works due to the way it worked in the past / in other frameworks. If its wrong, we should change it..... For me, I would like to see: <%= Encoded %> <%!= Not Encoded %> ASP.net 2.0 auto encodes for GridView etc and no one seems to complain.... Oh, on a sidenote. HtmlUtility.HtmlEncode is not the preferred way of securing your application as it uses blacklisting instead of whitelisting. No reported problems in 2.0 (there was in 1.1) but Microsoft have released the AntiXSS Library as the preferred approach... :) Dec 19, 2007 11:27 PM|Haacked|LINK @Damien The developer does have to take some culpability in security as well. I don't think it's a fair assessment to assume not wanting to change the behavior of <%= is due to a lack of awareness or attention to security. It's not such a black and white decision. We've had some interesting discussions internally sparked by this thread. One point I should bring up is that <%= %> is neither inherently secure nor insecure. It's a shorthand for <% Response.Write() %>. Should we automatically encode Response.Writes now? Certainly not. Here's another thing to chew on. Suppose we change <%= to html encode just for MVC. What happens when you have projects with both WebForms and MVC templates in the same project? Inconsistency is just as bad (if not worse) for security as requiring opt-out. Now, when you're on some pages, <%= automatically encodes while other pages <%= doesn't encode. That's not a good situation. One might conclude that <%= should be a universal change across ASP.NET. While I don't take security lightly, I also don't take a massive breaking change across nearly every site that uses ASP.NET lightly either. Here are some ideas for improving the situation: After all, even if we did do <%= we haven't really prevented very common XSS attack avenues. For example, sites that allow users to submit HTML and display HTML. Encoding doesn't help in those cases. Only HTML scrubbing, white listed html tags, etc... For example, we might consider a ToSafeHtml() extension method that doesn't encode HTML, but strips out common exploit tags. Or .ToSafeHtml(string[] allowedTags); In any case, this is a very interesting discussion and thinking about helping to prevent XSS is certainly on our radar. Ultimately though, I think providing consistency and not too much magic under the hood is required. We could do all the magic in the world, and a bad developer will always be able to write a page with an exploit. By at least remaining consistent, good developers know what to expect and can apply tried and true practices for writing secure web pages without worrying about the framework circumventing their efforts. Speculating, but I imagine that's why RoR and other frameworks chose to not encode <%=. Dec 19, 2007 11:40 PM|abombss|LINK The more I read the thread and think about it, the more it makes sense not to change the default behavior. HaackedThe developer does have to take some culpability in security as well +1 My feeling is, keep as is and don't encode any input. If Microsoft wanted to include an extension for encoding with <%!= thats cool, otherwise I am sure MVC Contrib could pick up something like that too. This is something that should be consistent with other frameworks, not innovative or creative... changing this will just makes things confusing. Another good tool would be an httpmodule that could filter output and throw warnings for potential xss attacks when in a test environment. Not perfect but certainly better than nothing. P.S. If you are thinking about working some magic with the Asp.Net compiler think about this too. Dec 20, 2007 12:04 AM|ben2005uk|LINK Phil, You make some very good points. No solution is fully secure (ValidateRequest has a number of holes) and I have to say I didn't think about WebForms + MVC in the same project which does put a different view on the idea of changing <%. The solution needs to be simply and easy for the newbie to find. If its an external method (like HtmlEncode) then they are unlikely to come across it unless they go looking at security - I wonder how many developers bypass that topic. I have saw a number of rails applications which have not used the h() simply because the developers wasn't aware of XSS, so even making it simple doesn't mean it will be implemented. This then comes down to your point about making sure all the samples are secure. Too many books publish security flaws in their samples. I tried to ask the rails team their decision not to be secure by default, I forget the extract quote but I think it was something like its upto the developers to make their applications secure and follow best practices, we don't want to enforce what they should and shouldn't do. (from memory) Dec 20, 2007 12:54 AM|damieng|LINK @Phil: Absolutely the developer should be taking some responsibility but one oversight is all it takes. I've been encoding my HTML since '99 and have still missed it a few times in ASP and now in ASP.NET because of the src/img/href issue in HtmlControls. There are so many changes between the MVC stack and WebForms such as loosing server-side controls, viewstate, postback, events that adding encoding by default to <%= %> is going to be a footnote in comparison. You're right we shouldn't encoded Response.Write but I think we do need a strategy for building HTML from inside code for controls/helpers. I think the HtmlControls are a good start although better constructors and that bug fix would be needed. I think a solution such as Steves whereby you can specify an option to enable it in the web.config for both MVC and ASP.NET applications switched on for MVC because it's new and the right thing to do. Whether it is switched on by default for new ASP.NET projects is something for Microsoft teams to think about but being able to switch it on for those is a good start. I'm not sure ToEncode or ToHtmlEncode add anything other than people attempting to write out HTML from code using strings rather than a recommended set of controls designed for building HTML. It's still easy to get things wrong such as standards compliance and the whole thing would fall under the 'Primitive Obsession' smell because we are thinking too much about the serialisation format (string) rather than a logical abstraction (dom / htmlcontrols). Robust supplied .NET functionality for white-listing HTML would be fantastic, +1 on that. I don't think we can draw from the RoR philosophy and do nothing. As RoR matures as a platform I think they are going to come back and regret that decision - I bet there are exploitable RoR systems out there already. [)amien Dec 20, 2007 04:03 PM|SteveSanderson|LINK Thanks again to everyone putting effort into discussing and thinking this through. I'd love it if you achieved "minimum keystrokes == maximum safety", so I have a strong preference that <%= ... %> should encode its output. Yes, it is a breaking change, but ASP.NET has had breaking changes in the past and the world didn't end. When request validation was shipped as an automatic update in .NET 1.1, the first my last company knew about it was when the production web app started breaking. That was unpleasant, but they changed the web.config and got on with business. What you're proposing here is far less dramatic - this is a whole new platform which nobody even has in production yet. And you could enable changing <%= ... %> back to its old behaviour in web.config. As Damien points out, this is nothing compared to the breaking of nearly all existing web controls, which has no workaround (which I totally understand and support). If this isn't your perfect opportunity to make a big improvement to security, I fear there will never be one. What do you think about the idea of not actually forcing the developer to choose between encoding and not encoding - and letting the framework make the choice by default? It could be determined by the type of the evaluation result. If it's a plain old string, encode it, if it's a special variant on string (let's call it RawHtml), then don't encode it. The HTML helper methods would return RawHtml of course. Sounds weird, but the key point is that it makes it very difficult for the developer to do the wrong thing. They just write <%= ... %> and the right thing happens, except in the rare case where they want to print HTML verbatim *without* using a HTML helper method, in which case they write <%= (RawHtml)value %>, or <%= value.toRawHtml() %> - a deliberately non-concise syntax to discourage unnecessary use. Even then it chose the safe default until they added the typecast. I know it's less obvious at first but it's very simple when you know it. This is what I implemented in my demo by the way. In my view this is more enlightened than NVelocity's style of forcing the developer to manually choose between $ and $! all the time (they're just one keystroke different, you can pick the wrong one without thinking about it). But even if you go with the manual choice approach (with <%!= ... %>), this could be one of the best features of ASP.NET MVC. Dec 20, 2007 04:57 PM|ghotiman|LINK I'm not too fond of encoding the input by default for all the reasons already mentioned. I like the idea of adding to <%=%>, but not changing it. As others have said, that would cause some confusion. If something like <%% = %%> did HTML encoding by default it would not break the old model, and it would get used since it's easy. Also, it would be an opportunity to educate developers on XSS. Every one would say to always use <%% = %%> and when devs asked why they could learn about XSS. Education on the matter is probably more important than the framework handling everything. I also like the idea of having extension methods to handle the different encodings for HTML, XML, and JavaScript. They are discoverable and easy to use. Dec 20, 2007 05:15 PM|SteveSanderson1|LINK Dec 20, 2007 07:22 PM|ghotiman|LINK SteveSanderson1, I don't care to much what the syntax should be, just that it be different than the current <%= %>. If they change the behavoir of <%= %> then most of the developers who need to be educated on this will never know anything about it. Also, there will be the inconsistant behavior between forms and mvc, or old code will break. If there is a new syntax, it can serve as the talking point for XSS. The new syntax should be easy, I think everyone can agree on that. I just think it should be different. Dec 20, 2007 09:18 PM|Jonathan Holland|LINK It absolutely baffles me to think that anyone would encourage default encoding. I know not everyone here has worked in PHP, but that language is a unorganized mess because of features such as "Magic_Escape_Strings" and "strip_Slashes" etc. The lesson learned? Leave the encoding to be done by the developer, not the framework implementation. We are all professionals here right? There is no need for hand holding. Dec 20, 2007 09:40 PM|damieng|LINK It is incredibly easy to miss or forget with alternate syntax, especially if you also maintain ASP.NET which won't have the new syntax. If you could rely on everybody being professional you wouldn't have this problem - the fact is you can't rely on that. As for hand-holding the fact is the majority of the time <%= %> is used to output simple text not HTML building. [)amien Dec 20, 2007 09:44 PM|Jonathan Holland|LINK So if you must have default encoding, what is so hard about default being off, and just having a config section in web.config for it? It seems like the convention over configuration concept is being taken too far, configuration files are not all that bad :) Dec 20, 2007 09:48 PM|damieng|LINK We can surely agree the root of the problem is ignorance? In which case defaulting to off or alternate syntax achieves nothing. They didn't know HttpUtility.HtmlEncode and now they won't know <page defaultOutput="Encoded" /> either. [)amien Dec 20, 2007 09:55 PM|Jonathan Holland|LINK I believe that the only responsibility of Microsoft is to provide the means to encode and decode HTML. The responsibility to use it is placed at the feet of the developer. Sure, ignorance leads to crappy, vulnerable sites....But that is not Microsoft's fault, and that is not really their problem. As you can see from the PHP community, default features such as this only provide a false sense of security and enable the crappy developer to continue to develop crappy sites. It does not magically turn them into good developers. Would you tell the ADO.NET team to only allow parameterized queries? Every decent developer knows better than using string concatenation to build a query, but you will never be able to convince the ADO.NET team that removing the ability to do queries that way is a good idea. I want a framework, not a set of training wheels without a bike. Dec 20, 2007 10:25 PM|damieng|LINK I think then you are missing the point of .NET with it's sandboxed VM, code access security, type safety, bounds checking, pointerless operations, garbage collection, trust levels... [)amien Dec 20, 2007 10:32 PM|Jonathan Holland|LINK damieng I think then you are missing the point of .NET with it's sandboxed VM, code access security, type safety, bounds checking, pointerless operations, garbage collection, trust levels... [)amien Your right, lets just add Html Encoding at the CLR level. Encode all strings! Apples to Oranges. Dec 22, 2007 05:36 PM|tgmdbm|LINK I'm all in favour of trying to eliminate all those poorly developed sites. And if we can take a huge bite out of them by html encoding on input then it's possibly not such a bad idea. However, I'm developing a WinForms interface which accesses the same database so encoding on input is obviously not an option. The question then is "which to do by default?". Well, if encode on input is OFF by default, will a novice turn it on? I'm not so sure that they would. If they are lazy enough not to bother about security they aren't even going to care that such an option exists. If it's ON by default, will we turn if off? Of course we will. We'll check the comments of our web.config and turn it off. All we need is good documentation! To be honest I'm not too concerned about which way they implement it as long as its extensible, overridable, configurable, and most of all it should be obvious what it's doing. Dec 22, 2007 05:57 PM|damieng|LINK I presume you mean encode on output - I'd agree with the sentiments. Encode. [)amien Member 227 Points Dec 23, 2007 12:19 AM|sergiopereira|LINK Great thread. Nice to see how this discussion was brought back from a down spiral. I'd like to add that although security is a cross-cutting concern, it needs to be dealt in each component at the component's context. By that I mean, if the UI needs to be secure (it does) then UI security measures need to be taken in the UI code (HtmlEncode in the outputs for example), never let UI concerns happen at the controller level (if you see any HtmlEncode calls in the controller code, think about it a little more.) And, please, no UI encoded stuff in my database, OK? :) An example of security concern that could be dealt at the controller level would be to inspect the user input before assigning it to the models and later to the database. In practical terms a good example of that is making sure only the fields you expect to be in the Response.Form gets populated in the model, so be careful on how you use myModel.UpdateFrom(Request.Form) so that you don't allow hand-crafted form posts to update sensitive properties. All in all, I think we are all getting to the same page now. - sp Dec 25, 2007 05:23 AM|robconery|LINK damiengEncode. One thing I'd like to reiterate at this point in the thread is that I completely agree with no encoded data in the DB. My point (and others who like the idea of encoding on input) is that you protect one of the main vectors of XSS attack - regurgitation of input to the screen (search results being one of the main culprits). So, to be clear: no one is suggesting you must input encoded text into your Db. Especially me. This discussion started with regards to a method that binds an object from Request.Form and the decision to encode/decode being your or ours. Dec 25, 2007 06:00 PM|FCsteve|LINK I'd like it to be overloaded.. but by default I would prefer not to encode.. I can kind of see the reason for the default to be encoded.. defaults targetting the most common scenario.. and I imagine you would love your 'product' to do as much as possible for you by default.. but stay highly custimizable and configurable.. Either way I wouldn't be too bothered what the default is as there is some option.. as otherwise it would just add to the code in .NET that becomes useless outside of its default scenario.. (disclaimer: most of the code in .NET I think it done great).. My personal argument for the output encoding is that it should be handler by the output generators.. but it would be great if we had a simpler way to do primative output encoding (such as the <%!= idea). 61 replies Last post Dec 25, 2007 06:00 PM by FCsteve
http://forums.asp.net/p/1194407/2060742.aspx?Re+UpdateFrom+and+Encoding
CC-MAIN-2014-42
refinedweb
6,970
63.8
On Wed, 2002-11-06 at 05:43, Alan Cox wrote:> On Wed, 2002-11-06 at 02:31, john stultz wrote:> > I'm fine w/ the X86_TSC change, but I'd drop the X86_PIT for now. > > > > Then make the arch/i386/timers/Makefile change to be something like:> > > > obj-y := timer.o timer_tsc.o timer_pit.o> > obj-$(CONFIG_X86_TSC) -= timer_pit.o #does this(-=) work?> > obj-$(CONFIG_X86_CYCYLONE) += timer_cyclone.o> > Not everything is going to have a PIT. Also I need to know if there is a> PIT for a few other things so I'd prefer to keep it, but I'm not> excessively botheredHmmm. Ok, How about something like what is below? This is very similarto what James is suggesting, but tries to fix some of the corner casesas well. The only problem I see with this is that in some places we'reusing _X86_PIT_TIMER as an imagined !_X86_TSC_ONLY, so one couldn't havea kernel that compiled in the Cyclone timer, not the PIT timer, andallowed one to disable the TSC. I'm still not sure this is the way to go, but at least gives James achance to poke at my code rather then the other way around. thanks-johndiff -Nru a/arch/i386/Kconfig b/arch/i386/Kconfig--- a/arch/i386/Kconfig Mon Nov 4 17:15:15 2002+++ b/arch/i386/Kconfig Mon Nov 4 17:15:15 2002@@ -430,6 +430,11 @@ depends on NUMA default y +config X86_PIT_TIMER+ bool+ depends on !X86_TSC || X86_NUMAQ+ default n+ config X86_MCE bool "Machine Check Exception" ---help---diff -Nru a/arch/i386/kernel/cpu/common.c b/arch/i386/kernel/cpu/common.c--- a/arch/i386/kernel/cpu/common.c Mon Nov 4 17:15:15 2002+++ b/arch/i386/kernel/cpu/common.c Mon Nov 4 17:15:15 2002@@ -42,7 +42,7 @@ } __setup("cachesize=", cachesize_setup); -#ifndef CONFIG_X86_TSC+#ifdef CONFIG_X86_PIT_TIMER static int tsc_disable __initdata = 0; static int __init tsc_setup(char *str)@@ -55,7 +55,7 @@ static int __init tsc_setup(char *str) {- printk("notsc: Kernel compiled with CONFIG_X86_TSC, cannot disable TSC.\n");+ printk("notsc: Kernel not compiled with CONFIG_X86_PIT_TIMER, cannot disable TSC.\n"); return 1; } #endifdiff -Nru a/arch/i386/kernel/timers/Makefile b/arch/i386/kernel/timers/Makefile--- a/arch/i386/kernel/timers/Makefile Mon Nov 4 17:15:15 2002+++ b/arch/i386/kernel/timers/Makefile Mon Nov 4 17:15:15 2002@@ -5,7 +5,7 @@ obj-y := timer.o obj-y += timer_tsc.o-obj-y += timer_pit.o+obj-$(CONFIG_X86_PIT_TIMER) += timer_pit.o obj-$(CONFIG_X86_CYCLONE) += timer_cyclone.o include $(TOPDIR)/Rules.makediff -Nru a/arch/i386/kernel/timers/timer.c b/arch/i386/kernel/timers/timer.c--- a/arch/i386/kernel/timers/timer.c Mon Nov 4 17:15:15 2002+++ b/arch/i386/kernel/timers/timer.c Mon Nov 4 17:15:15 2002@@ -8,7 +8,7 @@ /* list of timers, ordered by preference, NULL terminated */ static struct timer_opts* timers[] = { &timer_tsc,-#ifndef CONFIG_X86_TSC+#ifdef CONFIG_X86_PIT_TIMER &timer_pit, #endif NULL,-To unsubscribe from this list: send the line "unsubscribe linux-kernel" inthe body of a message to majordomo@vger.kernel.orgMore majordomo info at read the FAQ at
https://lkml.org/lkml/2002/11/6/261
CC-MAIN-2014-10
refinedweb
519
56.35
This instructable describes an approach to read temperature and humidity data from a RuuviTag using Bluetooth with a Raspberry Pi Zero W and to display the values in binary numbers on a Pimoroni blinkt! pHAT. Or to put it short: how to build a state of the art and a bit nerdy thermometer. The RuuviTag is an open source sensor bluetooth beacon that comes with a temperature/humidity/pressure and accelation sensors, but may also act as a standard Eddystone™ / iBeacon proximity beacon. It was a very successfully Kickstarter project and I got mine a few weeks ago. There is a Github with python software to read the RuuviTag using a raspberry, and I have used one of their examples, with some additions. The Raspberry Pi Zero W is the latest member of the RPi family, basically a Pi Zero with Bluetooth and WLAN added. The blinkt! pHAT from Pimoroni is basically a strip of eight RBG LEDs configured as a HAT for the Raspberry Pi. It is very easy to use and comes with a python library. The idea was to read the data from the RuuviTag and display it using the blinkt! HAT. The values are displayed as binary numbers using 7 of the LEDs, while the eight one is used to indicate if humidity or temperature (+/-/0) values are displayed. Step 1: Setting Up the System Setting up the system is easy: - Switch on the RuuviTag (RuuviTag temperature sensor version) . - Set up your RPi Zero W, RPi3, or any other RPi with bluetooth capacity added, following the instructions on. - Place the blinkt! HAT on the RPi (while off). - Install the blinkt! and RuuviTag software, as indicated on the corresponding GitHub pages. - You now have to identify the MAC address of your RuuviTag - copy the attached Python program, open it with IDLE for Python 3 - change the MAC address of the RuuviTag to yours, then save and run the program. - feel free to modify and optimize the program. The program comes as it is, to be used on your own risk, no liabilities are taken for any damages. Step 2: The Device and the Program As mentioned above, the idea was to construct a simple and inexpensive system to read data from the beacon and display numerical values on the blinkt! HAT, or a similar LED strip. The range of values for temperature to be measured with a RPi based system will in most cases be somewhere between - 50°C and +80°C, for humidity between 0 and 100%. So a display that can give values from -100 to +100 will be sufficient for most applications. Decimal numbers smaller as 128 can be displayed as binary numbers with 7 bits (or LEDs). So the program takes the temperature and humidity values from the RuuviTag as "float" numbers and transforms them into binary numbers, which then are displayed on the blinkt!. As a first step, the number is rounded, analysed if positive, negative or zero, and then transformed into a positive number using "abs". Then the decimal number is converted into a 7-digit binary number, basically a string of 0s and 1s, which gets analysed and displayed on the last 7 pixels of the blinkt!. For temperature values the first pixel indicates if the value is positive (red), zero (magenta) or negative (blue). Displaying humidity values it is set to green. To simplify the discrimination between temperature and humidity values the binary pixels are set white for temperature and yellow for humidity. To enhance legibility of the binary numbers, "0" pixel are not turned completely off, but instead are set much weaker than in the "1" state. As blinkt! pixels are veery bright, you can set the general brightness changing the parameter "bright" The program displays the values and parts of the process also on screen. In addition you will find several muted (#) print instructions. I left them in, as you may find them helpful to understand the process if unmuted. The values might also be stored in a log file. Step 3: Program Code The code was a bit debugged and optimized. You may now find version 3 (20_03_2017). ' This program is intended to read the temperature, humidity and pressure values form a RuuviTag ' ' and to display the temperature and humidity values as binary numbers on a Pimorini blinkt! HAT. ' '' ' It is based on the print_to_screen.py example from the ruuvitag library at github. ' ' Requires a Pi Zero W, Pi 3 or any other RPi equiped with bluetooth and all neccessary libraries installed.' import time import os from datetime import datetime from ruuvitag_sensor.ruuvi import RuuviTagSensor from blinkt import set_clear_on_exit, set_pixel, clear, show def temp_blinkt(bt): # this routine takes the temperature value and displays it as a binary number on blinkt! clear () # color and intensity of "1"pixels : white r1 = 64 g1 = 64 b1 = 64 #color and intensity of "0" pixels : white r0 = 5 g0 = 5 b0 = 5 # Round and convert into integer r = round (bt) # vz represents algebraic sign for indicator pixel if (r>0): vz = 1 # positive elif (r<0): vz= 2 # negative else: vz= 0 # zero # print (vz) i = abs(r) #print (i) # transform to absolute, 7-digit binary number i1 = i + 128 # for i<127 -> results in a 8-digit binary number starting with 1 # print (i1) b = "{0:b}".format(i1) # convert to binary # print (b) b0 = str (b) # convert to string b1 = b0[1:8] #truncate first bit print ("binary number: ", b1) # Set pixels on blinkt! # set binary number for h in range (0,7): f = (h+1) if (b1[h] == "1"): set_pixel (f, r1, g1, b1) # print ("bit ", h, " is 1, pixel ", f) else: set_pixel (f, r0, g0, b0) # print("nil") # Set indicator pixel if (vz==1): set_pixel (0, 64, 0, 0) # red for positive values elif (vz==2): set_pixel (0, 0, 0, 64) # blue for negative values else: set_pixel (0, 64, 0, 64) # magenta if zero show() # end of temp_blinkt() def hum_blinkt(bh): # this takes the humidity value and displays it as a binary number on blinkt! clear() # color and intensity of "1" pixels: yellow r1 = 64 g1 = 64 b1 = 0 #color and intensity of "0" pixels : r0 = 5 g0 = 5 b0 = 0 # Round and transform into integer r = round (bh) # transform to absolute, 7-digit binary number i = abs(r) #print (i) i1 = i + 128 # for i<127 -> gives a 8-digit binary number starting with 1 # print (i1) b = "{0:b}".format(i1) # print (b) b0 = str (b) b1 = b0[1:8] #truncate first bit print ("binary number: ", b1) # Set pixels on blinkt! # set binary number to pixels for h in range (0,7): f = (h+1) if (b1[h] == "1"): set_pixel (f, r1, g1, b1) else: # mute to blank LEDs set_pixel (f, r0, g0, b0) # mute to blank LEDs # Set indicator pixel set_pixel (0, 0, 64, 0) # green for humidity show() # end of hum_blinkt() set_clear_on_exit() # Reading data from the RuuviTag mac = 'EC:6D:59:6D:01:1C' # Change to your own device's mac-address print('Starting') sensor = RuuviTagSensor(mac) while True: data = sensor.update() line_sen = str.format('Sensor - {0}', mac) line_tem = str.format('Temperature: {0} C', data['temperature']) line_hum = str.format('Humidity: {0} %', data['humidity']) line_pre = str.format('Pressure: {0}', data['pressure']) print() # display temperature on blinkt! ba = str.format('{0}',data['temperature']) bt = float (ba) print (bt, " °C") temp_blinkt (bt) print() time.sleep (10) # display temperature for 10 seconds # display humidity on blinkt! bg = str.format('{0}',data['humidity']) bh = float (bg) print (bh, " %") hum_blinkt (bh) print () # Clear screen and print sensor data to screen os.system('clear') print('Press Ctrl+C to quit.\n\n') print(str(datetime.now())) print(line_sen) print(line_tem) print(line_hum) print(line_pre) print('\n\n\r.......') # Wait for a few seconds and start over again try: time.sleep(8) except KeyboardInterrupt: # When Ctrl+C is pressed execution of the while loop is stopped print('Exit') clear() show () break Participated in the Sensors Contest 2017 Participated in the Microcontroller Contest 2017 Discussions
https://www.instructables.com/id/RuuviTag-and-PiZero-W-And-Blinkt/
CC-MAIN-2019-30
refinedweb
1,334
59.23
My domain is: chux.info I ran this command: import requests import json url = "" headers = {'Content-Type':'application/json'} payload = { <redacted> } cert_file = 'chux-info-cert.pem' r = requests.post(url, data=payload, headers=headers, verify=cert_file) print(r) It produced this output: ssl.SSLError: ("bad handshake: Error([('SSL routines', 'tls_process_server_certificate', 'certificate verify failed')])",)` My web server is (include version): this docker, latest version: The operating system my web server runs on is (include): 1.3.0 My issue is I have a remote API I want to use, and they required me to get a static IP and provide them that IP and a single domain certificate (e.g. not wildcard). So I set up on my home server (I run unraid on bare metal and then run dockers) the letsencrypt docker linked above. The cert generation worked great, I ended up with a directory of .pem files: cert, chain, fullchain, privkey and priv-fullchain-bundle. I sent the fullchain one to the remote API administrators along with my IP, and they claim to have set it up on their end. Well I keep attempting the python script above and just keep getting cert verify failed. I have tried all the various cert files given, and tried giving it as the cert= parameter instead of the verify= parameter. Any thoughts would be greatly appreciated. I’m a long time software developer but fairly ignorant of how certs work.
https://community.letsencrypt.org/t/remote-api-calls-with-certificate-failing/116154
CC-MAIN-2020-16
refinedweb
238
55.74
Vue vuelidate jsonschema Create validation definitions for vuelidate based on json schema Version: 0.13.4 Updated: 11/15/2017 By: mokkabonna License: MIT Downloads Last 30 Days: 1.4k Install Repository: CDNs bundle.run: jsDelivr: unpkg: vue-vuelidate-jsonschema Create vuelidate validation rules based on json schema Use the json schemas you already have for validating your api input to generate validation rules for vuelidate. And use default values to generate the data attributes. And title, description for your user interface. The goal is that if your vuelidate validation is valid then you will also pass validation against the json schema. So you can with confidence serialize your model to json and the server will accept it if it validates against the same schema. npm install vue-vuelidate-jsonschema --save Install plugin globally NOTE: if using this plugin as a global mixin, make sure to use it before you register Vuelidate. If no schema property is present neither this plugin nor vuelidate will be instantiated. Unless you have a validations object/function on your vm. import Vue from 'vue' import VueVuelidateJsonschema from 'vue-vuelidate-jsonschema' import Vuelidate from 'vuelidate' Vue.use(VueVuelidateJsonschema) Vue.use(Vuelidate) Local mixin You can use the local mixin like this: import VueVuelidateJsonschema from 'vue-vuelidate-jsonschema' export default { mixins: [VueVuelidateJsonschema.mixin] } Example export default { schema: { type: 'object', properties: { name: { type: 'string', pattern: '^\\w+\\s\\w+$' }, username: { type: 'string', minLength: 5 }, age: { type: 'integer', default: 20, minimum: 18, maximum: 30 } }, required: ['username'] } } Is functionally equal to: import {minLength, required} from 'vuelidate/lib/validators' import {pattern} from 'vue-vuelidate-jsonschema' export default { data() { return { schema: { name: undefined, username: '', age: 20 } } }, validations: { schema: { name: { pattern: pattern('^\\w+\s\\w+$') }, username: { required, minLength: minLength(5) }, age: { between: between(18, 30) } } } } Default data values If the property have a default value, that is always used. If it does not and the property is not required the value is set to undefined. If the property is required then the value is set to string: '', boolean: false, object: {}, array: [], null: null, and for both number and integer: 0 If allOf, oneOf, anyOf or not present If you have the following schema { type: 'object', properties: { prop1: { type: 'string', default: 'priority' } }, allOf: [{ type: 'object', properties: { prop1: { type: 'string', default: 'does not override default value in main schema' } } }, { type: 'object', properties: { added: { type: 'string', default: 'added' }, nodefault: { type: 'string' } } }] } We can with confidence also create data properties for added and nodefault. allOf acts in a way as a extension of the base schema. However for the not, oneOf, anyOf validators we don't consider the default values, we always scaffold with undefined as the value. We don't want any default values in one of these schemas to be filled in. They are also only scaffolded one level deep. If we didn't do this you would have to use Vue.set when adding new properties. Now we create them up front. Supported json schema validation rules All validators are supported. Validators are attached with the prefix schema. So required => schemaRequired Some notes: - allOf this does not add a validator, but it generates validators for all the provided schemas in allOf and merges them using the and validator. The individual validators are still added as schemaMinLength etc. But if more schemaMinLength for a property they are combined. - items, if items is a single schema, the $each property is used, if not then a custom schemaItems validator is used - type => schemaType, if array of types then schemaTypes The library is well tested. Test cases from draft v6 are used: Validation of the json schema itself This library does little to no validation of the schema itself. So if you have a property of type integer and define a minLength property (an unsupported validator for integer), that validator is actually added. There are loads of tools that do validation for you and this should be ideally be done at creation time of the schema rather than at runtime, adding overhead. Property schema exposure The schema for the property and any params are passed to all the validators and available like this: // $v.name.$params.schemaMinLength { type: 'schemaMinLength', min: 3, schema: { type: 'string', minLength: 3, maxLength: 30, title: 'Name', description: 'The name of the student.' default: 'John' ... } } This can be used to generate validation messages. patternProperties and additionalProperties You can't have patternProperties on a schema mounted to root. And additionalProperties must be undefined or true. This is because you will likely run into problems since the vue instance have many extra properties. In these cases, use a mount point. Items and $each validation All versions of the items property is supported. Single schema { type: 'array', items: { type: 'number', minimum: 3 } } We use vuelidate $each option. This works when items is any type. Multiple schemas { type: 'array', items: [{ type: 'number', minimum: 3 }, { type: 'object', properties: { name: { type: 'string', minLength: 3 } }, required: ['name'] }] } If the first item in the array are not a number with minimum value of 3 and item 2 is not an object with name and minLength of 3 then the array is invalid. We can't expose any errors on the object itself if present, due to vuelidates limitation with the use of the $each keyword that requires all objects to be the same. Required property in json schema context The required property in json schema only means that the property should be present. Meaning any value that matches the type or types. So adding the property to the required array does not apply the required validator in vuelidate. It adds a custom validator that only checks if the value is not undefined. A type validator is added that kicks in if the value is not undefined. uniqueItems Using uniqueItems in a json schema context means that the values are equal in terms of similarity. So an array with two similar objects violates the uniqueItems rule even though they are unique in terms of javascript object identity. Between validator If both the minimum and maximum properties are present a between validator is used. Override or extend validation You can override, extend or delete the validation rules on your vue vm like this: export default { schema: { type: 'object', properties: { name: { type: 'string', minLength: 5, maxLength: 30 } } }, validations: { schema: { name: { schemaMinLength: minLength(2), //overrides minLength 5 email, // adds email validator schemaMaxLength: undefined // removes maxlength validator } } } } This works also if your validations property is a function. Multiple schemas You can define multiple schemas that all adds their validation rules. Simply define schema as an array. export default { schema: [{ type: 'object', properties: { prop1: { type: 'string' }, conflict: { type: 'string', minLength: 3, maxLength: 5 } } }, { type: 'object', properties: { prop2: { type: 'string' }, conflict: { type: 'string', maxLength: 10 } } }] } This will add data/validation for prop1, prop2 and conflict. The later definition of conflict will be merged into the other definition. In the above example, the conflict property will still have the minLength validator. But also a maxLength validator of 10. Custom mount point By default the schemas are added to the schema property/validation structure. To attach them deeper down in the structure you can define a mount point: export default { schema: [{ mountPoint: 'deep.nested.structure', schema: { type: 'object', properties: { prop1: { type: 'string' } } } }, { mountPoint: 'other.deep.structure', schema: { type: 'object', properties: { prop2: { type: 'string' } } } }] } This exposes prop1 at vm.deep.nested.structure.prop1 and prop2 at vm.other.deep.structure.prop2 You can mount a schema to root by defining mountPoint: '.'. This is however not supported with async schemas, since we can't add reactive properties to the vue instance after init. Also sibling validators like additionalProperties or patternProperties makes little sense when added to the root as the root is full of additional vue properties. Promises and functions are supported, just define your schema like this: export default { schema: [ function loadSchemaOnCreate() { // functions must return a promise or a schema synchronously return fetchSchema('') }, // load schemas on module require, default mount point fetchSchema(''), { //this will throw on init, since we have async and root mount point mountPoint: '.', schema: fetchSchema('') } ] } Functions are called on the beforeCreate hook. If the schema config has any promises or any function return a promise, then the property $schema on the vm is a promise that will be resolved when all schemas have loaded. Then $schema will be replaced by the actual array of schemas. You need to use a v-if in your view to prevent the view from failing if you try to access data or validation properties that aren't created synchronously: <form v- <input v-model. </form> If one of your schemas contain a $ref property you can then resolve those manually in the promise or use json-schema-ref-parser to dereference your schema for you. Extract data The mixin adds a method getSchemaData that you can call to get all the data that a schema originally helped scaffold. vm.getSchemaData(vm.$schema[0]) This will include any property that is undefined, but you will get rid of them when you do JSON.stringify(). For schema at a mountpoint, you will get only the structure from that mountpoint. But if you have mounted several schemas on the same mountpoint or below you will get those included. If you call getSchemaData with an array of schemas you will always get a fully structured export from the root of your vm. Since you might have different schemas on different mountpoints. vuelidate error extractor I recommend to use vuelidate-error-extractor to display error messages. This takes the pain out of the manual labor of writing validation messages for each property and rule. Vue.use(VuelidateErrorExtractor, { messages: { schemaRequired: 'The {attribute} field cannot be undefined.', schemaMinLength: '{schema.title} must have minimum {min} characters.' ... } }) Roadmap - support all json schema validation properties - support loading of remote schemas - support $ref inside schemas (will not support, but added docs for resolving refs with third party module) - export own validators - more tests for really complex schemas - scaffold data, populate, serialize and test output against mainstream json schema validator (ajv) - document and test mounting procedure (multiple schemas in one vm) - possibly support and test circular $refs - better validation params for array items validation (when not object) - pass title, description etc to the validator as params (possibly whole property schema) - support standard format - allow registration of custom validators for custom formats PRs are welcome. Contributing Create tests for new functionality and follow the eslint rules. License MIT © Martin Hansen Contributors mokkabonna commits
http://tahuuchi.info/vue-vuelidate-jsonschema
CC-MAIN-2021-25
refinedweb
1,736
51.89
Tax Have a Tax Question? Ask a Tax Expert Welcome to Just Answer. I am here to help you resolve your tax and finance concerns. Please feel free to ask anytime you need extra help. Losses can only be claimed if they were attributed to previously taxed income. Accordingly, there is no loss here since you were never taxed on this. The same holds true for the legal fees. Sorry to have to give you bad news but it is usually better to know the reality than to live in a misunderstanding. Hello and thank you for your question. It is too early to determine and you may very well have a loss. It sounds like you're going to have to go back to court. If you get a judgement, you may find that the aunts owe you a debt that they may not be able to pay (bad debt equates to a loss for you / potential forgiveness of debt income to the aunts). However, was this not addressed initially, as you seem to have already been to court? Did title insurance apply? BotXXXXX XXXXXne, if you inherit a house you'll have a tax basis in that house equal to its fair market value on the date of the estate generally, and if you lose that house and have a loss that is not compensated for by insurance or otherwise, you'll have a deductible loss (IRC, aka internal revenue code section, 165). An inherited house is generally an investment property until it is sold, used for personal reasons, turned into a rental, etc. Furthermore, legal fees spent on defending/acquiring investment property are deductible generally. See here: . See also IRC 1014: How Current is- (1) the fair market value of the property at the date of the decedent's death, I hope this is helpful. Sorry to the above expert, but I don't agree. You, without a doubt, need someone that can get at your personal facts and circumstances, such as the court records etc. Simply telling you that you do not have a deductible loss or deductible legal fees is not appropriate. Thank you for your question! This is a situation where, in practice, I would ask for permission to speak directly to your attorney and obtain any official court records. I would look to determine the true and rightful owner of the home and investments at the time of the estate and proceed accordingly. Your attorney's fees in this case should be deductible under IRC 212:. As far as your theft loss goes, IRC 165 above would apply. Now for the tricky part. NOL (net operating losses) apply to theft and casualty losses. Let's start with an IRS pub, here (bolding mine): "Net operating loss (NOL). If your casualty or theft loss deduction causes your deductions for the year to be more than your income for the year, you may have an NOL. You can use an NOL to lower your tax in an earlier year, allowing you to get a refund for tax you have already paid. Or, you can use it to lower your tax in a later year. You do not have to be in business to have an NOL from a casualty or theft loss. For more information, see Publication 536, Net Operating Losses (NOLs) for Individuals, Estates, and Trusts." The tax code behind the above can be found here, in IRC 172: "(ii) Eligible loss For purposes of clause (i), the term "eligible loss" means- (I) in the case of an individual, losses of property arising from fire, storm, shipwreck, or other casualty, or from theft," Finally, if you can get a 1099C in your aunts' hands, that might be good. 1099C is for forgiveness of debt (ie... you don't sue for the house, but if you at least recognize a debt owed to you by your aunts, you can forgive that debt, solidifying a deductible bad debt loss for you and forgiveness of debt income to your aunts). If you don't claim this as a theft or other loss, the IRS could actually construe this as a gift too, in which case you would have to file a gift tax return (probably just a reportable, and not a taxable, gift, pending you specific facts and circumstances). Does it seem like you have a deductible loss over JustAnswers? Absolutely. While I realize you have spent $ already, I can assure you, it is worth a little more at this point to have a quality tax professional assist you. Schedule an appointment and come with your code sections handy (IRC 212, IRC 165, IRC 1014, and IRC 172 all above). I am very sorry for your loss... Hopefully you are are able to find some resolution. Thank you again for your question too! No problem here and thank you! The fair value of the house at the time of the estate is used. The fair value becomes the beneficiary's new basis in the home for tax purposes (sale price - basis = [taxable] gain/loss, should the beneficiary later sell). The tax value of the home and the fair value per tax documents probably are not accurate... The sale price of the home provides, assuming an arms' length transaction, the fair value of the home at the time it was sold, however, the determination still must be made at the time of the estate (ie... date of death). An appraisal is generally used at the time of the estate to help document that fair value. I do sincerely XXXXX XXXXX the best here. I understand this is probably frustrating...
http://www.justanswer.com/tax/4ew08-husbands-aunts-sold-fathers-house-when-assumed.html
CC-MAIN-2016-36
refinedweb
941
70.63
We Thanks 🙂 Could you write that post about requests/questions. I was very impressed with the IE9 presentations last week and I'm glad you put these up. But I'm very disappointed about the XHTML parsing and error handling. This blog post explains the issue: @Gaurav I commented on the linked blog post, but I'll reply here as well for completeness.. Hope that helps clear things up! i note that in order to see the videos you ask to install a "plugin" ( in 2010 ! a plugin! my god 😉 Please could you provide the same videos using the new video element in HTML5? Thanks in advance carlos ...which codec would you expect them to use to post the videos? If they post in h264, the Firefox kids complain. They don't seem likely to post in Theora format, given the IP fear. @carlos you can download them in a variety of formats here: wmv, high-bitrate wmv, and mp4. The plugin it wants you to install is silverlight for viewing inside the browser (which works a good deal better than flash does at the same job for me) Interesting presentations. I was surprised that Microsoft is adding image support for JPEG XR in IE9, yet there is no word on support for Animated PNGs (APNG) or MNG formats. Both of these formats are supported by other major browsers like Firefox. It would be nice if IE9 at least supported one of them... @ted: I'd categorize apng along with blink and animated gifs as another piece of technology the web doesn't need. Is IE9 going to support CSS3 calc()? Tony, thank you for clarification regarding display of XML parsing error messages in IE 9. I posed a couple of follow-up questions on the blog (one of them is difficult to reproduce here because it has a code example): @andrew, thank you for the links! @Ted: You are wrong, there is no more MNG support in Firefox… Neither do Opera or Webkit based browsers support this format. However APNG is supported by current Firefox and Opera versions. @JM: Currently, IE supports what are called "Dynamic Properties", which use Javascript to perform actions similar to calc(), but that's been deprecated and only works in compatibility mode. The calc() function is far simpler and doesn't use Javascript at all, making it easier to implement and less disruptive to a browser's security model. Currently, no browser supports calc(), although both Gecko and Webkit have tracking bugs with patches. It would be nice if the JPEG XR code was backported to IE8 as well. Please tell every presenter to TURN OFF their mobile devices before going on stage.. the static feedback is very annoying! This should be a known for any professional presenter. Checked out the dev tools in IE9! 1.) HTML source is shown with the correct tag case (lower)! Great! Any chance this will be backported to the IE7/IE8 dev tools? 2.) Text nodes in the source still have a useless prefix - please remove it! 3.) element names in the style tab (inherited) are NOT lowercase - this still needs to be fixed. 4.) There is too much whitespace around the colon on CSS properties and HTML attributes. 5.) Pressing Enter is still required on all attribute/property changes/additions to have changes take effect. This is highly anoying when you have just typed a large style string and then mouse click outside of the edit box to see the changes or grab additional text content - it should save all changes on Blur (by Enter, Tab, or de-focus) 6.) attributes in the HTML source tree are still appearing in 1990camelCase vs. lowercase/true source case. Please fix that! It makes it look like our code is buggy! 7.) The "edit" HTML source is all IE6 TagSoup case. It should be 100% pure source, not IE's legacy qUiRkShTmLmOdE. 8.) The "edit" HTML source does not include the body tag, the head tag (and any of its content) or the html tag / doctype. This tool is therefore just shy of absolutely useless. 9.) Networking tab is an "about time!" item, so glad it was finally added. 10.) Select by click doesn't highlight the elements as you mouse over them allowing you to easily identify which element you are getting (e.g. a div wrapping a span) (this is a bug since IE8 supported it) 11.) Color picker picks up anti-aliasing on text if you have Clear-type turned on. On one hand this makes sense but it is a bit confusing if you aren't expecting it e.g. if the font color is #0000ff, then it is odd to get a cyan or purple color back. 12.) I count about 9 different modes that IE9 can be rendering/parsing JavaScript in. I see this as a massive nightmare to maintain. I'm not sure how to make it better, but expect developers to get more and more frustrated with IE with every version released. I watched the various presentations but have a few comments about the High Performance one by Jason Weber. Most of the content was good (and likely known by pro developers) but there were a few new items I hadn't seen. Slide deck is on the video page. #12.) Cache function pointers (slide 75) which refers to examples on slides (55 and 56) I watched this and groaned that it looked like micro-optimization but conceded that I didn't have test data to base that decision on. I just ran several benchmark tests in Firefox, Chrome & IE8 (50,000 calls - dozens of times) and discovered no determinable difference in speed using a local pointer vs. a global one. I'm wondering if there is more to this picture? Does it become an issue on large sites because IE pollutes the global namespace with every DOM element that has an ID or a NAME attribute? Or is this something that gets worse in IE9 that we should be aware of? I would presume that modern JIT compilers would optimize for this kind of stuff anyways. The second thing I noticed was: #15 Minimize DOM Interations (slide 75) refers to slide (62 and 63) The example shows how to reduce lookups (greatly desired) but fails (as did the talk) to indicate that looking up: document.body.all.lside document.body.all.rside document.body.all.result is bad with bad written all over it. Since "lside", "rside" & "result" are all unique items, they should have an id attribute set, thus: document.getElementById(id); would be the preferred lookup method, or even more simple (using jQuery) $('#lside') $('#rside') $('#result') The **only** time developers would be advised to use the ".all" collection is when they are writing a function that is specifically designed to provide a workaround for a broken DOM method implementation in legacy versions of IE (e.g. IE6 & IE7) Other than those 2 items, the presentation was great. I'm surprised that so many of the items were "news" to many, but glad the information is getting spread. @stevewebdev: The book "Even Faster Websites" has a section on the cost of scope resolution, with performance charts: Hmm, yeah, the charts do indicate a perf gain (esp. in IE browsers) Doing some quick math... If I reference a global, from 4 levels deep in scope 200,000 times I can save ~100ms if I have a local pointer. 100ms/200,000iterations = 0.0005ms saved for each iteration. Since most stuff I do would likely not iterate over more than 250 items... I could save 0.125ms! I'll certainly keep it in mind, but yeah definitely micro-optimization... and the impact is really only geared to IE browsers. The performance video was the most interesting. I'm making a lot of these mistakes today without knowing. You should publish a reference guide on performance like the orielly code samples series which shows developers exactly what we need to change with checklists and how. It's easier to reference a book and checklists than trying to find the right section in a video. I would like to request an official reference guide. Thanks for making these videos.
https://blogs.msdn.microsoft.com/ie/2010/03/23/mix-session-videos-now-available/
CC-MAIN-2017-30
refinedweb
1,375
72.76
to Nepal Wireless Networking Project Started by Himanchal Higher Secondary School Introducing Wi-Fi and Emerging Wireless Technology to Connect and to Create New Opportunities in Rural Nepal Mahabir Pun, Team Leader of the project with the strong support of friends from around the world, has started a campaign - "Donate $1 per month to help Build Broadband Information Highway Across Nepal". Here is the "Speech Delivered by Mahabir Pun" at the ANA Convention in 2008 at Baltimore, USA. Here is the Power Point Presentation of Mahabir Pun about "One Dollar a Month" Campaign - Click to download Mahabir's presentation. Here is the "Request Letter for One Dollar a Month Campaign" . Please read it and sign up for the campaign as follows. Please Note: You will get tax dedcution for your contribution in the US because Himanchal Education Foundation is registered as 501 (c)(3) not-for-profit-making corporation in Nebraska, USA. Encourage your children to initiate the $ 1 campaign among their peers in schools so that the children can learn from their early age to be involved in projects like this for good cause. This is the picture of the first relay station we built in May 2002 on a 20m tall tree. The elevation of the relay station mountain is 10,800 ft (3,320m) high. We had used a normal 8-foot TV dish antenna as the reflector and a one liter measuring can as the feed. We are still using the same tree as the "relay tower" with different antenna and radios. Please read detail Case Study Report on Nepal Wireless Project submitted to World Bank in September 2006 at: Please visit the local homepage to see how the villagers are using the Intranet at. Some links in the local homepage are not available from outside . We have to do it to protect the website from spams. Please print Sign-up sheet from here - Sign up sheet and distribute to members of your organization and friends of Nepal. WHY ARE WE LOOKING FOR SUPPORT AND HOW CAN YOU SUPPORT? A Request from Team Leader, Mahabir Pun So far we are moving at slower speed for two reasons. The first reason is that we were testing different things and learning ideas to find ways to maximize the benifits of wireless networks in the isolated remote villages of Nepal. Secondly we did not have enough resources to expand the wireless network in larger areas of Nepal. Whatever we have been able to do is because of the financial and technical supports of some individuals, businesses, non-profit organizations, and international organizations (such as International Telecommunication Union, World Bank). So far we have not gotten any support from the Government of Nepal even though we approached them in 2007. We have also submitted a concept plan for 2008 to build wireless networks that includes 19 districts. The government is positive about the proposal but has indicated a shortfall in available funds. Moreover, it will take some time for the political parties to resolve all the political issues in Nepal. At this situation we just don't want to wait for some years until current political issues are resolved in order to get support from Nepal Government. We want to continue our effort of building bigger wireless networks and provide ICT services in rural Nepal. Therefore we have started "Donate $1 Per Month To Build Wireless Network Across Nepal" campaign . Please participate in the campaign and help Nepal to be prepared to move to 21st century. We would like to request all the organizations of the Nepalese in the US to actively participate and contribute for the campaign during the ANA convention in Baltimore USA. This is a great opportunity for two million Non Residence Nepalese (NRNs) living around the globe for doing something good for your country that gave you birth, took care of you and brought to the position where you are now. Please Note: You will get tax dedcution for your contribution in the US because Himanchal Education Foundation is registered as 501 (c)(3) not-for-profit-making corporation in Nebraska, USA. According to the estimate done by NRN Association there are 2 millions Nepalese all over the world. If we could convince just 5% of these Nepalese signed up for this campaign, we will have 100,000 members. With this number of people supporting to build the information highway, we can easily connect most of the rural Nepal in five years. We would also like to request donor agencies to provide matching fund for whatever we will be able to raise from "the $1 per month campaign". With your support, we can build wireless networks across Nepal covering at least 80% of the country, without taking any loan from international funding agencies. This task is perfectly doable and we are determined to do it. The request is not only for people of Nepali origin. This request goes also to friends of non Nepali origin from around the world. Donating $1 a month you won't loose anything but 80% of the Nepalese living in rural areas will benefit so much by getting access to the Information and communication technology. Your $1 a month will actually be one of the greatest supports you can ever make to build "New Nepal". We appreciate very much for your support. Why did we start this project? Digital Divide" and "Digital Gap" have been big words in the past few years. Organizations like the United Nations and others have organized many conferences and have launched campaigns to address this issue. Developed and developing countries are talking to each other to find what they can do to bring the computers and the Internet within the reach of the poor people. Everybody seems very much worried about finding ways to make the digital gap narrower. So is the Nepal Wireless Networking Project, seriously speaking. Our project is building wireless networks and is connecting mountain villages. However, connecting the villages wirelessly and bringing computers in the villages are not enough. We need to develop educational contents in Nepali language that everybody can understand. We also need to provide services such as e-health, Internet phone, remittance, and local e-commerce that are useful for the villagers. Obviously, we can't do all those things by ourselves and we need partners that can provide applications and contents for the villagers. Therefore we are working with several organizations now to find ways to maximize the benefit of wireless technolgy for the people living in the isolated villages of Nepal. Our partners and supporters now are E-Network Research and Development for wireless networking and training, Open Learning Exchange - Nepal for developing educational contents in Nepali language, Nepal Research and Education Network for research and network designing, Gandaki College of Engineering and Sciences, and Kathmandu Engineering College for software development and technical support, Kathmandu Model Hospital and Om Hospital Pokhara for telemedicine program, Thamel.com for e-commerce purposes and Nepal Library Foundation Canada for setting up computer labs with thin client set up in the rural areas.. That time we did not know at all how useful a wireless network can be for the rural people. We did not even thought that we would be able to build wireless networks in different parts of Nepal. The villages are wirelessly networked and connected to an ISP WorldLink, which is approx. 22 air miles (~34 km) away from Relay Station 1, in a city called Pokhara. Wlink is one of the sponsors of the broadband Internet connection to the villages in Myagdi district Nepal. In September 2003, we had connected five villages of Myagdi district. In 2004, we became able to connect 7 villages. In 2006 we connected 6 more villages. Now we have connected altogether 22 villages of Myagdi, Kaski and Parbat district. We helped to build a similar wireless network in Makawanpur district connecting 7 villages, and in Palpa district connecting 4 villages. Who owns, runs and maintains the network? The Myagdi network of Nepal Wireless Networking Project is now owned and run by Himanchal Higher Secondary School, Nangi Village, Nepal. This is the school that Mahabir Pun had helped villagers to start after coming back from the USA, which is also the hub of several income producing projects including wireless networking project. However, Nepal Wireless Networking Project is an ambitious project and we want to go far beyond what we have done now by inviting people and communities that are interested to replicate such projects in other parts of Nepal. We are also knocking at the doors of Nepal Government and asking them to replicate the network across Nepal. We have now signed MoUs with several institutions and organizations to expand the network in other parts of Nepal and to make the wireless network as much beneficial as possible for rural population. On the long run, this project will be a national project and it will be developed in public and private partnership business model. Who is our target? The taget of this project are the people living in isolated villages of Himalayan region of Nepal where there is almost no chance of getting the modern means of communication in near future. We are introducing the information technology to villagers, most of whom had never seen computers until a few years ago. Most of the villagers still have no idea as what the uses of the computers are. For the villagers, a computer is no more than a "mysterious box". Moreover, they have no idea what Internet is. What is our goal? Our initial goal is to introduce the "mysterious box" to the remote villages and show its real uses to the villagers. It is only after the villagers see what a computer does will they be motivated to learn about it and use it by themselves step by step. Each step they will take will be a step forward to bring the digitally divided countries closer. We believe that this is the right way to go. What were the biggest challenges and problems that we had to face? Technically, we were running the network illegally because we had not gotten license that the government of Nepal then required. Also it was almost impossible to import Wi-fi equipment from abroad. We had smuggled all the wireless equipment from Singapore and the US. Therefore the biggest challenges until September 2006 for this project was to find ways to work in the absence of flexible government law. Moreover it was very risky to our lives to bring the equipment and build the network during the time of peak political conflict in Nepal. We might have been killed or tortured either by the government or by the Maoist armies if there had gone something wrong. Luckily, we survived. There were obviously some technical problems also that incurred. However, we became able to solve the technical problems. After the restoration of democracy in Nepal in April 2006, the political situation is getting better in Nepal. Therefore we don't have as much risk now as it was before to set up Wi-fi network. Wi-fi technology (2.4 GHz and 5.8 GHz) has been de-licensed since Setpember 2006, and it has been easier to import and set up wireless network. Our team members along with the people working in the wireless networking field had to lobby hard to de-license the Wi-fi bands. What are we lobbying for now? Nepal Wireless Networking Project along with individuals and organization working in the field of wireless networking had lobbied for opening up of VOIP and provision for rural and community ISPs in Nepal. For the last two years, team leader Mahabir Pun has spent more time in Kathmandu making presentation to lawmakers and officials of the importance of these things for rural communications. The team leader gave presentations to member of parliaments, political leaders and government officials telling how Wi-fi technology can be very useful for the people living in the remote areas. As a result the government has brought a new law on Rural and Community ISPs within Nepal reducing the license fee to about USD3 for using VSAT in the rural areas and starting a rural ISP. Originally the license fee was almost USD 5,000. The government has also opened up PC to PC and IP to IP VoIP in September 2007. We also lobbied for about a month with Nepal Telecom Authority of Nepal to make Nepal Telecom share its copper and fiber infrastructure with private ISPs. Now Nepal Telecom Authority has brought a law requiring Nepal Telecom to share it copper and fiber infrastructure. What can you see in this site? In this website, we are trying to explain how the idea came about, what we tried, what we have done so far, what we are doing with it, what our future plans are, and how we can work together. If you like the idea, you are welcomed to be a part of this campaign. Who is the sponsor of this site? Jonni Lehtiranta from Finland is the sponsor of this website. He is helping to create and maintain this website from his own server. He visited Nangi village, Nepal in 2002 and 2004 and stayed a total of more than two months. Jonni was back to Nangi in Sptember 2007 for three weeks. Jonni also brought a sauna stove from Finland and installed in Nangi village, which the villagers like very much. ----------------------------------------------------------------------------------------------------------------------------------------------------------
http://www.nepalwireless.net/index.php?option=com_content&view=category&layout=blog&id=44&Itemid=54
CC-MAIN-2014-10
refinedweb
2,254
60.85
Get mouse wheel direction [SOLVED] On 30/03/2015 at 17:35, xxxxxxxx wrote: I've sifting through the mouse messages with: def Message(self, msg, result) : for each in msg: if each[0] == 1768452963: print 'mouse wheel: ', result This detects mouse wheel messages fine, but I can't find any data to indicate the direction the mouse wheel is scrolling (turning). How do you do that? Thanks, Chris On 31/03/2015 at 11:47, xxxxxxxx wrote: Hi Chris, I'm a bit confused about the message ID you are comparing to. Can you give me a hint, where you found that? And can you furthermore give me some context you are trying this (GeUserAre, ToolData,...)? On 31/03/2015 at 12:28, xxxxxxxx wrote: I found the message ID by staring at endless streams of message data printed to the console. It works fine so far. It ignores all button presses, and only triggers on wheel scrolls, but there is no direction in the 'result' or anywhere else I can find. The context is 'gui.GeUserArea'. How do you get mouse wheel directions? Thanks. On 01/04/2015 at 06:42, xxxxxxxx wrote: Hi, in a GeUserArea you can use something like this: def InputEvent(self, msg) : dev = msg[c4d.BFM_INPUT_DEVICE] if dev == c4d.BFM_INPUT_MOUSE: chn = msg[c4d.BFM_INPUT_CHANNEL] if chn == c4d.BFM_INPUT_MOUSEWHEEL: val = msg[c4d.BFM_INPUT_VALUE] if val > 0: print "dir up" else: print "dir down" return True On 01/04/2015 at 09:55, xxxxxxxx wrote: Andreas, Now that's what I call support! Thanks, Chris On 01/04/2015 at 10:08, xxxxxxxx wrote: You are welcome
https://plugincafe.maxon.net/topic/8619/11263_get-mouse-wheel-direction-solved
CC-MAIN-2020-40
refinedweb
272
82.65
2009/10/21 Tim Wawrzynczak <inforichland at gmail.com>: > True...here we go then: > > import Data.IORef > import System.IO.Unsafe > > mkNext :: (Num a) => IO (IO a) > mkNext = do > ref <- newIORef 0 > return (do modifyIORef ref (+1) > readIORef ref) > > next :: IO () > next = do > foo <- mkNext > a <- sequence [foo,foo,foo] > putStrLn $ show a > > > running next will print [1,2,3] which is the result of calling 'foo' 3 > times. > > But technically then, mkNext is just an IO action which returns an IO action > ;) > and not a function which will return the next value each time it is called, > hence the need to extract the value from mkNext, then use it... That why it is called mkNext: do next <- mkNext sequence [next, next, next] > > Cheers, > Tim > > > On Wed, Oct 21, 2009 at 1:30 PM, minh thu <noteed at gmail.com> wrote: >> >> 2009/10/21 Tim Wawrzynczak <inforichland at gmail.com> >> > >> > Here's an example in the IO monad: >> > >> > import Data.IORef >> > import System.IO.Unsafe >> > >> > counter = unsafePerformIO $ newIORef 0 >> > >> > next = do >> > modifyIORef counter (+1) >> > readIORef counter >> > >> > Naturally, this uses unsafePerformIO, which as you know, is not >> > kosher... >> >> But you don't close around the Ref like in your schemy example. >> >> mkNext = do >> ref <- newIORef 0 >> return (do modifyIORef ref succ >> readIORef ref) >> >> mimic your other code better. >> >> Cheers, >> Thu > >
http://www.haskell.org/pipermail/haskell-cafe/2009-October/068039.html
CC-MAIN-2013-20
refinedweb
219
80.11
#include <wx/checklst.h> A wxCheckListBox is like a wxListBox, but allows items to be checked or unchecked. When using this class under Windows wxWidgets must be compiled with wxUSE_OWNER_DRAWN set to 1. The following event handler macros redirect the events to member function handlers 'func' with prototypes like: Event macros for events emitted by this class: wxEVT_CHECKLISTBOXevent, when an item in the check list box is checked or unchecked. wxCommandEvent::GetInt() will contain the index of the item that was checked or unchecked. wxCommandEvent::IsChecked() is not valid! Use wxCheckListBox::IsChecked() instead. Default constructor. Constructor, creating and showing a list box. wxPerl Note: Not supported by wxPerl. Constructor, creating and showing a list box. wxPerl Note: Use an array reference for the choices parameter. Destructor, destroying the list box. Checks the given item. Note that calling this method does not result in a wxEVT_CHECKLISTBOX event being emitted. Return the indices of the checked items. Returns true if the given item is checked, false otherwise.
http://docs.wxwidgets.org/trunk/classwx_check_list_box.html
CC-MAIN-2017-43
refinedweb
165
60.61
IRC log of rdfval on 2013-09-11 Timestamps are in UTC. 01:38:40 [DavidBooth] DavidBooth has joined #rdfval 03:44:13 [SteveS] SteveS has joined #rdfval 04:58:43 [mib_x8cefa] mib_x8cefa has joined #rdfval 06:53:02 [Zakim] Zakim has left #rdfval 12:59:01 [RRSAgent] RRSAgent has joined #rdfval 12:59:01 [RRSAgent] logging to 13:03:36 [SteveS] SteveS has joined #rdfval 13:03:59 [danbri_] is zakim in listen-only mode? 13:04:41 [Arnaud] Arnaud has joined #rdfval 13:06:16 [Zakim] Zakim has joined #rdfval 13:06:40 [Arnaud] sorry guys we're a bit behind 13:06:43 [Arnaud] hang in there 13:06:52 [Arnaud] eric is setting up the phone 13:07:08 [Arnaud] zakim, this is rdfval 13:07:08 [Zakim] ok, Arnaud; that matches SW_(RDFVal)8:30AM 13:08:20 [labra] Slides 13:08:27 [gjiang] gjiang has joined #rdfval 13:08:36 [rmb] rmb has joined #rdfval 13:08:37 [Zakim] +Workshop_room 13:08:44 [Arnaud] ok, we're on 13:08:46 [nmihindu] nmihindu has joined #rdfval 13:08:57 [Arnaud] please, join in, we're starting 13:09:00 [ssimister] ssimister has joined #rdfval 13:09:38 [hsolbri] hsolbri has joined #rdfval 13:10:21 [ericP] Zakim, pick a victim 13:10:21 [Zakim] Not knowing who is chairing or who scribed recently, I propose Workshop_room 13:10:42 [hsolbri] Jose Gayo - Validating statistical index data represented in RDF using SPARQL queries 13:10:54 [dbooth] dbooth has joined #rdfval 13:10:59 [AAshok_Malhotra] AAshok_Malhotra has joined #rdfval 13:11:02 [Arnaud] zakim, who is on the phone? 13:11:02 [Zakim] On the phone I see kcoyle, [IPcaller], [IPcaller.a], Workshop_room 13:11:10 [mgh] mgh has joined #rdfval 13:11:14 [TimCole] TimCole has joined #rdfval 13:11:15 [ericP] scribenick: hsolbri 13:11:44 [Zakim] -Workshop_room 13:11:53 [Arnaud] ok, we're calling back 13:12:08 [Zakim] +Workshop_room 13:12:17 [kcoyle] still whooshing 13:12:29 [hsolbri] soporific? 13:12:36 [kcoyle] this happened briefly yesterday then went away 13:13:25 [roger] roger has joined #rdfval 13:13:40 [Arnaud] we'll try to reboot in a desperate move 13:14:25 [Arnaud] well, we haven't published the minutes per se but the irc log is available 13:14:41 [hsolbri] Motivation - Webindex Project 13:14:42 [ericP] [ slide 2] 13:14:55 [ericP] jose: developed for web index 13:15:12 [ericP] ... we developed the data portal for web index 13:15:12 [hsolbri] Visualization and data portal 13:15:26 [ericP] [slide 3] 13:15:33 [GR] GR has joined #rdfval 13:15:34 [ericP] jose: the workflow involves: 13:15:39 [Arnaud] irc log: 13:15:48 [ericP] ... .. get data from external sources 13:16:02 [ericP] ... .. statisticians produce index 13:16:14 [ericP] ... .. we map that to RDF and provide visualizations 13:16:31 [hsolbri] Conversion is from Excel to RDF 13:16:38 [Arnaud] rrsagent, make logs public 13:16:54 [Zakim] +Workshop_room.a 13:17:29 [kcoyle] tbaker: the piratepad has quite a bit of content 13:17:31 [hsolbri] jose: Technical details. 61 countries, 85 indicators. > 1megatriple, linked to DBpedia, etc. 13:18:17 [hsolbri] WebIndex slide 13:18:24 [ericP] [slide: WebIndex computation process (1)] 13:18:53 [Zakim] -Workshop_room 13:19:00 [dbooth_] dbooth_ has joined #rdfval 13:19:39 [PhilA] Jose Emilio is talking about and its use of 13:21:48 [DaveReynolds] DaveReynolds has joined #rdfval 13:22:52 [ericP] link should be ther. i forgt to remove the "not available" text 13:23:09 [hsolbri] Jose: Used SPARQL CONSTRUCT instead of ASK 13:23:23 [hsolbri] ... empty graph if ok, else RDF graph with error 13:23:42 [gjiang] gjiang has joined #rdfval 13:23:51 [hsolbri] [slide: SPARQL queries RDF Data Cube] 13:24:53 [hsolbri] [slide: limitations of SPQRAL expressivity] 13:25:12 [hsolbri] s/SPQRAL/SPARQL/ 13:25:30 [Zakim] +[IPcaller.aa] 13:25:50 [hsolbri] Jose: Challenge computing series computation on RDF collections 13:26:48 [Zakim] -DaveReynolds 13:27:19 [Zakim] +hhalpin 13:27:29 [hsolbri] Jose: Idea of RDF Profiles for dataset families 13:28:40 [hsolbri] could it be the mouse? 13:29:11 [hsolbri] Jose: 13:29:29 [hsolbri] Jose: Source code in Scala (site on slides) 13:30:36 [hsolbri] Jose: - demo site 13:32:39 [hsolbri] Jose: Webindex as use case, SPARQL as implementation, RDF Profiles (declaritive, Turtle) 13:33:05 [ddolan] ddolan has joined #rdfval 13:35:18 [hsolbrig] hsolbrig has joined #rdfval 13:35:30 [danbri] (somewhat related, SKOS validation - - also just a structure) 13:35:31 [gqjiang] gqjiang has joined #rdfval 13:35:36 [ericP] jose: you can check e.g. that one observation is in one slice but not much more expressivity than that 13:36:27 [ericP] ashok: if SPARQL works for a fairly complicated situation, why are we thinking about anything else? 13:36:34 [ericP] jose: SPARQL is hard to debug 13:36:44 [gjiang] gjiang has joined #rdfval 13:37:07 [ericP] ... we need to differentiate validating the graph vs. a dataset 13:38:04 [ericP] ... with SPARQL, we can test specific values in a particular graph 13:38:05 [hsolbrig] A couple of interesting, albeit unrelated ideas here... 13:38:19 [ericP] ... though we could compile ShEx to SPARQL 13:38:27 [hsolbrig] ... signing RDF - how do you generate a reproducable MD5 w/o order? 13:38:56 [hsolbrig] ... functional patterns for RDF lists. Should there be "best practices"? 13:40:20 [ericP] PhilA: is slide 11 a candidate profile? 13:40:27 [ericP] ... if so, i see it as too complicated 13:41:18 [ericP] ... we have two req: validation and form creation. too complex for the latter 13:41:38 [ericP] ericP: is that 'cause of the expressivity, or 'cause it's in RDF? 13:41:49 [ericP] PhilA: i suppose 'cause it's in RDF 13:42:26 [ericP] evren: re: UI generation, the issue is not the syntax, it's the SPARQL query. that's where the shape of the data is described 13:42:33 [ericP] scribenick: ericP 13:43:38 [ericP] PhilA: EU reqs are "don't make me need to speak SPARQL to generate a UI" 13:43:44 [gjiang] gjiang has joined #rdfval 13:46:26 [ericP] gjiang: did you use SPARQL extensions? 13:46:39 [ericP] jose: we weren't happy when we had to use jena:sqrt 13:46:41 [hsolbri] hsolbri has joined #rdfval 13:46:55 [ericP] gjiang: maybe there can be a link from SPARQL to some statistical package 13:47:31 [DavidBooth] scribe: DavidBooth 13:47:57 [ericP] topic: Stardog ICV 13:48:52 [Arnaud] slides: 13:50:27 [DavidBooth] slide 3 13:50:44 [Zakim] +??P39 13:50:46 [DavidBooth] Slides are not numbered. :( 13:51:09 [hsolbri] hsolbri has joined #rdfval 13:51:15 [TallTed] TallTed has joined #rdfval 13:51:29 [dbs] Zakim, ??P39 is dbs 13:51:29 [Zakim] +dbs; got it 13:52:34 [DavidBooth] slide 5 13:53:15 [DavidBooth] slide 7 13:55:18 [DavidBooth] slide 8 13:57:25 [gjiang] Semantics in OWL are for inference not suitable for validation 13:58:43 [DavidBooth] slide 10 14:00:33 [DavidBooth] slide 11 14:00:45 [gjiang] Rule syntax for constraints 14:01:21 [DavidBooth] slide 12 14:01:32 [DavidBooth] slide 13 14:01:33 [arthur] arthur has joined #rdfval 14:06:00 [DavidBooth] Evren: if each person must have two parents, but only one was specified, inference can determine that there is another parent, and then the validation can be applied after inference. 14:06:34 [DavidBooth] (Evren talks to a slide that is not in the uploaded slides) 14:08:12 [DavidBooth] Evren: tool figures out explanation of validation. 14:08:36 [DavidBooth] slide 15 14:08:56 [ericP] evren: i agree with the folks that said we need good explanations of errors but don't believe the constraints author should have to write the explanation. that should be the tool. 14:09:36 [ericP] ... we have definitions of constraints in W3C specs so we should capture those 14:11:15 [DavidBo. 14:11:40 [DavidBooth] Evren: Yes. 14:12:06 [DavidBooth] Arnaud: The question is whether the language allows you to specify that entailment should be used. 14:12:13 [ericP] arthur: the quesiton is "does the language you use allow you to specify the entailment?" 14:12:36 [ericP] s/arthur: the quesiton/Arnaud: the question/ 14:12:37 [DavidBooth] Arthur: Initially you propopsed to just change the OWL namespace. Is that what you use now? 14:13:29 [DavidBooth] Evren: No, that would require using all the tool chains. You just execute it through the validation. That's why at the tool level you need to separate the axioms from the constraints. 14:14:36 [DavidBooth] Arthur: How would you associate the constraints with a graph? 14:16:08 [PhilA] PhilA: A proposal (from Paul Davidson) is to add a property to VoID that links a dataset to a profile (constraint set) 14:16:23 [DavidBo. 14:16:53 [DavidBooth] EricP: What if someone interprets constraints as inference rules accidentally? 14:18:21 [DavidBooth] Evren: under OWA it would just infer that person085 is a manager, instead of determining (under CWA) that there is an error because person085 is not a manager. 14:18:54 [ericP] @@1: how can i read this to learn about the graph to e.g. generate a form? 14:19:23 [ericP] evren: you can thing about it as the SPARQL BGP describes the graph 14:19:47 [ericP] ... so we see "someValuesFrom" and we'll create a text box, ... 14:20:07 [DavidBooth] (Evren explains how constraint can be represented in SPARQL) 14:20:15 [DavidBooth] _: What about optional properties? 14:20:20 [ericP] @@1: how would i describe optional properties 14:20:41 [ericP] evren: right, you wouldn't write that in the constraints langauge 14:21:24 [DavidBooth] Arthur: It's not really a constraint, it's a graph descriptoin. 14:21:55 [DaveReynolds] +1 to last speaker, optional properties are needed for describing the data "shape" as part of publish/consume contract, even though they are not part of validation 14:22:13 [DavidBooth] Arthur: You want to describe a contract with a service, and part of the contract is that a property can appear 0+ times. 14:23:22 [ericP] evren: we added "min 0" to our OWL constraint. it's not actionable during constraints checking but it describes the graph 14:24:09 [DavidBooth] Topic: Bounds: Expressing Reservations about incoming Data, Martin Skjaeveland 14:24:15 [DavidBooth] slides: 14:26:25 [DavidBooth] slide 2 14:27:40 [DavidBooth] slide 3 14:30:32 [DavidBooth] slide 4 14:30:40 [DavidBooth] slide 5 14:31:56 [DavidBooth] slide 6 14:34:14 [DavidBooth] Arthur: What do you mean by element? Does it depend on ts position? 14:34:25 [DavidBooth] Martin: By element I mean S P O in a graph. 14:34:48 [DavidBooth] s/P O/P or O/ 14:35:05 [DavidBooth] s/I mean/I mean a/ 14:36:04 [DavidBooth] slide 7 14:38:48 [DavidBooth] slide 8 14:40:47 [DavidBooth] slide 9 14:42:46 [DavidBooth] slide 10 14:43:15 [DavidBooth] slide 1 14:43:17 [DavidBooth] slide 11 14:44:58 [DavidBooth] slide 13 14:47:21 [DavidBooth] Evren: What kind of use cases for ontology hijacking? 14:47:41 [DavidBooth] Martin: Can check if you are adding domain and range axioms. 14:48:53 [DavidBooth] Evren: OWL RD only allows things that can be expressed with one triple. Cannot have someValuesFrom, allValuesFrom, (and some others). 14:49:03 [danbri] if I say MyNewType is a subClassOf ,">, versus MyNewType is a superTypeOf ... people tend to see the latter as weirder, the former as acceptable and non-hijack-y 14:49:25 [DavidBooth] _: Re ont hijacking that adds statements. What about removing statements? what effect does it have? 14:49:48 [ericP] s/_: Re ont/gjiang: Re ont/ 14:49:53 [DavidBooth] martin: no, only considered use cases of receiving data and protecting existing dataset. 14:50:40 [DavidBooth] Eric: Use case came from practical considerations or theoretical? 14:51:00 [DavidBooth] Martin: We did prior work on managing RDF transformations. This is transforming by adding. 14:51:28 [DavidBooth] EricP: SADI project is all about inferring extra triples. Their rules are written in OWL LD. 14:52:19 [PhilA] scribe: PhilA 14:52:22 [Zakim] -kcoyle 14:52:23 [PhilA] scribeNick: PhilA 14:52:31 [Zakim] -hhalpin 14:52:35 [PhilA] Coffee 14:52:40 [dbs] coffee++ 14:55:47 [tbaker] Eric? 15:00:15 [Zakim] -[IPcaller] 15:01:08 [dbs] I can hear tbaker (assuming tbaker = Tom) 15:06:13 [DaveReynolds] DaveReynolds has left #rdfval 15:10:57 [ssimister] ssimister has joined #rdfval 15:19:18 [PhilA] Next up OSCL Resource Shapes 15:19:19 [DavidBooth] Arthur's slides: 15:19:21 [PhilA] slides 15:19:35 [hsolbri] hsolbri has joined #rdfval 15:19:51 [rmb] rmb has joined #rdfval 15:20:02 [PhilA] Arthur's paper 15:20:20 [DavidBooth] Topic: OSLC Resource Shape: A Linked Data Constraint Language 15:20:24 [PhilA] slide 1 - 1 slide intro to OSLC 15:20:26 [SteveS] SteveS has joined #rdfval 15:21:24 [PhilA] Arthur: IBM customers want tools that cover the product life cycle and beyond 15:21:33 [Zakim] +kcoyle 15:22:17 [PhilA] Arthur: core specs delivered to W3C, being worked on in LDP WG. More domain specific specs gone to OASIS 15:22:47 [PhilA] ... customers bothered by lack of XML Schema analogue 15:23:41 [PhilA] ... came up with minimal language 15:24:39 [PhilA] Slide 5 15:24:59 [PhilA] slide 6 15:25:32 [PhilA] RDF/XML snippet shown is a resource shape for a bug report 15:25:43 [PhilA] slide 7 15:26:51 [PhilA] Does data have to be in the graph or is it externally referenced, for e.g. 15:27:01 [hsolbrig] hsolbrig has joined #rdfval 15:27:18 [PhilA] slide 8 15:28:33 [PhilA] Arthur: Creation factory is the data source, query capability is the endpoint (scribe paraphrase) 15:29:52 [PhilA] arthur: data can link to its description (its shape) 15:30:34 [PhilA] slide 9 15:32:06 [PhilA] slide 10 is an example 15:32:16 [rogerm] rogerm has joined #rdfval 15:33:11 [PhilA] Declarative list of properties etc. Encoded in turtle 15:34:55 [PhilA] arthur: OSLC is just a vocabulary, it's not an ontology. How you use it is up to you 15:35:36 [PhilA] slides 11 - 16 show the spec 15:35:44 [PhilA] slide 17 15:36:10 [PhilA] Arthur: SPARQL seems good for the task of testing against the resource shape 15:37:14 [PhilA] ericP: I notice people favour returning True if there's a failure (the inverse of OSLC model) 15:37:32 [PhilA] Arthur: OK, but you want data to be returned so you cna fix it 15:39:28 [PhilA] slide 18-19 15:39:56 [PhilA] slide 20 - Summary 15:40:46 [PhilA] Arthur: OSLC has been around about 3 years 15:40:54 [PhilA] ??: How does this relate to WSDL? 15:41:08 [ericP] s/??: How/hsolbrig: How/ 15:41:10 [PhilA] Arthur: It's in the same spirit 15:41:20 [PhilA] ... you cna check for properties, cardinalities etc. 15:41:42 [DavidBooth] s/cna/can/ 15:41:44 [gjiang] gjiang has joined #rdfval 15:43:20 [PhilA] Arthur: 15:43:50 [PhilA] hsolbrig: Is there a spec for the semantics of OSLC? 15:43:50 [evrensirin] evrensirin has joined #rdfval 15:44:07 [PhilA] Arthur: The semantics would be formalised using SPARQL 15:44:20 [evrensirin] q+ ask about deletes 15:44:34 [evrensirin] q+ to aks about deletes 15:44:49 [PhilA] Discussion of what 'read only' means 15:45:00 [PhilA] q? 15:45:27 [Arnaud] ack evrensirin 15:45:27 [Zakim] evrensirin, you wanted to aks about deletes 15:45:31 [PhilA] ack evrensirin 15:45:50 [PhilA] evrensirin: you said something about the payload? 15:46:03 [PhilA] arthur: you might want to specify a pre-condition for a delete 15:46:12 [ericP] s/about the payload/about not needing to do anything about DELETE/ 15:46:14 [PhilA] ... that's a good point. The context of the constraint is important 15:47:01 [arthur] arthur has joined #rdfval 15:47:09 [ericP] 15:47:37 [labra] labra has joined #rdfval 15:47:59 [PhilA] PhilA has joined #rdfval 15:48:54 [PhilA] tbaker: paper 15:49:01 [ericP] topic: Description Set Profiles 15:49:12 [PhilA] slides 15:49:33 [PhilA] tbaker: Gives background on DC. Application Profiles date from 2000 15:50:12 [PhilA] slide 2 15:50:49 [PhilA] slide 3 15:51:14 [PhilA] slide 4 15:51:21 [PhilA] slide 5 15:51:43 [PhilA] slide 6 15:51:44 [rmb] rmb has joined #rdfval 15:51:51 [PhilA] tbaker: Looks more like a record format 15:51:52 [PhilA] slide 7 15:52:21 [PhilA] slide 8 15:52:33 [kcoyle] description set document: 15:52:48 [PhilA] slide 9 15:54:08 [PhilA] slide 10 shows same data in XML 15:54:24 [PhilA] tbaker: So can we validate the extracted data 15:54:59 [PhilA] tbaker: Defined a small set of constraints that we saw being used in the DC community in their app profiles 15:55:14 [PhilA] ... being produced as natural language text 15:55:56 [PhilA] slide 12 15:57:04 [PhilA] slide 13 15:57:24 [PhilA] tbaker: Just flash this up - it's the entire set of templates defined in the description set profile constraint language 15:57:26 [PhilA] slide 14 15:57:49 [PhilA] slide 15 15:58:19 [PhilA] slide 16 15:58:35 [PhilA] tbaker: The motivation was to help people author application profiles in a consistent way 15:59:13 [PhilA] ... here's a screenshot from an experiment that sadly no longer exists although there is some Python code I can share 15:59:33 [PhilA] ... it shows a tabular presentation of a profile - a style people are used to 15:59:38 [PhilA] slide 17 15:59:59 [PhilA] tbaker: constraints are being embadded in the source of the wiki page in a controlled way 16:00:01 [PhilA] slide 18 16:00:30 [PhilA] slide 19 16:00:46 [PhilA] tbaker: vision was that the profile could be used to configure editors as well as validators 16:00:48 [PhilA] slide 20 16:01:49 [PhilA] tbaker: We found that people were designing APs without looking at functional requirements 16:02:03 [PhilA] ... so this is an attempt from 2007 to put the APs in context 16:02:20 [PhilA] ... the yellow box is the AP - a set of documentation about the content of your metadata 16:02:42 [PhilA] .... you can also document the domain model it was based on 16:02:53 [gjiang] ... distinction among foundation standards, domain standards, application profile 16:03:37 [PhilA] ... we had some syntax definitions based on the abstract model 16:03:38 [PhilA] slide 21 16:04:48 [PhilA] tbaker: I'm really offering this as a set of requirements that were gathered in the DC community up to 2008 16:04:50 [PhilA] slide 22 16:05:28 [PhilA] tbaker: we wanted to encourage people to base their APs on functional requirements 16:05:29 [PhilA] slide 23 16:06:04 [PhilA] tbaker: wanted to encourage people to model reality but with a light touch 16:06:22 [PhilA] slide 24 16:06:45 [PhilA] tbaker: then we wanted to constrain the data - important for consistency and quality control 16:07:14 [PhilA] ... bridging the gap between people who see the world as a series of records and those whop see unbounded graphs 16:08:46 [PhilA] ... record people, used to XML, just saw it as the latest validation syntax. Some APs were then written as OWL ontologies. Wanted to get people to constrain the data, not the vocabulary (scribe note - hope I got that right) 16:08:50 [PhilA] slide 25 16:10:18 [PhilA] slide 26 16:10:56 [PhilA] PhilA: +1 to the 'Authored in an idiom usable by normal people' requirement 16:11:00 [PhilA] slide 27 16:12:37 [PhilA] Arnaud: Any questions? 16:13:02 [PhilA] tbaker: Before questions - can I ask kcoyle to comment? Anything to add? 16:13:28 [PhilA] kcoyle: My only comment is that I've been doing a back of the envelope on what we have and do not have is DSP language 16:13:54 [PhilA] ... when the requirements are completed, what we might want to do is to look at the existing languages and techniques and see which ones cover what 16:14:14 [PhilA] ... my gut feeling that there may not be a single solution because diff comunities have diff contexts 16:15:02 [PhilA] Arnaud: I hope you'll be able to join us after lunch as that's when we'll step back from the reqs and look at use cases, diff technologies etc. whether they match or not 16:15:23 [PhilA] ... challenge in standards is always to decide on the use cases 16:15:30 [PhilA] ... that's all for after lunch 16:16:44 [PhilA] TimCole: Thinking about APs.... XMl Schema always seem pretty powerful. Does anything on DSP provide any guidance on how we might make a language from what we have? 16:17:39 [PhilA] TimCole: One application might ask for foaf:name, another might want foaf:givenName and foaf:familyName - can I define a constraint doc in some way so that I can add an extra requirement? 16:18:22 [PhilA] tbaker: We refer to a specific set of DPS, or set of them - they're cookie cutters for data 16:19:12 [PhilA] ... in the example from FOAF - those distinctions are defined in the FOAF vocab - the DSP would say what to use but I don't see how that eg would impact the design of the constraint language itself 16:19:45 [PhilA] TimCole: You've defined a profile with lots of things and I want to change one thing. Do I have to repeat the whole thing or can I just define the difference? 16:20:25 [PhilA] tbaker: We did discuss having a layered approach so people can define a basic profile and then just add a layer on. So that's in the same thought process but we decided not to solve that 16:20:34 [PhilA] Arnaud: Anything else? 16:20:47 [PhilA] Topic: Experiences with the Design of the W3C XML Schema Definition Language 16:21:03 [PhilA] Noah's paper 16:21:16 [PhilA] Noah's slides 16:22:00 [PhilA] Arnaud: Noah was involved in XML Schema and so he's here to share his experiences of that 16:23:43 [PhilA] Noah: We went through a lot of things when designing XMLSchema - it has a lot right and a few problems 16:23:50 [PhilA] slide 2 16:24:13 [PhilA] slide 3 16:24:26 [PhilA] Noah: These topics match those in the paper 16:24:48 [PhilA] slide 4 Use Cases 16:25:23 [PhilA] Noah: People came with very different assumptions and ideas and diff ideas about validation 16:25:42 [PhilA] ... some thought the idea was to end up with a Boolean 16:26:26 [PhilA] ... others wanted to say more 16:27:06 [PhilA] ... some people wanted to know that data matched a type and why (data binding) 16:28:12 [PhilA] ... following the 80/20 rule is good but one person's 80 is another's 20 16:28:34 [PhilA] slide 5 16:30:06 [PhilA] Noah: discussed diff between validating doc as a whole or at the element level 16:31:33 [PhilA] Noah: RDF folks better at idea that serialisations are diff versions of same abstract model. That doesn't work so well for all XML folks 16:33:13 [PhilA] slide 6 16:34:03 [PhilA] Noah: No surprise that XML folks write their schemas in XML 16:36:21 [PhilA] ... It's possible that there were better ways of encoding a schema 16:37:39 [Arnaud] Noah is talking about the example on page 3 of his paper 16:37:46 [Arnaud] 16:38:54 [PhilA] Noah: So the warning is - don't automatically write your schemas in RDF 16:40:22 [PhilA] slide 7 16:40:56 [PhilA] slide 9 - Anticipate versioning 16:41:05 [PhilA] Noah: you're likely to need an answer 16:42:23 [PhilA] ... people find that their previous work needs updating. May need to reinterpret something 16:44:36 [PhilA] ...' 16:46:52 [PhilA] ericP: Drills down a little. 16:46:58 [mgh] In GS1 standards that provide XSD artefacts, we use this mechanism to represent an extension point (wildcard) <xsd:any 16:48:01 [PhilA] Noah: Point is that how to handle such cases is essentially app-specifc 16:48:56 [PhilA] ericP: Did you consider creating a compact syntax? 16:49:20 [PhilA] Noah: I guess you'll want your abstract model to map to RDF - you're used to that 16:50:30 [PhilA] ... we do have the abstract model for XML, it's there. 16:50:32 [Zakim] -dbs 16:50:46 [PhilA] Arnaud: Thank you for coming Noah 16:51:01 [tbaker] Thank you, Noah! 16:51:04 [kcoyle] could someone post here when things start up again, for those of us on the phone? thx 16:51:05 [PhilA] ... you're touching points that have been raised 16:51:41 [PhilA] Lunch - will be 25 minutes 16:51:45 [Zakim] -kcoyle 16:51:49 [PhilA] We'll resume at 13:35 EST 16:51:59 [PhilA] s/13:35/13:15/ 16:52:14 [tbaker] PhilA, do you mean 13:35 or 13:15? 17:05:46 [Zakim] -[IPcaller.a] 17:17:27 [Zakim] +??P0 17:17:31 [Zakim] -Workshop_room.a 17:17:31 [Zakim] +Workshop_room.a 17:20:28 [mSkjaeveland] mSkjaeveland has joined #rdfval 17:22:03 [Arnaud] about to resume meeting 17:22:13 [kcoyle] thx 17:22:21 [dbs] Arnaud: thanks 17:22:45 [dbs] conf call has gone silent 17:23:09 [Zakim] +kcoyle 17:23:30 [Zakim] -??P0 17:23:31 [Arnaud] can you guys here us? 17:23:59 [Zakim] +??P0 17:24:25 [dbs] Zakim, ??P0 is dbs 17:24:25 [Zakim] +dbs; got it 17:24:38 [ssimister] ssimister has joined #rdfval 17:24:42 [Anamitra] scribe-Anamitra 17:24:57 [roger] roger has joined #rdfval 17:25:04 [dbs] aside: thanks to everyone for being so good to us remote attendees :) 17:25:04 [kcoyle] it's hard to hear - we may need some structure to be able to get participation of the phone people 17:25:09 [SteveS] Scribe: Anamitra 17:25:14 [PhilA] q+ to talk about queuing 17:25:19 [DavidBooth] Topic: Discussion 17:25:23 [PhilA] ack me 17:25:23 [Zakim] PhilA, you wanted to talk about queuing 17:25:27 [hsolbri] hsolbri has joined #rdfval 17:25:34 [kcoyle] +1 dbs -- keeping track of the slides is a big help 17:26:35 [arthur] arthur has joined #rdfval 17:26:37 [Anamitra] up next Alignment of requirements and technology 17:26:42 [labra] labra has joined #rdfval 17:28:07 [Anamitra] Arnaud: questions regarding what we want to do 17:28:22 [Anamitra] Arnaud: capture use cases 17:28:53 [Anamitra] Arnaud: its just not about validation - its abt describing the Resource too 17:29:10 [Zakim] +[IPcaller] 17:29:19 [tbaker] zakim, IPcaller is tbaker 17:29:20 [Zakim] +tbaker; got it 17:29:42 [PhilA] q+ 17:29:50 [Arnaud] ack PhilA 17:30:22 [hsolbri] q+ 17:30:29 [Arnaud] ack hsolbri 17:30:31 [arthur] q+ to describe scope 17:30:34 [mgh] XSD can also be used to generate an instance XML document example from an XSD. Do we need that kind of capability? - to generate a set of triples from a description? 17:30:39 [Anamitra] _:describe and validation are different 17:31:16 [Arnaud] s/_/PhilA/ 17:31:24 [Arnaud] ack arthur 17:31:24 [Zakim] arthur, you wanted to describe scope 17:31:26 [ericP] hsolbri: in many cases, i don't need to go to SPARQL 17:31:29 [Anamitra] harold: want to publish what you expect without going to SPARQL 17:31:42 [Zakim] -dbs 17:31:52 [ericP] ... if i import data from an RDB with a good model, all i need from our language is to publish the description 17:31:53 [PhilA] +1 to Harold 17:32:35 [Anamitra] Arthur:just calling this workshop validation is not accurate 17:32:57 [Anamitra] ericP: lets call it validation and description 17:33:03 [Anamitra] +1 ericP 17:33:12 [hsolbri] Characterization? 17:33:55 [Anamitra] ericP:constraints is not a clear way to describe a resource 17:34:04 [kcoyle] q+ to ask about defining description 17:34:17 [Arnaud] ack kcoyle 17:34:17 [Zakim] kcoyle, you wanted to ask about defining description 17:34:54 [TimCole] +q 17:35:00 [Arnaud] ack TimCole 17:35:01 [ericP] kcoyle: when we talk about validation description, or do we have a broader view of description? 17:35:03 [Anamitra] kcoyle:there are certails aspects that are just description without any validation aspect 17:36:33 [Anamitra] hsolbri: we need something that does not imply process 17:36:49 [TimCole] To provide scope, do we want though to focus on descriptive aspects that support validation? 17:37:54 [evrensirin] q+ to comment about being careful about descriptions 17:38:01 [Anamitra] hsolbri: testcases for RDF and sw that produces RDF is to be considered 17:38:32 [Anamitra] Arnaud: Resource shape serves dual purpose of describe and validation 17:38:35 [Arnaud] ack evrensirin 17:38:35 [Zakim] evrensirin, you wanted to comment about being careful about descriptions 17:38:54 [gjiang] q+ 17:39:37 [PhilA] q+ to talk about the likely new CSV on the Web WG which, in some ways, is closely related 17:39:40 [arthur] q+ to discuss how resources can use existing vocabularies in a novel way 17:40:04 [Anamitra] evrensirin: define the scope - main goal validation - side goal is describe the resource 17:40:10 [Arnaud] ack gjiang 17:40:45 [Arnaud] ack PhilA 17:40:45 [Zakim] PhilA, you wanted to talk about the likely new CSV on the Web WG which, in some ways, is closely related 17:40:45 [Anamitra] gjiang: low level user should be able to define the constraints like UML 17:40:51 [PhilA] -> CSV on the WEb 17:40:59 [hsolbri] gjiang: we may need an OCL for the description language as well 17:42:12 [Anamitra] philA: similar to csv metadata - like headers and data type 17:42:19 [hsolbri] q+ to say CSV is on our radar itself. We started with UML / XML Schema, need to produce RDF equiv and CSV 17:42:55 [Arnaud] ack arthur 17:42:55 [Zakim] arthur, you wanted to discuss how resources can use existing vocabularies in a novel way 17:43:54 [Anamitra] arthur: we need to describe resources/documents - you can describe that without inventing any new RDF terms 17:44:53 [ericP] q? 17:45:17 [Anamitra] arthur: we should avoid inventing vocab terms if we can 17:45:37 [Anamitra] Arthur: and re-use as much we can 17:47:08 [Arnaud] ack hsolbri 17:47:08 [Zakim] hsolbri, you wanted to say CSV is on our radar itself. We started with UML / XML Schema, need to produce RDF equiv and CSV 17:47:54 [Ashok_Malhotra] Ashok_Malhotra has joined #rdfval 17:47:57 [Anamitra] hsolbri: omv - schema for describing ontology - modeled in RDF 17:48:25 [Anamitra] hsolbri: started with UML 17:48:51 [Anamitra] hsolbri: UML->XML schema 17:50:02 [Anamitra] hsolbri: we need to be able to exchange constraints between different modeling framwork - UML, RDF 17:50:18 [Ashok_Malhotra] q+ 17:50:19 [PhilA] +1 to hsolbri 17:50:23 [Arnaud] ack Ashok_Malhotra 17:51:28 [Anamitra] Ashok_Malhotra: UML is useful - lets focus on just RDF validation - and then build tooling later for covering exchange between models - keep the swcope small 17:52:05 [hsolbri] q+ to rebut 17:52:52 [Anamitra] Arnaud: can define a transformation from csv to RDF and then validate using the RDF validator 17:53:05 [Arnaud] ack hsolbri 17:53:05 [Zakim] hsolbri, you wanted to rebut 17:54:01 [Anamitra] hsolbri: UML and xml schema community has already done the groudwork - lets start with that - as relevant to RDF 17:54:37 [arthur] q+ to say UML has a different perspective 17:54:43 [arthur] q+ 17:54:56 [arthur] q+ 17:55:02 [Anamitra] sandro: there is too much mismatch between these models 17:55:09 [Ashok_Malhotra] q? 17:55:12 [arthur] arthur has joined #rdfval 17:56:23 [Anamitra] hsolbri: RDF type analogus to UML class and UML attribute to RDF predicate 17:56:59 [kcoyle] q+ to caution about starting with UML or XML or ?? 17:58:02 [Arnaud] ack arthur 17:58:02 [Zakim] arthur, you wanted to say UML has a different perspective and to and to 17:58:07 [Anamitra] arnaud: guided by UML - makes sense 17:58:23 [Anamitra] arthur: fundamental mismatch between UML and RDF 17:58:51 [Anamitra] arthur: RDF class is a classification - a resource can have many classification 17:59:39 [Anamitra] arthur: UML and RDF has intersection - so u can do a OO model as RDF - but not the other way 17:59:46 [ericP] q+ 18:00:08 [Anamitra] hsolbri: lossy in both direction 18:00:29 [SteveS] q+ 18:00:35 [Anamitra] arthur: oo is abt info hiding - 18:01:04 [ericP] q+ to say that it's probable that the info that we care about for shape/pattern description is largely covered by UML 18:01:09 [Arnaud] ack kcoyle 18:01:09 [Zakim] kcoyle, you wanted to caution about starting with UML or XML or ?? 18:01:26 [Anamitra] kcoyle: agree with Arthur - 18:02:32 [Anamitra] kcoyle: UML and other models comes with baggage 18:02:35 [Arnaud] ack ericP 18:02:35 [Zakim] ericP, you wanted to say that it's probable that the info that we care about for shape/pattern description is largely covered by UML 18:04:09 [Arnaud] ack SteveS 18:04:55 [Anamitra] SteveS: UML has evolved 18:07:07 [Anamitra] sandro: we should have a way to produce the RDF constraints as UML diagrams 18:07:10 [arthur] q+ 18:07:18 [Arnaud] ack arthur 18:07:28 [mgh] q+ 18:07:47 [Arnaud] ack mgh 18:07:57 [Anamitra] arthur: ER diagrams precede UML 18:08:07 [hsolbri] q+ to change the subject. 18:08:20 [Arnaud] ack hsolbri 18:08:20 [Zakim] hsolbri, you wanted to change the subject. 18:08:41 [kcoyle] SteveS: flow-charting 18:09:02 [DavidBooth] q+ to say I think it would be helpful if we roughly ranked our use cases and requirements 18:09:19 [DavidBooth] I have to leave now :( 18:09:56 [kcoyle] can't we start as a community group? 18:10:25 [arthur] q+ 18:10:42 [Ashok_Malhotra] q+ 18:11:26 [Arnaud] ack David 18:11:26 [Zakim] DavidBooth, you wanted to say I think it would be helpful if we roughly ranked our use cases and requirements 18:12:15 [Arnaud] ack arthur 18:13:29 [Anamitra] arthur: we need to plan - have atleast 2 stages - 18:13:45 [ericP] q+ to ask if the description and validation of the issue tracking document in seems useful to all of us here 18:14:03 [Anamitra] arthur:statge 1>extremely simple spec - then follow that up with the stage 2 18:14:07 [ericP] q+ sandro 18:14:14 [Arnaud] ack Ashok_Malhotra 18:15:31 [Anamitra] Ashok_Malhotra: easy declarative stuff for 80% of stuff - and the SPARQL for rest of it 18:15:35 [Arnaud] ack ericP 18:15:35 [Zakim] ericP, you wanted to ask if the description and validation of the issue tracking document in seems useful to all of us here 18:15:50 [Anamitra] +1 Ashok_Malhotra 18:16:09 [Arnaud] ack sandro 18:16:46 [arthur] q+ 18:17:33 [Arnaud] ack arthur 18:17:55 [kcoyle] sandro: start with a spec, get all of the right people in the room 18:18:24 [hsolbri] q+ to ask eric a question about pushback 18:18:39 [Arnaud] ack hsolbri 18:18:39 [Zakim] hsolbri, you wanted to ask eric a question about pushback 18:19:41 [Anamitra] hsolbri: do we have a political issue for validating RDF - 18:21:15 [TimCole] +q Reaction may depend on definition of validation. 18:21:43 [TimCole] q+ to suggest that reaction may depend on definition of validation 18:22:11 [Anamitra] sandro: consumers need to know about what they are consuming - that argument works - as opposed to a triple store needing that info 18:23:33 [Arnaud] ack TimCole 18:23:33 [Zakim] TimCole, you wanted to suggest that reaction may depend on definition of validation 18:23:58 [SteveS] Based on past discussions within context of LDP: I think Tim and Henry see the need/motivation for this thing we called validation 18:24:24 [Anamitra] TimCole: want to stay away from just a binary result - valid or not - give information about the result 18:26:22 [Anamitra] _: the simple declarative format will lend itself to autogenerate SPARQL 18:26:32 [ericP] q? 18:26:44 [ericP] q+ 18:26:48 [evrensirin] q+ to comment on simplicity 18:26:53 [Arnaud] ack ericP 18:27:35 [Arnaud] ack evrensirin 18:27:35 [Zakim] evrensirin, you wanted to comment on simplicity 18:28:11 [Anamitra] ericP: if simple format is not able to define something - we will need to re-look as to whether we can improve it to cover that 18:28:22 [arthur] q+ 18:28:45 [Arnaud] ack arthur 18:29:26 [kcoyle] can't hear - pls scribe! thx 18:29:38 [Anamitra] Arthur: disjoint constraint can be added to resource shape 18:29:57 [Anamitra] Arthur: should be driven by use cases 18:30:37 [Anamitra] Ashok_Malhotra: do we have people who will like to start of this spec? 18:30:58 [Anamitra] Arthur: I would 18:31:19 [arthur] q+ 18:31:23 [Anamitra] Arnaud: is it a requirement to make this language RDF 18:31:37 [kcoyle] DCMI can offer the constraints in DSP - Arthur, I will do that 18:32:42 [evrensirin] q+ about RDF representation 18:32:51 [Anamitra] ericP: the primary language should be RDF 18:32:52 [evrensirin] q+ to talk about RDF representation 18:33:34 [kcoyle] +1 needs to be demonstrable 18:34:03 [tbaker] +1 agree that should be representable, not necessarily represented, in RDF - who am I agreeing with (is this being scribed)? 18:34:48 [Anamitra] hsolbri: description should exist in SPARQL query form 18:34:57 [Ashok_Malhotra] q+ 18:34:58 [Arnaud] ack arthur 18:36:01 [Anamitra] arthur: the more declaritive the language is - the easier it is to define in RDF 18:37:01 [Arnaud] ack evrensirin 18:37:01 [Zakim] evrensirin, you wanted to talk about RDF representation 18:37:25 [ericP] q+ to say that the requirement we're discussing is whether the expression in RDF is *interoperable* 18:37:49 [Anamitra] evrensirin:atleast have a way to specify sparql as a literal in the constraint language 18:38:06 [Arnaud] ack Ashok_Malhotra 18:39:04 [Anamitra] Ashok_Malhotra: schema for schemas never worked 18:40:02 [Arnaud] ack ericP 18:40:02 [Zakim] ericP, you wanted to say that the requirement we're discussing is whether the expression in RDF is *interoperable* 18:40:25 [Anamitra] ericP: interoperable RDF representation 18:40:47 [arthur] q+ 18:42:08 [Anamitra] hsolsbri: represent in RDF as much as possible - should be able to publish a standard representation form 18:42:13 [Arnaud] ack arthur 18:43:04 [kcoyle] pls scribe 18:43:06 [tbaker] rrsagent, please draft minutes 18:43:06 [RRSAgent] I have made the request to generate tbaker 18:44:03 [Arnaud] q? 18:44:10 [tbaker] didn't catch the point about SKOS - or who was talking... 18:44:31 [arthur] Eric was talking about SKOS 18:44:37 [tbaker] thnx 18:44:55 [Arnaud] scribe: TimCole 18:45:27 [TimCole] Can we define next steps 18:46:00 [TimCole] Do we agree that a Working Group should be formed to make a new declarative language with fall back to SPARQL 18:46:29 [TimCole] To speed things along we should start from a preliminary spec? Who would do this? 18:47:16 [kcoyle] I offered DSP structure and constraints to Arthur 18:47:37 [TimCole] Candidates. ResourceShape, Shape Expressions, DSP 18:48:26 [TimCole] Arthur. There will have to be a call... 18:49:02 [roger] can you send a link to your "shape expressions" information please Eric ? 18:49:39 [tbaker] wondering whether there is consensus that a working group is needed as opposed to a community group (as Karen suggested) 18:49:51 [TimCole] Arnuad: The working group will be chartered to use a spec as starting point, but WG can throw the spec out and start again. 18:50:47 [PhilA] q+ to talk a little about W3C process 18:51:39 [TimCole] evrensirin: Could the WG start with multiple specs? 18:52:01 [TimCole] Arnaud: There are IP issues which make this approach more difficult. 18:52:09 [Arnaud] ack PhilA 18:52:09 [Zakim] PhilA, you wanted to talk a little about W3C process 18:52:45 [TimCole] PhilA: To get a WG chartered, need bums on seats 18:52:59 [kcoyle] TimCole: :-) 18:53:04 [SteveS] q+ to talk about doing joint submission 18:53:26 [Arnaud] ack SteveS 18:53:26 [Zakim] SteveS, you wanted to talk about doing joint submission 18:53:48 [TimCole] SteveS: Submission (of starting spec) can be collaborative. 18:54:24 [TimCole] Arnaud: Charters need to be approved by W3C mgmt, and then by members. 18:55:01 [TimCole] Arnaud: A draft charter is developed on mailing list. Responses feed the process of moving the charter forward. 18:56:17 [TimCole] Arnaud: If interested in submitting a spec to serve as starting point, need to submit to W3C to clear IP issues. 18:56:42 [TimCole] Arnaud: process takes a few months. PhilA: at least. 18:58:30 [TimCole] TimCole: Do we need to do any winnowing or prioritizing of list developed yesterday? 18:59:02 [kcoyle] TimCole: list needs a fair amount of work 18:59:03 [TimCole] Arnaud: Have we done enough for now? Let Chairs move forward, form mailing list, etc. 18:59:22 [TimCole] Arnaud: Or we can work a little longer? 19:00:03 [TimCole] evrensirin; We need to say a little more about needs and priorities 19:00:27 [ericP] -> SOTA ex 19:00:30 [tbaker] q+ to ask if a WG is really needed. Why not a Community Group? 19:01:23 [TimCole] ericP: The example implies some things about expressivity and interface 19:01:59 [TimCole] evrensirin: Wants to talk more about higher level aspects of use case. Who's this for? 19:02:31 [TimCole] ericP: Wants to keep concrete though. Not too hi-level. 19:02:34 [Arnaud] ack tbaker 19:02:34 [Zakim] tbaker, you wanted to ask if a WG is really needed. Why not a Community Group? 19:02:41 [PhilA] q+ to answer Tom 19:03:09 [TimCole] tbaker: Given lack of really strong agreement on task needed, do we want to start with a Community Group 19:04:04 [TimCole] Arnaud: Community Groups are recent. More of a forum to work together. No resources or formal endorsement by the W3C. 19:04:43 [PhilA] ack me 19:04:43 [Zakim] PhilA, you wanted to answer Tom 19:04:46 [TimCole] Arnaud: At best CG creates a spec which would need to be submitted, go through a WG, and then be ratrified. 19:04:46 [Arnaud] ack PhilA 19:05:45 [TimCole] PhilA: Some commercial entities reluctant to implement a CG spec. 19:06:39 [TimCole] Arnaud: Some success stories, but really though the startup is faster in the end not really faster in the end. 19:07:06 [TimCole] PhilA: if we can get a WG charter that tends to be better 19:07:30 [arthur] q+ 19:07:55 [Arnaud] ack arthur 19:08:16 [tbaker] +1 depends on how mature the concept is, and easier to involve people with CG 19:08:24 [TimCole] arthur: I think this is a mature area, and so appropriate for a WG 19:09:14 [TimCole] Arnaud: Going back to having people commit. Do we have a critical mass? 19:09:24 [TimCole] Arnaud: Who here would commit? 19:09:29 [arthur] +1 19:09:33 [hsolbri] +1 19:09:34 [ericP] +1 19:09:37 [roger] +0.6 19:09:39 [labra] +1 19:09:44 [evrensirin] +1? 19:09:54 [kcoyle] ~1 (unsure) 19:09:58 [mesteban] mesteban has joined #rdfval 19:10:05 [nmihindu] +1 19:10:31 [TimCole] TimCole: harder to join WG if your institution not part of W3C 19:10:36 [tbaker] +0.6 19:10:40 [ssimister] 0.5 not sure yet 19:10:44 [Ashok_Malhotra] 0 19:10:48 [mSkjaeveland] 0 19:10:48 [mesteban] +0.5 19:10:50 [mgh] +0.5 not sure yet 19:10:53 [TimCole] -1 since Illinois not part of W3C 19:11:12 [ddolan] +0.5 19:11:13 [SteveS] +0.1 I will participate through Arthur/Arnaud, definitely support it 19:11:57 [Ashok_Malhotra] Community Groups cannot create standards 19:12:32 [TimCole] tbaker: Not sure we are really ready to write a good charter yet. 19:12:58 [Ashok_Malhotra] q+ 19:13:12 [Arnaud] ack Ashok_Malhotra 19:15:23 [TimCole] Arnaud: Let's get back to what the problem we're trying to solve? 19:15:53 [TimCole] Arnaud: Let's focus on the use cases. 19:16:03 [Arnaud] 19:16:26 [kcoyle] pad has requirements, but not use cases. need to gather use cases 19:17:21 [kcoyle] most of the talks represented one or more use cases 19:17:30 [TimCole] moving to pirate pad now. 19:25:03 [mesteban_] mesteban_ has joined #rdfval 19:25:41 [Zakim] -kcoyle 19:27:54 [dbooth] dbooth has joined #rdfval 19:28:45 [dbooth] zakim, code? 19:28:45 [Zakim] the conference code is 733825 (tel:+1.617.761.6200 sip:zakim@voip.w3.org), dbooth 19:29:06 [Zakim] +DBooth 19:29:47 [dbooth] rrsagent, draft minutes 19:29:47 [RRSAgent] I have made the request to generate dbooth 19:56:25 [Arnaud] q? 19:57:03 [dbooth] q+ to suggest roughly prioritizing use cases and requirements 19:59:24 [Arnaud] ack dbooth 19:59:24 [Zakim] dbooth, you wanted to suggest roughly prioritizing use cases and requirements 20:01:57 [SteveS] How about a X day effort to build the list of requirements and/or use-cases, then Y day effort to prioritize them (using a surveying tool)? 20:05:11 [TimCole] TimCole has left #rdfval 20:15:30 [dbooth] q+ to say it is important to be able to apply different schemas to the same datasets 20:20:01 [Arnaud] ack dbooth 20:20:01 [Zakim] dbooth, you wanted to say it is important to be able to apply different schemas to the same datasets 20:20:35 [PhilA] rrsagent, make logs public 20:20:41 [PhilA] rrsagent, generate minutes 20:20:41 [RRSAgent] I have made the request to generate PhilA 20:21:16 [PhilA] PhilA has left #rdfval 20:21:47 [Zakim] -DBooth 20:22:21 [Zakim] -tbaker 20:23:27 [dbooth] Meeting: RDF Validation Workshop 20:23:34 [dbooth] rrsagent, draft minutes 20:23:34 [RRSAgent] I have made the request to generate dbooth 20:24:29 [dbooth] Chair: Arnaud Le Hors and Harold Solbrig 20:24:36 [dbooth] rrsagent, draft minutes 20:24:36 [RRSAgent] I have made the request to generate dbooth 20:25:26 [gjiang] gjiang has joined #rdfval 20:25:53 [Zakim] -Workshop_room.a 20:25:54 [Zakim] SW_(RDFVal)8:30AM has ended 20:25:54 [Zakim] Attendees were kcoyle, Workshop_room, DaveReynolds, hhalpin, dbs, Workshop_room.a, tbaker, DBooth 20:30:51 [dbs] dbs has left #rdfval 20:46:19 [PaulD] PaulD has joined #rdfval 21:51:10 [Arnaud] Arnaud has joined #rdfval 22:32:23 [Zakim] Zakim has left #rdfval
http://www.w3.org/2013/09/11-rdfval-irc
CC-MAIN-2016-36
refinedweb
8,245
50.4
Since I am in between real projects right now, I have had some time to work on some side projects. As I was working on some threading in one of these projects, I noticed that there was a new class in the System.Threading namespace that had not been there in .NET 1.1 ... EventWaitHandle. I was curious to see what this new class was. Background Info: Windows exposes several types of synchronization primitives (Mutexes, Events, etc.), but in .NET 1.1 we were limited in our use of them. Sure, we had AutoResetEvent and ManualResetEvent, but the framework did not expose the "named" version of these. In case you were wondering, the "named" version allows us to share an event between two (or more) processes. The name makes it easy for multiple processes to say "give me 'EventA' "!! So before 2.0, we had pretty good support for synchronization within a process, but not very good support across processes. Yes, in .NET 1.1, we could get to this functionality using PInvoke, but it could get complicated quickly because you can attach security descriptors to an event. And anyone who has tried to PInvoke to set some ACLs can tell you that security descriptor is a beast that you don't want to be playing with in C#. Fortunately this has been remedied in the 2.0 framework, and the Access Control Lists are now 1st class .NET objects. I am going to go out on a limb and speculate that this is why named events were not included in the first version of the framework. Back on Track: "Great!" you say, but what the heck does this have to do with EventWaitHandle? Well, EventWaitHandle is .NET 2.0's implementation of events -- both named and unnamed. You can see that ManualResetEvent and AutoResetEvent now inherit from EventWaitHandle. So, let's get started and see what we can create with this. In this example, WorkerA does some work, which notifies WorkerB who begins some work, which notifies WorkerC to finish up some work. You can see that we are creating a simple pipeline. (A real pipeline would keep working, but ours just exits after one iteration). Let's start by providing some tools for these events to get access to the events. public static class NamedEvents { public static EventWaitHandle OpenOrCreate(string name, bool initialState, EventResetMode mode) { EventWaitHandle ewh = null; try { ewh = EventWaitHandle.OpenExisting(name); } catch (WaitHandleCannotBeOpenedException) //Handle does not exist, create it. ewh = new EventWaitHandle(initialState, mode, name); return ewh; } public static EventWaitHandle OpenOrWait(string name) while (null == ewh) try { ewh = EventWaitHandle.OpenExisting(name); } catch (WaitHandleCannotBeOpenedException) Thread.Sleep(50); } We've provided the tools to create an event if it doesn't already exist or open it if it does, and to open an existing event or wait for it to be created. Unfortunately there is not a good way to "test" if an event exists, so we just have to catch WaitHandleCannotBeOpenedException. Here is our code for WorkerB, though the other workers are almost identical except that they set and wait on different events. static void Main(string[] args) EventWaitHandle completedA = NamedEvents.OpenOrWait("CompletedA"); EventWaitHandle completedB = NamedEvents.OpenOrCreate("CompletedB", false, EventResetMode.ManualReset); EventWaitHandle pipelineDone = NamedEvents.OpenOrWait("PipelineDone"); Console.WriteLine("{0} Initialized", Process.GetCurrentProcess().ProcessName); completedA.WaitOne(); for (int i = 0; i < 10; i++) Thread.Sleep(250); Console.WriteLine("{0} Working: {1:hh-mm-ss.ffff}", Process.GetCurrentProcess().ProcessName, DateTime.UtcNow); Console.WriteLine("{0} Done", Process.GetCurrentProcess().ProcessName); completedB.Set(); //wait until the whole pipeline is done. pipelineDone.WaitOne(); completedB.Close(); Console.WriteLine("{0} Exiting", Process.GetCurrentProcess().ProcessName); In the output, we can see that B waits for A to finish, and C waits for B to finish. Now, you know how to use named events!!
http://blogs.msdn.com/b/mattdotson/archive/2006/03/03/543143.aspx
CC-MAIN-2014-35
refinedweb
627
58.58
Computer Science Archive: Questions from February 24, 2011 - Anonymous askedFind the minimum sum of products expression for: f(w,x,y,z)= sigma m(2,3,4,5,6,7,9,10,11,13) f(a,b,c,... Show moreFind the minimum sum of products expression for: f(w,x,y,z)= sigma m(2,3,4,5,6,7,9,10,11,13) f(a,b,c,d)= sigma m (0,2,3,7,8,9,13,15) + sigma d(1,12) • Show less1 answer - Anonymous askedAn array is sparse if most of its entries are null. A list L can be used to implement such an array,... More »1 answer - Anonymous asked2 answers - Anonymous askedThe local Registry of Motor Vehicle office has asked you to creat an application that grades the wri... Show moreThe local Registry of Motor Vehicle office has asked you to creat an application that grades the written portion of the driver's license exam. The exam has 20 mulitple choice questions. Here are the correct answers to the questions: 1. B 6. A 11. B 16. C 2. D 7. B 12. C 17. C 3. A 8. A 13. D 18. B 4. A 9. C 14. A 19. D 5. C 10. D 15. D 20. A Your application should store the correct answers in an array. The form should allow the user to enter answers for each question. When the user clicks the Score Exam button, the application shoudl dislay another form showing whether each question was ansered correctly or incorrectly, and whether the student passed or failed the exam. A student must correctly answet 15 of the 20 questions to pass teh exam. Input validation: Pnly accept the letters A, B, C, D as answers. • Show less1 answer - Anonymous askedQ1. Des... Show moreAn element y in an array A is plural if more than half of the elements in A is the same as y. Q1. Design an efficient divide-and-conquer algorithm that determines whether an Array A contains a plural element y and if so, returns y. Note that the elements of A can be compared to determine whether they are the same; however, they do not necessarily have an order. Consider that, e.g., the elements represents colors. In other words, we can check A[i]=A[j], but we cannot check A[i] > A[j]. Q2. give a tight asymptotic upper bound on the number of comparisons that your algorithm makes in the worst case. we now consider a variation of the previous question. Suppose that an array A is known to contain a plural element, and we would like to find it. Prof Smith suggests that a simple way is to guess an element from A and verify whether it is plural. Use this guess-and-verify idea to design an efficient algorithm that finds the plural element in A. Show that the expected running time of your algorithm is theta(n). • Show less0 answers - Anonymous asked0 answers - Anonymous askedwhen I run the program I"m supposed to enter (first n... Show morei have to write a program for evacuating people when I run the program I"m supposed to enter (first name, last name, male, age, income). It should prioritize children under 18 before any above 18, and for adults it should prioritize females first, and if they are the same sex, it should compare income to see which is higher. If they have the same income, then i should compare last names lexicograhically, then first names if last is the same. I don't know who to set up my if statements to compare so many of these factors with the compareTo() method. When I compile my program it does not prioritize the evacuees as it should. It prioritizes by first name and possibly age, but I think thats it. somewhere in my if statements I dont have the correct return statements or either my loops are not grouped properly? Prioritization is the most important thing for this assignment, but i can't figure out how to get SO many different factors into loops. 2) Also, we are supposed to have a "menu" when our program runs and the user is supposed to choose either 1 2 or 3. 1 to add people to a list. 2 to release the with listed people in it lifeboat ( which I haven't started on yet ) and 3 to exit the program. how to I do this menu? I use a "switch" statement? Where/which class do I put it in? This always trips me up... 3) when I get around to "2" where the user releases the lifeboat, do I just create a new class in my main to do this just as I did for creating a new person? • Show less0 answers - Anonymous askedCreate an ElapsedTimeCalculator class that computes the amount of time that passes between a startin... Show moreCreate an ElapsedTimeCalculator class that computes the amount of time that passes between a starting time and an ending time, in military format. For example, suppose the two times are 1445 and 1730. Then the program output should look something like this: Start time: 1445 End time: 1730 Exactly 2 hour(s) and 45 minute(s) have passed. Total elapsed time in minutes: 165 Total elapsed time in hours: 2.75 • Show less1 answer - Anonymous askedThe pool of free blocks is... Show moreLet 'n' identical memory blocks be set aside for allocation to processes. The pool of free blocks is maintained as a stack. We defined two system calls to request and return blocks. These system calls were: getspace :: Block getspace = getspace <-- stack[top]; top - 1 release :: Block -> () release addr = top + 1; stack[top] <-- addr We said that atomicity was a requirement for correct execution. That was a white lie. Why? Because we also need to guarantee against stack underflow. Against stack overflow too? The stack is an array. Pick and initialize semaphores for this problem. Write the synchronized code in the style of our 4-semaphore producer-consumer solution. • Show less0 answers - Anonymous askedlocal_... Show more The following section of code is an implementation of sense-reversing barrier synchronization.• Show less local_sense =!local_sense; lock(counterlock); count=count+1; unlock(counterlock); if(count==total) { count=0; release=local_sense; } else spin(release==local_sense); 1) A straightforward implementation of the highlighted three instructions is: Lockit: LL R2, 0(R1) ; assume counterlock is located at 0(R1) BNEZ R2, Lockit ADDUI R2, R0, #1 SC R2, 0(R1) BEQZ R2, Lockit LW R4, 0(R3) ; assume count is located at 0(R3) ADDUI R4, R4, #1 SW R4, 0(R3) Unlock: ADDUI R2, R0, #0 SW R2, 0(R1) 1) How do you simplify the implementation of the “Lockit” so only one store instruction is required? (1 points) 2) Compare the approach against the implementation shown below. Which program is in favor? Why? (2 points)0 answers - Anonymous asked1) If the links are du... Show more Answer the following questions based on the Hyper-Cube interconnection network 1) If the links are duplex (i.e., 1->3, and 3->1 can be done concurrently), and each node cannot receive more than 1 message in a step (i.e., 1->3 and 2->3 cannot be done concurrently). Show the minimum number of steps to complete the following communication permutation. (4 points) Sender -> Receiver • Show less0 answers - Anonymous asked1. Ins... Show moreCreate an actionscript 3 program that asks the user to enter upto 10 names into 10 textboxes: 1. Insert 10 text fields dynamically (with codes rather than dragging on the stage) 2. Insert a button labeled “Load”. When it is pressed, the program will populate an array with the names from the textboxes. (Do not copy the textboxes, just the names (strings) inside them) 3. Insert a button labeled “Print”. When it is pressed, the program will output the names in the array into a textbox. 4. Insert a button labeled “Reverse”. When it is pressed, the program will output the names in the array into a textbox. 5. Insert a button labeled “Random”. When it is pressed, the program will rearrange the names in the array in a random order and output the elements of the array into a texrbox. (a loop in this situation is more efficient) Note: Please if you can’t do the whole project, just do it one question at a time..thnxx! • Show less0 answers - EducatedColor694 asked2 answers - Anonymous asked1)reads from a text file and makes an alphabetical list of all the words in that file. the list of w1 answer - Anonymous askedDevelop a program to maintain a list of homework assignments. When an assignment is assigned, add it... Show moreDevelop a program to maintain a list of homework assignments. When an assignment is assigned, add it to the list, and when it is completed, remove it. You should keep track of the due date. Your program should provide the following services: 1. Add a new assignment. 2. Remove an assignment. 3. Provide a list of the assignments in the order they were assigned. 4. Find the assignment(s) with the earliest due date. Basically...I'm looking to a program that performs the functions above from a users input with a similar menu/layout to this one. import java.util.*; public class Driver { public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); ArrayList <Inventory>ingredients = new ArrayList<Inventory>(); String name; String measurement; int units; int menuChoice=menu(); int i; int addOn; while(menuChoice!=5) { if(menuChoice==1) { System.out.println("What type of ingredient would you like to add?"); name=keyboard.nextLine(); System.out.println("What is "+name+" measured in?"); measurement=keyboard.nextLine(); System.out.println(""); System.out.println("How many "+measurement+" of "+name+" do you have?"); units=keyboard.nextInt(); keyboard.nextLine(); System.out.println(""); Inventory foodItem = new Inventory(name, measurement, units); ingredients.add(foodItem); } else if(menuChoice==2) { for(i=0; i<ingredients.size(); i++) { System.out.println(i +") "+ingredients.get(i).toString()); } System.out.println("What would you like to add to?"); int x = keyboard.nextInt(); addOn=ingredients.get(x).getUnits(); System.out.println("How many "+ingredients.get(x).getMeasurment()+" would you like to stock?"); addOn+=keyboard.nextInt(); ingredients.get(x).setUnits(addOn); } else if (menuChoice==3) { for(i=0; i<ingredients.size(); i++) { System.out.println(i +") "+ingredients.get(i).toString()); } System.out.println("Which item would you like to use?"); int x = keyboard.nextInt(); addOn=ingredients.get(x).getUnits(); System.out.println("How many "+ingredients.get(x).getMeasurment()+" would you like to use?"); addOn-=keyboard.nextInt(); ingredients.get(x).setUnits(addOn); } else if (menuChoice==4) { for(i=0; i<ingredients.size(); i++) System.out.println(ingredients.get(i).toString()); } menuChoice=menu(); } } public static int menu() { Scanner keyboard = new Scanner(System.in); int menuChoice; System.out.println("Please select an option"); System.out.println("1)Add inventory"); System.out.println("2)Stock inventory"); System.out.println("3)Use ingredients"); System.out.println("4)Display ingredients"); System.out.println("5)Exit program"); menuChoice = keyboard.nextInt(); while(menuChoice < 1 || menuChoice > 5) { System.out.println("Invalid please try again"); menuChoice = keyboard.nextInt(); } return menuChoice; } } public class Inventory { int units; String name; String measurment; public Inventory(String nameIn,String measurmentIn, int unitsIn) { name=nameIn; measurment=measurmentIn; units=unitsIn; } public int getUnits() { return units; } public void setUnits(int units) { this.units = units; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getMeasurment() { return measurment; } public void setMeasurment(String measurment) { this.measurment = measurment; } public String toString() { String foodInfo="you have "+units+" "+measurment+" of "+name; return foodInfo; } } Thanks! • Show less1 answer - DiligentDragon7282 asked1 answer - DiligentDragon7282 asked(Algorithms: Complexit... Show more Write a (n) algorithm for sorting n distinct integers, ranging from 1 to 20n. (Algorithms: Complexity Analysis)• Show less1 answer - BlueSpring21 askedIn one of my homework problem, I have to write a MIPS program, however, I am new to MIPS and I w... Show more Hi, In one of my homework problem, I have to write a MIPS program, however, I am new to MIPS and I would like learn how to write a MIPS assembly program that uses a procedure to calculate 8x-7y+z. Thanks in advance. Here are some rules. The procedure named proc . The "main" calling routine will ask the user for the variables (x,y,z). These values will be passed to the procedure using the appropriate registers. Before calling the procedure, set $s0 to 3010 and $s1 to 4510. In proc, put 8x in the register $s0 and 7y in register $s1. Using these values to form the answer in $v0 before returning. After you return to the "caller", print the registers $s0 and $s1 to show their value has not been changed by proc. Then print the result with the user's input for x,y,z ----------------------------- Ex: Please enter X: 8 Please enter Y: 4 Please enter Z: 6 After returning from the procedure $s0 = 30 $s1 = 45 The result of the equation is : 42 --------------------------------------------• Show less1 answer - DiligentDragon7282 asked1 answer - DiligentDragon7282 asked2 answers - DiligentDragon7282 askedConsider a hybrid algorithm for sorting. This algorithm uses both bubble sort with time complexity o... Show more Consider a hybrid algorithm for sorting. This algorithm uses both bubble sort with time complexity of O(n2) and merge sort with time complexity of . First a list of n numbers are divided into sublists with numbers in each sublist. Next, each sublist is sorted by the bubble sort algorithm. Finally, these sorted sublists are merged to obtain a sorted list. Find the complexity of this algorithm.• Show less1 answer - Anonymous askeda) List the types of models that might be used in requirements... Show moreThere are two parts to this question: a) List the types of models that might be used in requirements modeling and describe what the model contains and the purpose or role of each type of model. b) Explain what is wrong with the notion that computer software does not need to evolve over time. • Show less1 answer - Anonymous askedI'm am trying to write a code that helps people get off of a boat. I have a menu where the user can... Show moreI'm am trying to write a code that helps people get off of a boat. I have a menu where the user can choose 1 to add more people to a list, 2 to release the people in the list to a lifeboat, and 3 to exit. I have to create the classes and methods. I've created a class that prioritizes people when they are added to the list, then sorts them using Arrays.sort, and I'm trying to create a class that will gather those sorted people and allow a certain amount of them to get onto the lifeboat( how ever many the lifeboat can fit). This is what i need to happen when the user chooses option 2. I am very stuck. 1 seems to work well enough, but I can't go from there. I've commented my code to help show what I was TRYING to do.... package evacuation; import java.io.*; import java.util.*; public class Evacuation { static Evacuee newPerson(Scanner scan1) //what happens when i press 1 { System.out.println("What is the evacuee's first name? "); String firstn = scan1.next(); System.out.println("What is the evacuee's last name? "); String lastn = scan1.next(); System.out.println("Is the evacuee 'male' or 'female'"); boolean sex = scan1.next() != null; //not sure if this is gonna do what I need it to... System.out.println("What is the evacuee's age"); int age = scan1.nextInt(); System.out.println("What is the evacuee's annual income"); int income = scan1.nextInt(); return new Evacuee(firstn, lastn, sex, age, income); } static void waitList(Scanner scan1, int numPeople) // reads in a specific (numPeople) of ppl { Evacuee[] listArray = new Evacuee[numPeople]; //listArray is array of Evacuees for(int i = 0; i <numPeople; i++) listArray[i] = newPerson(scan1); // set each Evacuee to each index in listArray System.out.println("These Are The Following People In The List..."); //System.out.println(); //System.out.println(); for(int i = 0; i < listArray.length; i++) //hopefully goes through the array and prints the Evacuees { System.out.println(listArray[i]); } System.out.println(); System.out.println(); Arrays.sort(listArray); System.out.println("These Are The People In Prioritized Order..."); for(int i = 0; i < listArray.length; i++) { System.out.println(listArray[i]); } } //I need to create this which is what would happen wwhen option 2 is chosen //what I'm trying to do: read in the sorted array listArray and print out the number of Evacuees //in the array up to a certain number. The number of people I want to print out from listArray //is boatSize number of people. But an error i get is that listArray cannot be resolved to a variable static void lifeBoat(Scanner scan1) { System.out.println("How many people can the lifeboat hold? "); //where the confusion starts. int boatSize = scan1.nextInt(); System.out.println(); // Evacuee[] boatArray = new Evacuee[boatSize]; // for(int i = 0; i < boatSize; i++) // boatArray[i] = Arrays.sort(listArray); } public static void main(String[] args) { System.out.println("Welcome! You're Probably About To Die! MAKE IT QUICK..."); System.out.println("1. Add Person To List..."); System.out.println(); System.out.println("2. Release Lifeboat..."); System.out.println(); System.out.println("3. Exit Program And SAVE YOURSELF!!!"); Scanner scan0 = new Scanner(System.in); int choice = scan0.nextInt(); switch (choice) { case 1: { Scanner scan1 = new Scanner(System.in); waitList(scan1, 2); } break; case 2: { } break; case 3: System.exit(1); } } } • Show less2 answers - Anonymous asked1 answer - Anonymous asked0 answers - SparklingRiver8452 askedA self organizing list is a linked list in which elements which are used get moved to... Show moreSpecification: A self organizing list is a linked list in which elements which are used get moved to the front of the list. Write a generic doubly-linked list class called SOList that implements the SOListInterface interface. New elements should be added to the front of the list. When an element is accessed by a find operation, it should be moved to the front of the list. You should have a private inner class Node for constructing the list. Implement an Iterators using a private inner class. Your iterators should include a remove() method which works in the conventional way. This means remove should be legal only if the operation follows a next() operation in which case the previously returned object is removed. Your iterator should be fail fast which means that any operation that changes the state of the list should cause any iterator that did not perform that operation to fail the next time it is used. You can mimic the way the java LinkedList class handles this via the following "helper" method final void checkForComodification() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); } Override the toString method for the list. Create a test class that contains JUnit tests. Define tests that exercise all of the functionality of the list. You should have one or more tests for every method in the list and iterator classes. You will be graded on the completeness of your tests. Below is the SOListInterface import java.util.*; /** * This interface provides an abstraction for a self-organizing * list which has the following properties: * -- Additions are made to the front of the list. * -- If a "find" operation succeeds, the associated * element is placed at the front of the list; * the order of the remaining elements does not change. */ public interface SOListInterface<E> { /** * The following method should add the new element * to the front of the list. * * @param obj -- the data object to be added. */ public void add(E obj); /** * Returns the first element from the list. * * @returns the data object from the first cell. * @throws NoSuchElementException if the list is empty. */ public E get(); /** * The remove() method removes the first element * of the list. This method normally follows * an application of a successful find operation. * * @return the data member associated with the * first cell. * @throws NoSuchElementException if the list * is empty. */ public E remove() throws NoSuchElementException; /** * The following method returns the data member * of a cell or null if the object is not in * the list. If present, the method moves the * the cell to the front of the list before * returning the value. * * @param obj -- the data value to match (via * equals). * @throws NoSuchElementException if the list * is empty. */ public E find(E obj); /** * Returns the number of elements in the list. */ public int size(); /** * The iterator() method returns an Iterator. * * @return an Iterator for the list. * */ public Iterator<E> iterator(); } • Show less0 answers - Anonymous askedWhat types of diagram is shown in the following illustration? Assume you are a software engineer exp... Show more • Show less What types of diagram is shown in the following illustration? Assume you are a software engineer explaining the requirements and functionality to a prospective end user or customer. Provide a written description of the diagram.1 answer - Anonymous asked1 answer - Anonymous asked- Takes three inputs from the... Show moreBuild a simple “English language” calculator that does the following: - Takes three inputs from the keyboard, two of them single digits (0 to 9) - Takes a char from the keyboard, representing one of the following five operations from the keyboard: + (addition), - (subtraction), * (multiplication), / (division), and ^ (exponentiation). - Outputs the description of the operation in plain English, as well as the numeric result The operations should be translated into English as follows: + plus / divided by - minus * multiplied by ^ to the power The switch…case statement might be helpful when translating the input values and operators into words. You need to consider three special situations: 1) one or two of the numbers is not a valid digit; output an error message. 2) the “operator” is not one of the allowed five operators; in that case output a message saying that the operator is not a valid one. 3)for division there is a special constraint ; you cannot divide by 0, and you should therefore test whether the second number is 0. If it is 0, you should output a message saying that division by zero is not allowed and end your program. • Show less1 answer - Anonymous asked1. Design a VB project to compute and display some statistics about a road trip the user... Show morePlease help 1. Design a VB project to compute and display some statistics about a road trip the user has taken during a long weekend. The user should enter the following information: • Distance in miles, • The gallons of gas used, • Price per gallon, • The number of minutes it took to drive to destination. When the user clicks on “Compute” Button, the program should compute and display the following information in one large Label, on three separate lines: • The mileage (miles per gallon), • The average speed on this trip (miles per hour), • Cost of gas. The program should have Buttons to clear the input and output boxes and to end the program execution. • Show less1 answer - Anonymous askedI've getting some output errors here and I'm unsure as to what I've done wrong. Instructor wont help... Show moreI've getting some output errors here and I'm unsure as to what I've done wrong. Instructor wont help me with it for some reason. Here are my files for the program. Any advice would be awesome! this is the class we are suppose to make according to the book //header file for the employeeinfo class //this class should be part of a binarytree //searched via the employee number #ifndef EMPLOYEEINFO_H #define EMPLOYEEINFO_H #include <iostream> #include <string> using namespace std; class EmployeeInfo { private: int idNum; string name; public: //constructor EmployeeInfo(int num, string str) { idNum = num; name = str; } //deconstructor ~EmployeeInfo(); //mutator void setID(int id) { idNum = id; } void setname(int nm) {name = nm; } //overload bool operator==(const EmployeeInfo& emp) { return this->idNum == emp.idNum; } bool operator<(const EmployeeInfo& emp) { return this->idNum < emp.idNum; } bool operator>(const EmployeeInfo& emp) { return this->idNum > emp.idNum; } void operator << (const EmployeeInfo& emp) { cout << idNum << endl; cout << name << endl; } }; #endif this is the altered template file. // Specification file for the TBinaryTree class //this class is a template that will accept any data type and make a tree out of it // changes have been made to IntBinaryTree to get this template. //all comments should hold true #include <iostream> using namespace std; #ifndef TBINARYTREE_H #define TBINARYTREE_H template<class T> class TBinaryTree { private: struct TreeNode { T value; // The value in the node TreeNode *left; // Pointer to left child node TreeNode *right; // Pointer to right child node }; TreeNode *root; // Pointer to the root node // Private member functions void insert(TreeNode *&, TreeNode *&); void destroySubTree(TreeNode *); void deleteNode(T, TreeNode *&); void makeDeletion(TreeNode *&); void displayInOrder(TreeNode *) const; void displayPreOrder(TreeNode *) const; void displayPostOrder(TreeNode *) const; int countNodes(TreeNode *&); public: // Constructor TBinaryTree() { root = NULL; } // Destructor ~TBinaryTree() { destroySubTree(root); } // Binary tree operations void insertNode(T); bool searchNode(T); void remove(T); int numNodes(); void displayInOrder() const { displayInOrder(root); } void displayPreOrder() const { displayPreOrder(root); } void displayPostOrder() const { displayPostOrder(root); } }; #endif //************************************************************* // insert accepts a TreeNode pointer and a pointer to a node. * // The function inserts the node into the tree pointed to by * // the TreeNode pointer. This function is called recursively. * //************************************************************* template<class T> void TBinaryTree<T>::insert(TreeNode *&nodePtr, TreeNode *&newNode) { if (nodePtr == NULL) nodePtr = newNode; // Insert the node. else if (newNode->value.idNum() < nodePtr->value) insert(nodePtr->left, newNode); // Search the left branch else insert(nodePtr->right, newNode); // Search the right branch } //********************************************************** // insertNode creates a new node to hold num as its value, * // and passes it to the insert function. * //********************************************************** template<class T> void TBinaryTree<T>::insertNode(T num) { TreeNode *newNode; // Pointer to a new node. // Create a new node and store num in it. newNode = new TreeNode; newNode->value = num; newNode->left = newNode->right = NULL; // Insert the node. insert(root, newNode); } //*************************************************** // destroySubTree is called by the destructor. It * // deletes all nodes in the tree. * //*************************************************** template<class T> void TBinaryTree<T>::destroySubTree(TreeNode *nodePtr) { if (nodePtr) { if (nodePtr->left) destroySubTree(nodePtr->left); if (nodePtr->right) destroySubTree(nodePtr->right); delete nodePtr; } } //*************************************************** // searchNode determines if a value is present in * // the tree. If so, the function returns true. * // Otherwise, it returns false. * //*************************************************** template<class T> bool TBinaryTree<T>::searchNode(T num) { TreeNode *nodePtr = root; while (nodePtr) { if (nodePtr->value == num) return true; else if (num < nodePtr->value) nodePtr = nodePtr->left; else nodePtr = nodePtr->right; } return false; } //********************************************** // remove calls deleteNode to delete the * // node whose value member is the same as num. * //********************************************** template<class T> void TBinaryTree<T>::remove(T num) { deleteNode(num, root); } //******************************************** // deleteNode deletes the node whose value * // member is the same as num. * //******************************************** template<class T> void TBinaryTree<T>::deleteNode(T num, TreeNode *&nodePtr) { if (num < nodePtr->value) deleteNode(num, nodePtr->left); else if (num > nodePtr->value) deleteNode(num, nodePtr->right); else makeDeletion(nodePtr); } //*********************************************************** // makeDeletion takes a reference to a pointer to the node * // that is to be deleted. The node is removed and the * // branches of the tree below the node are reattached. * //*********************************************************** template<class T> void TBinaryTree<T>::makeDeletion(TreeNode *&nodePtr) { // Define a temporary pointer to use in reattaching // the left subtree. TreeNode *tempNodePtr; if (nodePtr == NULL) cout << "Cannot delete empty node.\n"; else if (nodePtr->right == NULL) { tempNodePtr = nodePtr; nodePtr = nodePtr->left; // Reattach the left child delete tempNodePtr; } else if (nodePtr->left == NULL) { tempNodePtr = nodePtr; nodePtr = nodePtr->right; // Reattach the right child delete tempNodePtr; } // If the node has two children. else { // Move one node the right. tempNodePtr = nodePtr->right; // Go to the end left node. while (tempNodePtr->left) tempNodePtr = tempNodePtr->left; // Reattach the left subtree. tempNodePtr->left = nodePtr->left; tempNodePtr = nodePtr; // Reattach the right subtree. nodePtr = nodePtr->right; delete tempNodePtr; } } //**************************************************************** // The displayInOrder member function displays the values * // in the subtree pointed to by nodePtr, via inorder traversal. * //**************************************************************** template<class T> void TBinaryTree<T>::displayInOrder(TreeNode *nodePtr) const { if (nodePtr) { displayInOrder(nodePtr->left); cout << nodePtr->value << endl; displayInOrder(nodePtr->right); } } //**************************************************************** // The displayPreOrder member function displays the values * // in the subtree pointed to by nodePtr, via preorder traversal. * //**************************************************************** template<class T> void TBinaryTree<T>::displayPreOrder(TreeNode *nodePtr) const { if (nodePtr) { cout << nodePtr->value << endl; displayPreOrder(nodePtr->left); displayPreOrder(nodePtr->right); } } //**************************************************************** // The displayPostOrder member function displays the values * // in the subtree pointed to by nodePtr, via postorder traversal.* //**************************************************************** template<class T> void TBinaryTree<T>::displayPostOrder(TreeNode *nodePtr) const { if (nodePtr) { displayPostOrder(nodePtr->left); displayPostOrder(nodePtr->right); cout << nodePtr->value << endl; } } //this function is called by the user to get the number of nodes //the function calls another private function that is recursive //that does the counting template<class T> int TBinaryTree<T>::numNodes() { return countNodes(root); } //this recursive private function counts the nodes in the tree //it does this by taking one plus the nodes to the right and the left //the one is there to include the root node template<class T> int TBinaryTree<T>::countNodes(TreeNode *&nodePtr) { if (nodePtr == NULL) { return 0; //base case } else //this keeps looping through the tree until all nodes are counted { return 1+ countNodes(nodePtr->left) + countNodes(nodePtr->right); //recursive case } } this is the main function file. suppose to show that it works //this is a driver program that should show that the //employeeTree class is held in the nodes of TBinaryTree #include <iostream> #include <string> #include "EmployeeInfo.h" #include "TBinaryTree.h" using namespace std; int main() { EmployeeInfo one(1021, "John Williams"); TBinaryTree<EmployeeInfo> ids; ids.insertNode(one); ids.displayInOrder(); return 0; } • Show less0 answers - Anonymous asked“Guess Who” is a game played by two opponents, each having a set of pictures representing faces ... More »0 answers - Anonymous askedIn order to prepare a criminal case, the police has to analyze the fingerprints found in a given roo... More »0 answers - Anonymous askedReturn the number of times two consecutive characters occur in the... Show morepublic int charPairs(String str){ Return the number of times two consecutive characters occur in the given string. charPairs("") returns 0 charPairs("H") returns 0 charPairs("abc") returns 0 charPairs("aabbcc") returns 3 charPairs("mmmm") returns 3 charPairs("mmOmm") returns 2 LoopFun loops = LoopFun(); assertEquals(2, loops.charPairs("MMM")); assertEquals(0, loops.charPairs("MmM")); • Show less2 answers - Anonymous askedCourse (course_id [primary ke... Show moreGiven the Schema: Department (dept_name [primary key], building, budget) Course (course_id [primary key], title, dept_name, credits) Instructor (ID [primary key], name, dept_name, salary) Foreign Key is dept_name references Department Section (course_id [primary key], sec_id [primary key], semester [primary key], year [primary key], building, room_number, time_slot_id) Foreign Key course_id references Course Teaches ( ID [primary key], course_id [primary key], sec_id [primary key], semester [primary key], year [primary key]) Foreign key ID references Instructor. Foreign Key (course_id,sec_id,semester,year) references Section Write the following in SQL: a. Find the names of all students who have taken at least one CS course; make sure there are no duplicate names in the result. b. Find the IDs and names of all students who have not taken any course offering before Spring 2009. c. For each department, find the maximum salary of instructors in that department You may assume that every department has at least one instructor. d. Find the lowest, across all department,s of the per-department maximum salary computed by the preceding query. e. Create a new course "CS-001", titled "Weekly Seminar", with 0 credits. f. Create a section of this course in Autumn 2009, with sec_id of 1 g. Enroll every student in the CS department in the above section. h. Delete enrollments in the above section where the student's name is chavez. i. Delete the course CS-001. What will happen if you run this delete statement w/o first deleting offerings(sections) of this course. j. Delete all takes tuples corresponding to any section of any course with the word 'database" as a part of the title; ignore case when matching the word with the title. • Show less1 answer - Anonymous asked// then divide by 5 to get the ave... Show more// I am trying to figure out how to sum up each 5 rows of numbers // then divide by 5 to get the average, then get the average for the next // 5 numbers in the other row!! am I doing something wrong or something, // cause I come up with the wrong answers #include <iostream> #include <cmath> #include <iomanip> #include <fstream> using namespace std; int main() { double sum; double number; int count; ifstream indata; indata.open("numbers.txt"); indata >> number; while (indata) { sum = 0; count = 1; while(count <= 5) { sum = sum + number; count++; indata >> number; } cout << sum/count << endl; indata >> number; } indata.close(); system("PAUSE"); return 0; } • Show less3 answers - SilverGoose5740 askedI need help with getting the filereader to do the needed choosing operation while it is reading each... Show more I need help with getting the filereader to do the needed choosing operation while it is reading each line and chooses between C,H,S and then reads the next lines according to that one. I also need help with getting to bubblesort to do strings and not just integers. I'm sure that I'll need help with other stuff as I continue working on it, but this is it for now. Any help appreciated. If you need the other classes as well just let me know, and I will post them.• Show less What the Main program needs to do 1. You will begin by declaring an array of type employee. This will contain the information read from the main data file for each employee. 2. You will open the employee file, and read each line, since there are 3 different kinds of employees, there are 3 different line formats one for each category of employee, these are: C 1234 Sam Jones Salesman 45000.00 10.00 7000.00 S 2312 Larry Smith Manager 54000.00 H 3212 Sally Smith Decorator 6.50 Y Data lines containing Commission based employees begin with a C, Salaried an S , and Hourly an H. • Declare local variables for each possible data field, emp_type, empID, firstName, lastName, title, commissionRate, threshold, salary, hourly rate & overtimeEligible. • Open a scanner to the data file (maybe called input) • “While the data file has more data to read” i. Read the employee type empType =( input.next()).charAt(0); reads a single character from a string..(remember next() stops at the first blank space.) Then based on the letter read, extract the remaining information from the line. For example if empType=’S’ empID = input.nextInt(); firstName = input.next(); lastName = input.next(); title = input.next(); hourlyRate = input.nextFloat(); input.nextLine(); 3. Once all of the employees’ data has been read, and inserted into the array, you will need to sort the array. You may use any sorting algorithm you wish, including the bubble sort. 4. Open the data file for hourly employees, and create a scanner to that file. Each line has the following format EmployeeID HoursWorked IE: 3212 92.50 • Read each line of the file. • Based on employee ID that is the first data item, write a method that performs a RECURSIVE binary search algorithm to find the correct employee, and returns the index # of the array element that contains the information for that employee. • then use the setter to store the hours worked into the object found by the binary search. 5. Open the data file for commissionBased employees, and create a scanner to that file. Each line has the following format EmployeeID Sales IE: 1234 11765,00 • Read each line of the file. • Use the binary search method to “find” the correct employee • then use the setter to store the commission sales into the object, then print column headings for salaried employees 1. For each employee call the print() method to print out the object contents. 2. add this employees total Pay to the total pay for all employees of this type MAIN import java.util.*; import java.io.*; public class Employee_test { public static void main(String[]agrs) throws IOException { Employee[] emp = new Employee[]; public char type; public int ID; public String firstName; public String lastName; public String title; public Float commissionRate; public Float threshold; public Float salary; public Float hourlyRate; public Boolean overtimeEligible; while { FileReader input = new FileReader("Employee.dat"); } type = input.next().charAt(0); if (type=='S') { ID = input.nextInt(); firstName = input.next(); lastName = input.next(); title = input.next(); salary = input.nextFloat(); input.nextLine(); else if(type =='H') ID = input.nextInt(); firstName = input.next(); lastName = input.next(); title = input.next(); hourlyRate = input.nextFloat(); overtimeEligible = input.nextBoolean(); input.nextLine(); else (type == 'C') ID = input.nextInt(); firstName = input.next(); lastName = input.next(); title = input.next(); salary = input.nextInt(); commissionRate = input.nextFloat(); threshold = input.nextFloat(); input.nextLine(); } } } public static void bubbleSort(int[] list) { boolean swapped; do { swapped = false; for(int i=1; i < list.length; i++) { if(list[i-1]>list[i]) { int temp =list[i]; list[i] = list[i-1]; list[i-1] = temp; swapped = true; } } }while (swapped); }1 answer - vtstudent askedWrite a while loop code that will input a text document and output another text document using if -... Show moreWrite a while loop code that will input a text document and output another text document using if - else statment text input: remainder 19 9 divide 14 12 multiply 19 9 subtract 13 5 subtract 9 5 divide 5 14 multiply 9 8 divide 11 6 subtract 16 7 subtract 11 12 add 15 6 subtract 16 13 subtract 15 14 divide 17 11 divide 12 12 subtract 17 11 divide 18 6 add 13 13 subtract 9 13 remainder 14 13 multiply 12 7 add 13 10 add 10 6 add 16 5 remainder 17 13 and text output #1 Operation #2 Answer 19 % 9 1 14 / 12 1 19 * 9 171 13 - 5 8 9 - 5 4 5 / 14 0 9 * 8 72 11 / 6 1 16 - 7 9 11 - 12 -1 15 + 6 21 16 - 13 3 15 - 14 1 17 / 11 1 12 / 12 1 17 - 11 6 18 / 6 3 13 + 13 26 9 - 13 -4 14 % 13 1 12 * 7 84 13 + 10 23 10 + 6 16 16 + 5 21 17 % 13 4 • Show less1 answer - Anonymous56123 askedYour heater control... Show moreDevelop the pseudo-code that you could use for a heater that does the following: Your heater controller will always monitor the room temperature of your apartment. It will also monitor a control switch called ON/OFF and either DO NOTHING (when OFF) or HEAT (when ON). When the heater is turned ON, it will compare the room temperature to the heater desired temperature setting. If the room temperature is at least 2° lower than the desired temperature, the heater will TURN ON. It will stay ON until the room temperature is at least 2° higher than the desired temperature and then TURN OFF again. • Show less1 answer - Anonymous askedShow how to define a view tot_credits (year, num_credits), giving the total number of credits taken ... More »1 answer - Anonymous asked1 answer - Anonymous askedWrite the RAPTOR Flowchart, and Python code for the fo... Show more Need to figure out the code for this any help?• Show less Write the RAPTOR Flowchart, and Python code for the following programming problem. Change for a Dollar Game Design a change-counting game that gets the user to enter the number of coins required to make exactly one dollar. The program should ask the user to or less than one dollar. Use at least three modules in developing the logic…one can be the main().0 answers - Anonymous askedBelow is a description of what my code should be doing and also my attempt at the code. I would real... Show moreBelow is a description of what my code should be doing and also my attempt at the code. I would really appreciate any help with this code. Thanks. In the skeleton ?le attached (also available on SmartSite as lab5.skel) you will ?nd an array of structures(or records) stored in the memory corresponding to the C declarationstruct student {char *name;int id;intfinal }Class[20];Each record has three ?elds - The ?rst ?eld is the name of a student 8 characters long (includingthe null character at the end) second ?eld is the student id (6 decimal digit integer) and third ?eldthe score in the ?nal exam (positive integer less than 100).Your task is to write a MAL (MIPS Assembly Language) program to sort the students in theclass according to the input received from the user. The user should be prompted for two inputs -what ?eld to sort by and whether it is ascending or descending order. The user can input a singlecharacter, N for sort by name, I for sort by ID and F for sort by ?nal exam score and similarly A forascending and D for descending order.The output of your program should be the sorted array printed one record per line - with Name,ID, and Final, separated by a space.You cannot use SAL instructions in this laboratory exercise. You have to use MAL. .data Class: .asciiz "Bill " .word 934039 .word 87 .asciiz "Art " .word 188399 .word 45 .asciiz "Peter " .word 184909 .word 67 .asciiz "Miller " .word 594939 .word 55 .asciiz "Wells " .word 849309 .word 51 .asciiz "Rahim " .word 859310 .word 90 .asciiz "Thomas " .word 345698 .word 67 .asciiz "Garcia " .word 634899 .word 49 .asciiz "William" .word 599490 .word 77 .asciiz "Janice " .word 353849 .word 55 .asciiz "Emma " .word 239492 .word 82 .asciiz "Susie " .word 239420 .word 69 .asciiz "Katie " .word 123424 .word 59 .asciiz "Gizelle" .word 174351 .word 59 .asciiz "Michele" .word 112341 .word 66 .asciiz "Powell " .word 113949 .word 87 .asciiz "Marie " .word 107897 .word 80 .asciiz "Hannah " .word 793714 .word 71 .asciiz "Kristen" .word 638938 .word 60 .asciiz "Jones " .word 439939 .word 50 NumOfStudents: .word 20 eol: .asciiz " \n" cat: .word # category to sort by prompt1: .asciiz "Enter the field to sort by - N for Name, I for Student ID and F for Final Exam Score: " prompt2: .asciiz "Enter the sort order - A for Ascending or D for Descending: " # Your data declarations here .text __start: la $a0, prompt1 #puts the string prompt1! li $v0, 12 syscall la $a0, cat #reads the resultant string from prompt1 li $v0, 12 syscall la $a0, eol #puts an eol! li $v0, 4 syscall li $v0, 4 la $a0, Class #reads the struct of people in the #class! move $t0, $a0 #stores $a0 into $t0 because we will #be modifying $a0 later! loop: li $8,1 #flag = true li $9, 0 #9 is our offset #for: add $v0, $t0, $9 # lw $11, ($v0) #load element # lw $12, 4($v0) #load next element <3 # sub $13, $11, $12 # blez $13, noswap # # li $8, 0 # sw $11 4($10) # sw $12, ($10) #noswap: add $9, $9, 196 #see if the end of the array has been #reached? bltz $13,for beq $8, $0, loop #loop until done. done • Show less0 answers - StripedFlame1626 askedCreate a menu-driven program that will accept a list of non-negative integers from the keyboard, cal... Show moreCreate a menu-driven program that will accept a list of non-negative integers from the keyboard, calculate the mean and median values and display those values on the screen. Your menu should have 4 options: 1. Add a number to the array (list) 2. Display the mean 3. Display the median 4. Quit • Show less1 answer - Anonymous askedsuppose we have a video monitor with a display area that measures 12 inches across and 9.6 inches hi... More »2 answers - Anonymous asked1 answer - BubbaGump6969 askedWrite a method in RandomTester class called throwDice that returns a random number between 1 and 6 .... More »2 answers - Anonymous asked1 answer - DiligentDragon7282 asked1 answer - Anonymous asked7.20 (Total Sales) Use a two-dimensional array to solve the following problem: A company has four sa1 answer - DiligentDragon7282 asked1 answer - Anonymous asked4 1... Show moreConsider the following segment table: Segment Base Length 0 219 600 1 2300 14 2 90 100 3 1327 580 4 1952 96 what are the physical addresses for the following logical addresses? a. 0,430 b. 1,10 c. 2,500 d. 3,400 e. 4,112 • Show less1 answer - InvincibleRiver4804 askedAssume that all nodes... Show more • Show less Consider the network of Figure 1, where routers use RIP as routing protocol. Assume that all nodes are turned on at the same time, and that only neighbor nodes are learned at booting time. (a) Show the routing tables at node C after the first and the second update. (b) Show the final routing table for all nodes. (c) After how many minutes will the network converge? (d) To achieve convergence, does RIP need a centralized authority? Why/why not?1 answer - Anonymous asked% - (cell) cell array of verb... Show more% Function Name: realMadLib % Inputs (4): - (cell) cell array of nouns % - (cell) cell array of verbs % - (cell) cell array of adjectives % - (char) unedited MadLib sentence % Outputs (1): - (char) completed MadLib sentence % % Background Information: % MadLib is a word game where one player prompts another for a list of % words to substitute for blanks in a story; these word substitutions % have a humorous effect when the resulting story is then read aloud. % % Function Description: % This function takes in three cell arrays which contain the nouns, % verbs, and adjectives that will be used. The unedited MadLib sentence % will contain specific strings, '%n'(noun),'%v'(verb), '%a'(adjective) % which indicate what type of word must be replaced in that spot. After % that word (noun, verb, or adjective) has been used, it can not be used % again and the function must use the next available word in its % corresponding list of nouns, verbs, or adjectives. The function should % then output the completed MadLib sentence after it has completed all of % its word replacements. % % The identifiers %n, %v, and %a will always appear as an individual % word, like so: % % 'Today I went to the %n and bought a %n.' % % Notes: % - Not all nouns, verbs, and adjectives in their respective cell arrays % will be used. However, there will always be enough nouns, verbs, and % adjectives to use with the input string. % - Though nouns, verbs, and adjectives are guaranteed to appear as % individual words, they are not guaranteed to be separated exclusively % by spaces. For example, a punctuation may follow the %n, %v, or %a % symbol. However, you may assume that punctuation or any other % character will ever precede the prompt for the noun, verb, or % adjective (e.g. ' "%n ' will not occur, but '%n,' is a possibility) % % Hint: % - You may find strtok() useful. When a token is obtained, check that % the first character is a '%' character before selecting the % appropriate word for replacement. % % Test Cases: % ca1 = {'dog','cats','horse','chicken'}; % ca2 = {'ate', 'spoke', 'drank', 'slapped'}; % ca3 = {'pretty', 'lazy', 'strong'}; % sentence = ['Once upon a time, there was a %n who %v %a %n. ',... % 'His best friend was a %a %n who %v Chinese.']; % % out1 = realMadLib(ca1, ca2, ca3, sentence); % out1 => ['Once upon a time, there was a dog who ate pretty ',... % 'cats. His best friend was a lazy horse who spoke Chinese.'] % % ca1 = {'chris brown','rihanna','bieber'}; % ca2 = {'punched', 'kicked', 'drank', 'slapped'}; % ca3 = {'pretty', 'lazy', 'high-pitched'}; % sentence = ['Long time ago, there was %n who %v %a %n. ',... % 'He then went to jail where he got %v by %a and %a %n.']; % % out2 = realMadLib(ca1, ca2, ca3, sentence) % out2 => ['Long time ago, there was chris brown who punched ',... % 'pretty rihanna. He then went to jail where he got ',... % 'kicked by lazy and high-pitched bieber.'] • Show less0 answers - Anonymous asked% O... Show more% Function Name: findTemp % Inputs (2): - (cell) temperature data % - (cell) dates to search for % Outputs (1): - (cell) temperatures at the dates requested % % Function Description: % Write a function "findTemp" that takes in two cell arrays. In each cell % of the first cell array, there is a 1x2 vector of type double. The % first number in the vector is the ordinal day of the year (where Jan % 1=1 and Dec 31=365 for the 1st and 365th day of the year, respectively) % and the second number is the temperature of that particular day. % % In each cell of the second cell array, there is a string of the month % and day of the month, separated by a space. The day will always occupy % the last 2 positions of the string (where 4th day of the month = 04) % % Your function should then output a cell array that is the same length % as the second input cell array. In each cell of the output cell array, % insert a string that has the following format: % % 'On <month and date>, the temperature was <temperature found> degrees' % % If there is no data for the date requested, the output in that cell % should simply output a logical false (not 0). % % Note: % - It may be useful to create a vector of the number of days that make % up each month from January to December. From there, you can convert % to the ordinal day of the year, given prior knowledge of the month % and day. % % Test Cases: % data = {[365 3] [82 26] [1 30]}; % dates = {'March 23' 'January 01' 'December 31'}; % t1= findTemp(data,dates); % t1 => {'On March 23, the temperature was 26 degrees',... % 'On January 01, the temperature was 30 degrees',... % 'On December 31, the temperature was 3 degrees'} % % data2 = {[3 11] [121 20] [35 14]}; % dates2 = {'February 04' 'May 01' 'January 13'}; % t2= findTemp(data2,dates2); % t2 => {'On February 04, the temperature was 14 degrees',... % 'On May 01, the temperature was 20 degrees', [false]} • Show less0 answers - Anonymous askedsemaphores 's1' and 's2'. I... Show more a) Consider four concurrent processes A, B, C, and D, synchronized by two• Show less semaphores 's1' and 's2'. Initially, s1 = 1 and s2 = 0. process A = process B = process C = process D = wait ( s1 ) wait ( s1 ) wait ( s2 ) wait ( s1 ) print 'a' print 'b' print 'c' print 'd' signal( s1 ) signal( s2 ) signal( s1 ) signal( s1 ) i) Suppose 'a' is printed first. List the characters that can be printed as the last character of the string. Justify your answer. ii) Suppose 'b' is printed first. List the characters that can be printed as the last character of the string. Justify your answer. b) Consider a different example. Initially, atom = 1 and goB = 0. process A = process B = 'do' j := 1 to m ---> 'do' j := 1 to n ---> wait (atom) wait (atom) ... ... signal (goB) wait (goB) ... ... signal (atom) signal (atom) 'od' 'od' i) Let m > n. In this case, does there exist an execution scenario in which both processes block permanently? Does there exist an execution scenario in which neither process blocks permanently? Justify your answers. ii) Let m < n. In this case, does there exist an execution scenario in which both processes block permanently? Does there exist an execution scenario in which neither process blocks permanently? Justify your answers.0 answers - act4ucf askedi... Show moreI have always believed that in C you have to declare a variable at the beginning of a method, e.g. int i; ... for(i=0;... This is unlike, for example, java where you can declare a variable as needed, e.g. for(int i = 0;... A friend of mine however sent me c source code and declared variables as needed (i.e. the java example), and claimed that using devc++ it compiled and ran. Using visual studio 2010, I received tons of errors and it would not compile. Has c updated something and my computer is out of date or is this person "delusional" or something? Please let me know if you can indeed currently declare variables the same way you can in Java, and if so, why is Visual Studio 2010 giving compile time errors. • Show less1 answer - Anonymous askedA, co... Show more #include<iostream> #include<vector> using namespace std; vector<int> combine(const vector<int>& A, const vector<int>& B); int main() { vector<double> L1; vector<double> L2; vector<double> L3; int number; int number2; cout << "Number of students in this group: "; cin >> number; L1.resize (number); // asks user to enter 3 numbers and put them in vector L1 for (int i = 0; i < number; i++) { cout << "Enter numbers in increasing order #" << i+1 << ": "; cin >> L1[i]; } cout <<"Enter number of elements: "; cin >> number2; L2.resize (number2); // asks user to enter 3 numbers and put them in vector l2 for (int i = 0; i < number2; i++) { cout <<"Enter 3 more elements in increasing order#" << i+1 << ":"; cin >> L2[i]; } // im suppose to call the function below so it will sort L1 and L2 // How can i call the function below and also how do i show the result // of the combining vecots return 0; } vector<int> combine(const vector<int>& A, const vector<int>& B) { // Fill the resultant vector with sorted results from both vectors vector<int> R; unsigned L1 = 0, L2 = 0; while(L1 < A.size() && L2 < B.size()) { // If the left value is smaller than the right it goes next // into the resultant vector if(A[L1] < B[L2]) { R.push_back(A[L1]); L1++; } else { R.push_back(B[L2]); L2++; } } // Push the remaining data from both vectors onto the resultant while(L1 < A.size()) { R.push_back(A[L1]); L1++; } while(L2 < B.size()) { R.push_back(B[L2]); L2++; } } • Show less1 answer - TheProphecy askedCreate the program so that it implements a guessing game. The game works as follows: First, a (secre... Show more Create the program so that it implements a guessing game. The game works as follows: First, a (secret) random number in between 1 and 100, inclusive, is generated. Next, the user is prompted to enter a guess as to find the number is. If the guess is too high, an appropriate message asking for a lower guess should be printed. If the guess is too low, a corresponding message asking for a higher guess should be printed. In both of these cases, the user should enter another number. The game continues in this fashion until the user guesses the correct number. At this point in time, the game ends, and the program prints out a message stating the number of guesses it took the user to find the number
http://www.chegg.com/homework-help/questions-and-answers/computer-science-archive-2011-february-24
CC-MAIN-2014-10
refinedweb
9,019
63.9
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). Hello all, I tried everything to figure out how to use the newly added Python-Command "LayerShader.AddLayer()" in S24. As far as I know it only adds the "Type" of Layer. For Example I want to add a certain shader to the Layer I first use AddLayer(c4d.TypeShader) and this will give me an empty "Shader". But how can I define this shader to a specific Shader then? () I tried everything but I dont get it... does someone know how to do it? Thx in advance! NOTE ( @ferdinand ) : The here provided code example contains an error, please refer to How to Create and Populate a Layer Shader? instead. NOTE ( @ferdinand ) : The here provided code example contains an error, please refer to How to Create and Populate a Layer Shader? instead. Hi @PdZ-1 welcome in plugincafe. The type need to be one of the LayerType. So to have a regular BaseShader you first need to create a TypeShader layer and then set the link. Find a code snippet TypeShader import c4d # Main function def main(): # Retrieveh teh Layer Shader mat = doc.GetFirstMaterial() sha_xlayer = mat.GetFirstShader() # Create an HSL layer hsl = sha_xlayer.AddLayer(c4d.TypeHSL) # Create a Shader Layer shader_layer = sha_xlayer.AddLayer(c4d.TypeShader) # Create a Gradient Shader gradient_shader = c4d.BaseShader(c4d.Xgradient) # Insert this gradient to the material (so the material become the owner of this shader too) mat.InsertShader(gradient_shader, sha_xlayer) # Finally set the Shader Layer link to the Gradient Shader shader_layer.SetParameter(c4d.LAYER_S_PARAM_SHADER_LINK, gradient_shader) c4d.EventAdd() # Execute main() if __name__=='__main__': main() Cheers, Maxime. Hello @PdZ-1, without further questions or replies, we will consider this topic as solved by Monday, the 30th and flag it accordingly. Thank you for your understanding, Ferdinand Hi... I'm trying to figure out how to handle nested LayerShaders mat.InsertShader(gradient_shader, sha_xlayer) inserts gradient_shader as a child of sha_xlayer ? Would sha_xlayer.InsertShader(gradient_shader) do exactly the same thing ? If yes, does mat.InsertShader(sha_xlayer) have to be done first as well, or can you set up a shader tree first and then add it to the material? best, index
https://plugincafe.maxon.net/topic/13469/python-layershader-addlayer-defining-shader/4
CC-MAIN-2022-27
refinedweb
394
51.95
This is your resource to discuss support topics with your peers, and learn from each other. 01-09-2013 07:27 AM I was writing my app without it, but some samples and examples use it. Since I'm not a C/QML Developer, I have no idea if this is something from one of them, or it's something from Cascade, anyone have a logical explanation for this? What it really does? Is there any use for this code-piece? Example from: using namespace bb::cascades; TestApp::TestApp(bb::cascades::Application *app) : QObject(app) { QmlDocument *qml = QmlDocument::create("asset:///main.qml").parent(th is); qml->setContextProperty("injection", this); AbstractPane *root = qml->createRootObject<AbstractPane>(); app->setScene(root); }is); qml->setContextProperty("injection", this); AbstractPane *root = qml->createRootObject<AbstractPane>(); app->setScene(root); } Solved! Go to Solution. 01-09-2013 07:45 AM 01-09-2013 08:19 AM 01-09-2013 10:28 AM Thanks, I think I understood, I'll wait my head stop spinning so I can make sure of that. 01-09-2013 12:09 PM The reason you'll want to use this is because when Qt object trees are destroyed and cleaned-up, the parents destroy their children.This way, cleanup happens in a controlled manner. Earlier sample code tended to instantiate the application on the stack, which would cause it to be destroyed when it goes out of scope when main() exits. I think this can lead to some double-destruction happening if it is also attached to a parent object, so it is probably best these days to do something like shown here: note that I am allocating my class using new, but then not tracking it anywhere.. this is because the parent object is tracking it for me and will destroy it when the time comes. If you look back in the commit history, you'll see that I used to do it differently: the downside with this approach is that "app" and "mainApp" both go out of scope at the end of main(), and I have no control over the order that their destructors will be called. Things could get messy if I had set mainApp's parent object to "app" when destructors get called. Cheers, Sean 01-09-2013 12:28 PM 01-09-2013 12:43 PM - edited 01-09-2013 12:49 PM really? { Class1 a; Class2 b; } you're saying that C++ guarantees that b is destroyed before a when this block ends? It hadn't bothered to research this. (EDIT: yup, this is what C++ guarantees) Still dangerous, as simply re-arranging declaration could cause grief, especially if one of those classes is set to destroy the other instance. 01-09-2013 01:19 PM
https://supportforums.blackberry.com/t5/Native-Development/What-is-the-quot-QObject-app-quot-in-some-examples/m-p/2085377/highlight/true
CC-MAIN-2016-36
refinedweb
457
60.95
// Jericho HTML Parser - Java based library for analysing and manipulating HTML // Version 2.5 // // // This library is free software; you can redistribute it and/or // modify it under the terms of either one of the following licences: // // 1. The Eclipse Public License (EPL) version 1.0, // included in this distribution in the file licence-epl-1.0.html // or available at // // 2. The GNU Lesser General Public License (LGPL) version 2.1 or later, // included in this distribution in the file licence-lgpl-2.1.txt // or available at // // This library is distributed on an "AS IS" basis, // WITHOUT WARRANTY OF ANY KIND, either express or implied. // See the individual licence texts for more details. package au.id.jericho.lib.html; import java.io.*; /** * Represents a character stream source. The purpose of a class that implements this interface is to output text. * <p> * For small amounts of data, or when memory usage isn't a prime concern (e.g. in client-side applications), the simplest way to obtain the data is by calling * the {@link #toString()} method. * If the character stream might contain a large amount of data it is recommended to use the {@link #writeTo(Writer)} method to access the data, * especially if running in a multi-user server environment. * <p> * The advantage of providing textual data via this interface is that it gives the user the choice as to whether they would like to receive the data as a stream * of characters, or all as a single string. Furthermore, it allows the "active" stream source (see below) to be easily converted into a "passive" stream source * if required. * <p> * An <i><a name="Active">active stream source</a></i> is a stream source that actively outputs to a passive receiver ("sink"). * The {@link #writeTo(Writer)} method in this interface signifies an active source as the transmission of the entire data stream takes place when this method is executed. * In this case the sink is the object that supplies the <code>Writer</code> object, and would typically contain a <code>getWriter()</code> method. * The sink is passive because it just supplies a <code>Writer</code> object to be written to by the code in some other class. * <p> * A <i><a name="Passive">passive stream source</a></i> is a stream source that is read from by an active sink. * For character streams, a passive stream source simply supplies a <code>Reader</code> object. * The active sink would typically contain a <code>readFrom(Reader)</code> method which actively reads the entire data stream from the <code>Reader</code> object. * <p> * The {@link CharStreamSourceUtil#getReader(CharStreamSource)} method converts a <code>CharStreamSource</code> into a <code>Reader</code>, * allowing the data from the active <code>CharStreamSource</code> to be consumed by an active sink with a <code>readFrom(Reader)</code> method. * <p> * Every implementing class must override the {@link #toString()} method to return the output as a string. * <p> * An easy way to implement this is by calling the {@link CharStreamSourceUtil#toString(CharStreamSource) CharStreamSourceUtil.toString(this)} method, * which buffers the output from the {@link #writeTo(Writer)} method into a string. * * @see OutputDocument * @see SourceFormatter * @see Renderer * @see TextExtractor */ public interface CharStreamSource { /** * Writes the output to the specified <code>Writer</code>. * * @param writer the destination <code>java.io.Writer</code> for the output. * @throws IOException if an I/O exception occurs. */ void writeTo(Writer writer) throws IOException; /** * Returns the estimated maximum number of characters in the output, or <code>-1</code> if no estimate is available. * <p> * The returned value should be used as a guide for efficiency purposes only, for example to set an initial <code>StringBuffer</code> capacity. * There is no guarantee that the length of the output is indeed less than this value, * as classes implementing this method often use assumptions based on typical usage to calculate the estimate. * * @return the estimated maximum number of characters in the output, or <code>-1</code> if no estimate is available. */ long getEstimatedMaximumOutputLength(); /** * Returns the output as a string. * @return the output as a string. */ String toString(); }
http://www.java2s.com/Open-Source/Java/HTML-Parser/jericho-html/au/id/jericho/lib/html/CharStreamSource.java.htm
CC-MAIN-2013-20
refinedweb
675
55.44
So I am having some trouble with creating a variable that will hold a temporary string conversion. I am getting compiler errors telling me that no conversion is possible between a std::string iterator and a std:: basic string. This is my pertinent code thus far. #include <algorithm> #include <deque> #include <fstream> #include <iostream> #include <string> using namespace std; #include <cctype> class toLower {public: char operator()(char c) const {return tolower(c);}}; struct Email { string email; }; bool duplicateCheck(deque<Email>& email, Email anEmail) { bool duplicate; Email tempA; Email tempB; tempA.email = transform(anEmail.email.begin(), anEmail.email.end(), anEmail.email.begin(), toLower()); for (int i = 0; i < email.size(); i++) { tempB.email = transform(email[i].email.begin(), email[i].email.end(), email[i].email.begin(), toLower()); if (tempA.email == tempB.email) duplicate = true; else duplicate = false; } return duplicate; } This is for my final project in a C++ class and I am reading an input file, extracting valid emails, and then testing them to make sure there are no duplicates before being added to an output file. I can transform them PERMANENTLY, but that is going to get me docked points and I can't figure out what variable would hold the transformed text. I'm not an expert in c++ (yet!
http://www.dreamincode.net/forums/topic/232832-temporary-conversion-of-string-using-transform-function/
CC-MAIN-2016-22
refinedweb
211
53
Hello, in this short tutorial, I will demonstrate the process of controlling the Arduino Uno with the Arduino Esplora board. For this project you will need: - An Arduino Uno - An Arduino Esplora - 1 Jumper Cable Assuming you have all this, let's get started! Teacher Notes Teachers! Did you use this instructable in your classroom? Add a Teacher Note to share how you incorporated it into your lesson. Step 1: Code for Esplora In order for this to work, we need to send code to both the Uno, and the Esplora. Let's start with the Esplora code first. Copy and paste this to a blank sketch, make sure the Tool settings are appropriate, and upload the code to the Esplora. #include <Esplora.h> // Esplora Library int out = 14; // Output Pin void setup() { pinMode(out, OUTPUT); // set as output } void loop() { int button = Esplora.readButton(SWITCH_DOWN); // bottom button on esplora if (button == LOW) { // if button is pressed.... digitalWrite(out, HIGH); // send signal to pin } else { // if not.... digitalWrite(out, LOW); don't send signal to pin } } What this code does is send a signal to pin 14 on the Esplora, which will be connected to a pin on the Uno later. Step 2: Code for Uno Now, make a new sketch, and copy and paste the following code. Make sure to set Tools > Board > Uno before you upload, and make sure it's uploading to the correct port. int input = 3; // gives name to pin 3 void setup() { pinMode(in, INPUT); // sets pin 3 as input pinMode(13, OUTPUT); // sets pin 13 as output } void loop() { int signal = digitalRead(input); // reads input if (signal == HIGH) { // if there is a signal... digitalWrite(13, HIGH); // turn LED on } else { // if not... digitalWrite(13, LOW); // turn it off } } What this code does is check for a signal coming into Pin 3. If there is a signal, the internal LED connected to Pin 13 on the Uno will turn on. However, in order to get a signal, we will need to connect the Uno and Esplora together. Step 3: Connect the Two Now, for the easiest step of this whole project, connect Pin 3 on the Uno to pin 14 on the Esplora as shown in the photo above. If you did everything correctly, when you press the bottom button on the Esplora, the small LED on the Uno will turn on and off as you press the button! Now that you can blink an LED, think about how you can apply this to other, perhaps more useful things. Hope this helped! Feel free to comment any questions or suggestions below! Discussions
https://www.instructables.com/id/Communicating-Between-Arduino-Esplora-and-Uno/
CC-MAIN-2019-35
refinedweb
438
70.53
Alexander Strange <astrange at ithinksw.com> writes: > gcc 4.2+ provides __builtin_bswap32/64. Since it's usually a good idea My gcc 4.2.4 seems to be missing them. > figures for x86-64? > Any different numbers for other architectures? > > > Index: libavutil/bswap.h > =================================================================== > --- libavutil/bswap.h (revision 19639) > +++ libavutil/bswap.h (working copy) > @@ -30,7 +30,23 @@ > #include "config.h" > #include "common.h" > > -#if ARCH_ARM > +#if AV_GCC_VERSION_AT_LEAST(4,2) > + > +#define bswap_32 bswap_32 > +static av_always_inline av_const uint32_t bswap_32(uint32_t x) > +{ > + return __builtin_bswap32(x); > +} > + > +#if HAVE_FAST_64BIT > +#define bswap_64 bswap_64 > +static av_always_inline av_const uint64_t bswap_64(uint64_t x) > +{ > + return __builtin_bswap64(x); > +} > +#endif > + > +#elif ARCH_ARM > # include "arm/bswap.h" > #elif ARCH_BFIN > # include "bfin/bswap.h" > All else aside, this should go *after* per-arch stuff and be conditional on the macros being undefined. The arch-specific code needs to be able to override gcc's mess. The builtins are useless on ARM, where gcc generates calls to __bswapdi2 and __bswapsi2, and also fails to do anything clever with the 16-bit case (there is a REV16 instruction). Same thing on AVR32, Blackfin, MIPS, and SH4. On PPC32 it does reasonably, even for bswap64. On PPC64, it makes a total mess of bswap64, grabbing 112 bytes of stack and calling __bswapdi2. It should be noted that most of the bswap uses are in conjunction with reading or writing memory, and PPC has special byte-swapping load/store instructions which we use there. -- M?ns Rullg?rd mans at mansr.com
http://ffmpeg.org/pipermail/ffmpeg-devel/2009-August/061256.html
CC-MAIN-2014-42
refinedweb
245
69.28
#include <sys/stream.h> int putbq(queue_t *q, mblk_t *bp); Architecture independent level 1 (DDI/DKI). Pointer to the queue. Pointer to the message block. The putbq() function places a message at the beginning of the appropriate section of the message queue. There are always sections for high priority and ordinary messages. If other priority bands are used, each will have its own section of the queue, in priority band order, after high priority messages and before ordinary messages. putbq() can be used for ordinary, priority band, and high priority messages. However, unless precautions are taken, using putbq() with a high priority message is likely to lead to an infinite loop of putting the message back on the queue, being rescheduled, pulling it off, and putting it back on. This function is usually called when bcanput(9F) or canput(9F) determines that the message cannot be passed on to the next stream component. The flow control parameters are updated to reflect the change in the queue's status. If QNOENB is not set, the service routine is enabled. The putbq() function returns 1 upon success and 0 upon failure. Upon failure, the caller should call freemsg(9F) to free the pointer to the message block. The putbq() function can be called from user, interrupt, or kernel context. See the bufcall(9F) function page for an example of putbq(). bcanput(9F), bufcall(9F), canput(9F), getq(9F), putq(9F) Writing Device Drivers for Oracle Solaris 11.2 STREAMS Programming Guide
http://docs.oracle.com/cd/E36784_01/html/E36886/putbq-9f.html
CC-MAIN-2015-32
refinedweb
249
57.47
setup - setup devices and file systems, mount root file system #include <unistd.h> int setup(void);. setup() always returns -1 for a user process. EPERM Always, for a user process. Since Linux 2.1.121, no such function exists anymore. This function is Linux-specific, and should not be used in programs intended to be portable, or indeed in any programs at all. The calling sequence varied: at some times setup () has had a single argument void *BIOS and at other times a single argument int magic. This page is part of release 3.24 of the Linux man-pages project. A description of the project, and information about reporting bugs, can be found at.
http://huge-man-linux.net/man2/setup.html
CC-MAIN-2020-10
refinedweb
115
69.99
These are chat archives for marvell-iot/aws_starter_sdk wmprintf()only works from the main.cmodule, where I call wmstdio_init(UART0_ID, 0);I have imported #include <wmstdio.h>in my thread_2.cso wmprinf()at compilation doesn't throw error, but simply does nothing at runtime. Any ideas? wmprintf()to get some feedback. But eventually there will be too much output in the console. So I have noticed that there's file wmsdk/src/incl/sdk/wmlog.hwhich declares functtions like wmlog_w() wmlog_e() and wmlog()so that I can control the level of output. However when I try to use any of those functions in my main.c- they produce no output. I tried adding #define CONFIG_DEBUG_BUILDto the top of main.cand also running make APP=sample_apps/hello_world CONFIG_DEBUG_BUILD=1, but still no output. What should I do to enable it?
https://gitter.im/marvell-iot/aws_starter_sdk/archives/2016/03/06?at=56dc28ee817dfa1e41ecbf8b
CC-MAIN-2019-26
refinedweb
139
54.08
I think we have a problem in GTK. In the script below, if > you add a button or some other widget above the figure > canvas, only a part of the canvas is updated in the > motion_notify_event update. The distance from the top of > the figure canvas to the part that is not updated is equal > to the height of the widget packed above the canvas. You > can observe this by resizing the window to make it taller or > shorter and noting the vertical extent where the horizontal > line disappears. I think the answer is def draw(self): # synchronous window redraw (like GTK+ 1.2 used to do) # Note: this does not follow the usual way that GTK redraws, # which is asynchronous redraw using calls to gtk_widget_queue_draw(), # which triggers an expose-event # GTK+ 2.x style draw() #self._need_redraw = True #self.queue_draw() # synchronous draw (needed for animation) x, y, w, h = self.allocation #print x, y, w, h self._pixmap_prepare (w, h) self._render_figure(self._pixmap, w, h) self._need_redraw = False self.window.draw_drawable (self.style.fg_gc[self.state], self._pixmap, 0, 0, 0, 0, w, h) ^^^^^^^^^^
https://discourse.matplotlib.org/t/gtk-bug/3223
CC-MAIN-2019-51
refinedweb
186
67.86
7 segment display problem - Login or register to post comments - by _ZlaTanskY_ December 4, 2012. The program quite works, but I got a problem with segment c, e, f, and g from the right (unit)display, (connected to respectively RC4, RC2, RC1 and RC0). The problem is that sometimes (not always) that segment just flickers once, and then goes off. If I test the displays seperately (so the left one counts from 0 to 5 quite slow, and the right one from 0 to 9 10 times faster), then it works. but put together, those few segments seem to fail sometimes, and not always on the same numbers. Most of the time it's on 02, 03, 04, 13, and some more further on. Does anyone have a clue what the problem is? Thanks in advance, _ZlaTanskY_ It is probably a software error It would be best to post your code, maybe we can see what's wrong with it. Code + it works somehow! O_o Oke this is weird. I've changed my code (the pin connections) a little bit, to make the wiring and the coding easier, I used whole port A (from RA5 to RA0) and 1 pin of portB for display 2 (the tens) and whole port C (RA6 to RA0) for display 1 (the units). It worked better, only 1 segment wasn't working -> the d-segment of display 2 (tens) which was connected to RA3, the input button on the pickit2. I have no idea why this was, because I declared it to be an output. But I changed that connection from RA3 to one of port B, and now it seems to work... I don't understand, why can't I use RA3 as an input? Btw here's the code: #define _LEGACY_HEADERS #include <htc.h> #include <math.h> /* c7Segment.c - Roll through 60 Digits on 2x7 Segment LED Display This program will display each of the 60 digits on 2x 7 Segment Common Cathode LED Display. Hardware Notes: SSD1: RC6 - Segment a RC5 - Segment b RC4 - Segment c RC3 - Segment d RC2 - Segment e RC1 - Segment f RC0 - Segment g SSD2: RB6 - Segment a RA5 - Segment b RA4 - Segment c RB4 - Segment d RA2 - Segment e RA1 - Segment f RA0 - Segment g */ __CONFIG(INTIO & WDTDIS & PWRTEN & MCLRDIS & UNPROTECT \ & UNPROTECT & BORDIS & IESODIS & FCMDIS); int a,b,c,i, j; const char LEDDigit[10] = { // RRRRRRR - PIC16F690 Pin // ACCCCCC // 5543210 // abcdefg - LED Segment 0b1111110, // Digit Zero 0b0110000, // Digit One 0b1101101, // Digit Two 0b1111001, // Digit Three 0b0110011, // Digit Four 0b1011011, // Digit Five 0b1011111, // Digit Six 0b1110000, // Digit Seven 0b1111111, // Digit Eight 0b1111011}; // Digit Nine main() { PORTA = 0; PORTB = 0; PORTC = 0; // CMCON0 = 7; // Turn off Comparators ANSEL = 0; // Turn off ADC TRISA = 0; // All Bits of PORTA are Outputs TRISB = 0; // All Bits of PORTB are Outputs TRISC = 0; // All Bits of PORTC are Outputs c = 0; // Start at Digit 0 while(1 == 1) // Loop Forever { for (i = 0; i < 255; i++) // Simple Delay Loop for (j = 0; j < 199; j++); a = (int)floor(c/10); // Split the digit into 2 numbers, left and right display b = c%10; PORTC = LEDDigit[b] & 0x07F; // Pass Data Bits to LED Bits RB6 = LEDDigit[a] >> 6; RB4 = LEDDigit[a] << 3 >> 6; PORTA = LEDDigit[a] & 0x037; c = (c + 1) % 60; } } Good to see you got it Good to see you got it working. The reason RA3 did not work is because it is also MCLR which can only be an input. Oh I see, just checked the Oh I see, just checked the datasheets, didn't know what mclr was so, oke, now I know, thanks ^^ Now on to 4 displays and let's make a clock! Resistors Are you using any kind of current limiting resistors between your 7 segment and your uC? When you were asking about your protoboard earlier, I had mentioned the resistors --did you install them? Yes Yes, I'm using 7 resistors of each 470 Ohm for each display. Are you powering the LEDs through transistors, or, are you driving them right off the pins? Microcontrollers can only supply so much current per pin and they have a limit on how much they can supply over the whole package. Aye that is what I was thinking Birdmun PIC16F690 can handle 200 mA on PORTA,B,C combined. How much current are you running through those 7 segs Zla? If you limit each segment to 5mA thats 14 x 5 = 70mA well within limit. 1 k resistors on each segment will limit you to 5mA. I'm not using transistors, I'm not using transistors, connected directly to the pins of the microcontroller. Also, I'm not sure about the current trough the display segments, because I don't own a multimeter and I have no clue about the resistance of the display, so I can't calculate it either. But I'm using 470 Ohm resistors, perhaps i'll try 1k resistors tomorrow, but I doubt that will be the problem, because the displays are working with all but 2 segments out, and the 'problem' of one or two defecting is for example in the number 13, which only uses 7 segments out of 14, while 08 uses 13 out of 14 segments, and thats working fine. Also I had some trouble regarding pins RB5 and RB6, they weren't working at all. At first I thought it was a soldering problem, but then I touched the pin of the controller instead, with the male connecting cable, and I got no signal whatsoever. But thats 'fixed' by using other ports.
http://letsmakerobots.com/node/35308
CC-MAIN-2014-52
refinedweb
935
71.58
12 February 2008 15:56 [Source: ICIS news] LONDON (ICIS news)--Kuwait Petroleum Corp (KPC) will shut down its base oils plant at Rotterdam in the Netherlands for a one-month turnaround this week, a company source said on Tuesday. “We are slowly shutting down various units, and base oils production is due to stop in the next couple of days,” the source said. The four-week stoppage is one of several scheduled turnarounds planned in northwest ?xml:namespace> Several market participants reported tightness in the SN (solvent neutral) 150 and brightstock markets. Spot cargoes for these products were difficult to source in NWE, although customers said their contracted volumes were all covered. Kuwait Petroleum’s plant has a nameplate capacity of 235
http://www.icis.com/Articles/2008/02/12/9100219/kpc-prepares-rotterdam-base-oils-plant-shutdown.html
CC-MAIN-2015-06
refinedweb
123
60.14
How to Create and Use Shared Data and Shared Scripts This section discusses how to split tests into multiple files and how to share, access and use, shared scripts and shared data files. (It is also possible to share an Object Map; see Creating an Object Map for details.) Sharing scripts is ideal when you have functionality that is common to more than one test case. However, if you generally create test scripts from scratch and they all tend to have the same basic structure you might find it convenient to create test script templates to save having to copy and paste whenever you create a new test: see Testcase Templates for how to do this. How to Store and Locate Shared Scripts and Shared Data Files Each test case contains a default test script file called test.js (JavaScript) or test.py (Python) or test.pl (Perl) or test.rb (Ruby) or test.tcl (Tcl), depending on which scripting language has been set for the test suite. When creating test suites it often happens that many of the test cases require some common functionality or common data. Squish makes it possible to create separate script files that contain the common functionality and which can be used by all the test cases that need it. And Squish also makes it possible to create or import test data that can be shared by any of a test suite's test cases. For test data, Squish provides two options: test data that is specific to a test case, and test data that can be shared by any of a test suite's test cases. For test scripts, Squish provides three options: test scripts that are specific to a test case (in addition to the test.* file), test scripts that can be shared by any of a test suite's test cases, and—from global test scripts that can be shared by any test case in any test suite. (Global scripts are an advanced feature and not recommended for new Squish users.) Let's assume for ease of explanation that we have a test suite in a folder called myapp_suite. Let us further assume that we have two test cases for this suite in the folders myapp_suite/tst_case1 and myapp_suite/tst_case2. If we are using the Python scripting language, the first test case's filename will be myapp_suite/tst_case1/test.py, and it is easy to see what the name would be for the other scripting languages. Given the above assumptions, if we want to store some test case-specific data for the first test case it must be stored in the myapp_suite/tst_case1/testdata folder, for example, myapp_suite/tst_case1/testdata/case1_data.csv. And if we wanted to store some test data that could be shared by both test cases (and by any others we create later), it must be stored in the myapp_suite/shared/testdata folder. These details are important for command line users, but if you use the Squish IDE, there's no need to remember them since the Squish IDE can be used to create or import test data and will store it in the right place, and only filenames (not paths) are used to access test data in test scripts. Regardless of whether test data is test case-specific or shared by the whole test suite, we always use the same technique to access the data: we call the Dataset testData.dataset(filename) function with the test data's filename (without any path) to get a reference to an array or tuple (depending on scripting language) that can be used to access the data using the other Test Data Functions functions. (It is also possible to access test data anywhere by giving a filename with a path, but we recommend storing test data in the relevant test suite or test case.) If we want to have one or more additional scripts to neatly compartmentalize functionality, or to simplify our test.* test script, we can create additional script files. Given the earlier assumptions, if we want to have an extra test case-specific script we must put it in the same directory as the test.* test script, for example, myapp_suite/tst_case1/extra.py. If we have extra functionality that we want to be accessible to all of our test suite's test scripts, we must put the additional script in the test suite's shared scripts folder, e.g., myapp_suite/shared/scripts/common.py. If we want to have functionality that can be shared by any test case in any test suite we can add a global test script to the Global Scripts view. Regardless of whether the test script is test case-specific or shared by the whole test suite or global to all of our test suites, we always use the same technique to access the script's functionality: we call the source(filename) function with the script's name (including its path). Typically we get the name by calling the String findFile(where, filename) function giving it a first argument of "scripts" and a second argument of the script's name (without any path)—this will work for test case-specific scripts and for scripts shared by any of the test suite's test cases, and also for global shared scripts. Note that on Ruby we use the require function instead of souce. To create a script that can be shared by any test case in a test suite, in the Squish IDE's Test Suites view's Test Suite Resources section, click the New Test Script File toolbar button. This will create a new empty shared script called script_1.py (or script_1.js, and so on, depending on the scripting language in use). The script can be renamed to something more meaningful, either immediately by entering a new name, or later by clicking it and invoking the context menu and using the Rename option. (In the screenshot we have renamed the shared script common.py since it contains common functionality.) The Squish IDE with the New Test Script File toolbutton tooltip visible Once the shared script has been renamed, click (or double-click depending on your platform and settings) to show it in an Editor view. You can now edit the script to add any shared functionality you require. It is also possible (although less common) to add a shared script that can only be used by a particular test case. To do this click the New Test Script File toolbar button in the Test Suites view's Test Case Resources panel. And, of course, we can add as many shared script files to our test suites (and test cases) as we like. If you want to create a global shared script, that is, one that can be accessed by any test case in any test suite, open or click the Global Scripts view and add it through that view. If you want to import an existing script into a test suite's (or test case's) shared script's folder, click File > Import Test Resource. This will pop up the Import Squish Resource dialog. Enter the name of the script file to import (or choose it using the Browse button. Then set the Import As combobox item to "Script". If you want the script to be shared by all of the test suite's test cases (rather than just the current one that is shown), check the Create shared File in Test Suite radio button. This is recommended since it is usually more convenient to share scripts amongst all test cases. Now click the Finish button and the imported script will be available in the Squish IDE. It is possible to create shared scripts without using the Squish IDE at all. First, in the console, change directory to the test suite's directory. Then create a new subdirectory called shared if it doesn't already exist. Now change into this directory and create a new subdirectory called scripts if it doesn't already exist. Now use your editor or IDE to create the shared script and be sure to save it in the test suite's shared/scripts directory. And if you already have the script simply copy it into that directory. If you want to add a global shared script just create or copy it to the directory (or one of the directories) you want to use for that purpose. There may be situations where shared functionality might be useful not only in one particular test suite, but in most or all test suites. Squish makes it possible for all test suites to access globally shared scripts. This is achieved by creating one or more directories (wherever you like) that you will put all the globally shared scripts into. Then, to tell Squish that there are such directories, either register them using the Global Scripts view (which will add them to the paths.ini initialization file, or set the SQUISH_SCRIPT_DIR environment variable to one or more paths. For example, on Unix using the bash shell, export SQUISH_SCRIPT_DIR=$HOME/tests/shared_scripts. See also, Environment Variables and Setting Environment Variables for the AUT. Once a shared script has been created, it can be used by any test case-specific scripts that need it. Note though, that shared scripts are not usually imported using the language-specific import mechanism—after all, not all languages have such a mechanism, for example, JavaScript doesn't. Instead, the Squish API provides the necessary functions. The standard way to locate a shared script file (or shared data file), is to use the String findFile(where, filename) function. The first argument is the type of file, which for shared scripts should be "scripts". The second argument is the script's filename (with no path). The function will search all the standard locations that Squish uses, and will return the filename including its full path. Once we have the full path to the shared script, we can include it in our test case's script. This is done by evaluating the shared script using the source(filename) function—this means that it is in effect executed as if the actual text of the shared script was in the test case at the point where we call the source(filename) function. After this is done, all the objects created in the shared script—typically, classes and functions—become accessible in the test case's script. Here is an example where we want to share a script file called address_utility.py (or address_utility.js, etc., depending on the scripting language being used), so that we can access a function inside it—in this example, the insertDummyNamesAndAddresses function—that populates an addressbook AUT with some names and addresses so that there is some data present for further tests to work on. def main(): ... source(findFile("scripts", "address_utility.py")) insertDummyNamesAndAddresses() ... function main() { // ... source(findFile("scripts", "address_utility.js")); insertDummyNamesAndAddresses(); // ... } sub main { # ... source(findFile("scripts", "address_utility.pl")); insertDummyNamesAndAddresses(); # ... } # encoding: UTF-8 require 'squish' include Squish def main # ... require findFile("scripts", "address_utility.rb") insertDummyNamesAndAddresses # ... end proc main {} { # ... source [findFile scripts "address_utility.tcl"] insertDummyNamesAndAddresses # ... } Here we import the address_utility.py (or similar) script which defines a function called insertDummyNamesAndAddresses, which we are then able to call. For scripting languages that support importing, such as Python, it is possible to use the language's standard import mechanism. However, Squish's approach is usually more convenient, since in most cases our shared scripts are only relevant to our tests. In general, for shared scripts it is best to use Squish's source(filename) function, but to import standard modules it is best to use the language-specific mechanism (e.g., import in Python and use in Perl). In Ruby, use the standard require function instead of Squish's source function. Just as we have a test case script, we can also have test case-specific data files. Such files are stored in the test case's testdata directory. However, in some cases, we want to share the test data so that more than one test case can access it. In this case we store the test data in the test suite's shared/testdata directory. Test data can be added through the Squish IDE by importing files—Squish can read .tsv (tab-separated values format), .csv (comma-separated values format), .xls or .xlsx (Microsoft Excel spreadsheet format). Or we can simply create the directories on the command line in a console and copy our test data into them. The techniques used for adding shared test data, whether using the Squish IDE or manually, are exactly the same as for adding shared test scripts, only we use the appropriate testdata directory (rather than the scripts directory). Although the top-level directory structure must follow what we have described, within that structure—i.e., under a testdata directory—you are free to create subdirectories and structure them however you like. Retrieving test data is done using the String findFile(where, filename) function we mentioned earlier, only this time the first argment must be "testdata", and the second argument the name of the test data file you want to access. In practice we don't usually need to use the String findFile(where, filename) function for test data. Instead we use the Dataset testData.dataset(filename) function and access the data using Squish's Test Data Functions API, as we will see in the next section. How to Do Data-Driven Testing Data-driven testing is an approach where the test data (input, and expected output), is kept separate from the test script code which only contains the test's logic. The normal practice is for the test data to be read from a file or database one item or record at a time, and for the test script to use the data to test the AUT and then compare the results with those that are expected. One benefit of this approach is that it makes it possible to modify a test without actually having to change the test case's code—instead we simply add more data which the test then reads and processes along with the rest of the data. This makes it possible to separate responsibility for creating tests between test engineers who have coding skills and those who don't. Those with coding skills can create test scripts and encode the test logic in them, and test engineers who don't have coding skills can create and edit the test data that the test scripts use to test the AUT. Squish provides an API for handling test data (see Test Data Functions), that makes it easy to create data-driven tests. Here we will look at how to use Squish's script API to read and use test data, and will assume that the test data has already be imported or copied into the appropriate testdata directory. Test data always contains data in a tabular format. Squish can read files in .tsv (tab-separated values format), .csv (comma-separated values format), .xls or .xlsx (Microsoft Excel spreadsheet format) format). In the case of .csv and .tsv files, Squish assumes that they use the Unicode UTF-8 encoding—the same encoding that is used for test scripts. In .tsv files, records are separated by new lines and fields are separated by tabs. The first record is used to describe the columns. Here is an example .tsv data file— addresses.tsv—with tabs indicated by "\t" and newlines indicated by "\n" characters: First Name\tLast Name\tAddress\tEmail\tNumber\n Max\tMustermann\tBakerstreet 55\tmax@mustermann.net\t1\n John\tKelly\tRhodeo Drv. 678\tjkelly@acompany.com\t2\n Joe\tSmith\tQueens Blvd. 37\tjoe@smith.com\t3\n Each field (column) is separated by a tab, and each record (row, or line) is separated by a newline. As is common practice with .tsv (and .csv) files, the first line is not data as such, but instead the field (column) names ("First Name", "Last Name", etc.). All the other lines are data records. Here is an example where we read each record in turn and print its values to Squish's log: for record in testData.dataset("addresses.tsv"): firstName = testData.field(record, "First Name") lastName = testData.field(record, "Last Name") address = testData.field(record, "Address") email = testData.field(record, "Email") test.log("%s %s, %s; email: %s" % ( firstName, lastName, address, email)) var records = testData.dataset("addresses.tsv"); for (var row = 0; row < records.length; ++row) { var record = records[row]; firstName = testData.field(record, "First Name"); lastName = testData.field(record, "Last Name"); address = testData.field(record, "Address"); email = testData.field(record, "Email"); test.log(firstName + " " + lastName + ", " + address + "; email:" + email); } my @records = testData::dataset("addresses.tsv"); for (my $row = 0; $row < scalar(@records); $row++) { my $record = $records[$row]; my $firstName = testData::field($record, "First Name"); my $lastName = testData::field($record, "Last Name"); my $address = testData::field($record, "Address"); my $email = testData::field($record, "Email"); test::log("$firstName $lastName, $address; email: $email"); } TestData.dataset("addresses.tsv").each do |record, row| firstName = TestData.field(record, "First Name") lastName = TestData.field(record, "Last Name") address = TestData.field(record, "Address") email = TestData.field(record, "Email") Test.log("#{firstName} #{lastName}, #{address}; email: #{email}") end set records [testData dataset "addresses.tsv"] for {set row 0} {$row < [llength $data]} {incr row} { set record [lindex $records $row] set firstName [testData field $record "First Name"] set lastName [testData field $record "Last Name"] set address [testData field $record "Address"] set email [testData field $record "Email"] test log "$firstName $lastName, $address; email: $email" } Notice that we access fields by name, so the names we use in our test case's code must match those in the first line of the test data file. Also, although the data has a "Number" field at the end, we ignore it because we don't need it. In typical cases the test data file is found using the Dataset testData.dataset(filename) function which searches for test data in standard locations and returns an array or tuple of records. (It is also possible to give this function the name of a file including a path—for example, as returned by the String findFile(where, filename) function). We then use the String testData.field(record, fieldName) function to access the contents of individual fields within a given record. By using a for loop we can iterate over every record in the testdata—without having to know in advance how many records there are, so the code is unaffected if records are removed or added. And of course, in a realistic test we would feed the data to the AUT and compare expected with actual results rather than simply printing the data to the log as we have done here. Most of the tutorials include a complete example of a data-driven test. For a Qt example, see Creating Data Driven Tests; for a Java AWT/Swing example, see Creating Data Driven Tests; for a Java SWT example, see Creating Data Driven Tests; and for a Tk/Tcl example, see Creating Data Driven Tests. How to Use Test Data in the AUT So far this section has only discussed using test data in test scripts to create data driven tests. But two other use cases arise in practice. One use case is where test data files are provided for the AUT to read, and another is where we want to retrieve files that the AUT has created during the test run so that they can be verified. Let's start by looking at the first use case where we provide a data file for the AUT to read. For example, imagine we are using the addressbook AUT and we want it to load a file called customers.adr at the start of the test script so that it has a known set of data to work on. This is easily achieved by storing the data file in the test case's directory, or its testdata directory—or in the test suite's shared/testdata directory, if we want more than one test case to be able to access it. We want to avoid hard-coding the path to the data file in our test script since we want the flexibility to run our tests on different machines, and even on different platforms. We can copy a data file into the AUT's current working directory (without having to know its path) using the testData.put(filename) function. We only need to give the name of the file to this function since it will automatically look in the test case's directory. If we want to put a file from the test case's testdata directory or from the test suite's shared/testdata directory, we can call the testData.put(filename) function with the results of a call to the String findFile(where, filename) function, giving the latter a first argument of "testdata" and a second argument of the filename (without a path). Another benefit of using the testData.put(filename) function is that once the test run has finished, Squish will automatically clean up for us (i.e., Squish will delete the file from the AUT's working directory). Here is an example where we copy a test data file from the current test case's directory into the AUT's working directory. Then we access the AUT's main window object ( Addressbook), and call that object's fileOpen method with the name of the file we want it to load. def main(): ... testData.put("customers.adr") findObject("Addressbook").fileOpen("customers.adr") ... function main() { // ... testData.put("customers.adr"); findObject("Addressbook").fileOpen("customers.adr"); // ... } sub main() { # ... testData::put("customers.adr"); findObject("Addressbook")->fileOpen("customers.adr"); # ... } # encoding: UTF-8 require 'squish' include Squish def main #... TestData.put("customers.adr") findObject("Addressbook").fileOpen("customers.adr") #... end proc main {} { # ... invoke testData put "customers.adr" [invoke [invoke findObject "Addressbook"] fileOpen "customers.adr"] # ... } Another use case is where we need to verify that a file which has been created by the AUT has the contents we expect. For example, let's assume that during a test the addressbook AUT loads a data file, customers.adr, performs various operations (adds, edits, and deletes, addresses), and then saves its current address data into a new file, edited-customers.adr. After this has happened we want our test script to compare the edited-customers.adr file with another file, expected-customers.adr which has the contents we expect the file to have after accounting for the changes to the data made earlier in the script. We can copy a file to the AUT's current directory using the testData.put(filename) function. Here's an example that saves a file to the AUT's current working directory, copies an "expected" file into the AUT's current working directory, and then reads both files and compares them to see if they match.) function main() { // Load customers.adr and add/edit/delete addresses ... var mainwindow = waitForObject("Addressbook"); // Use the AUT's API to save the data to the AUT's directory mainwindow.saveAs("edited-customers.adr"); // Copy "expected" from the AUT's directory to the test case's directory testData.get("expected-customers.adr"); var edited = File.open("edited-customers.adr").read(); var expected = File.open("expected-customers.adr").read(); test.compare(edited, expected); } sub main { # Load customers.adr and add/edit/delete addresses ... my $mainwindow = waitForObject("Addressbook"); # Use the AUT's API to save the data to the AUT's directory $mainwindow->saveAs("edited-customers.adr"); # Copy "expected" from the AUT's directory to the test case's directory testData::get("expected-customers.adr"); open(FH1, "edited-customers.adr"); open(FH2, "expected-customers.adr"); my $edited = join("", <F1>); my $expected = join("", <F2>); test.compare($edited, $expected); } # encoding: UTF-8 require 'squish' include Squish) end proc main {} { # Load customers.adr and add/edit/delete addresses ... set mainwindow [waitForObject "Addressbook"] # Use the AUT's API to save the data to the AUT's working directory invoke $mainwindow saveAs "edited-customers.adr" # Copy "expected" from the AUT's directory to the test case's directory testData get "expected-customers.adr" set edited [read [open "edited-customers.adr"]] set expected [read [open "expected-customers.adr"]] test compare $edited $expected } We begin by getting a reference to the AUT's main window object; then we call the main window's saveAs method to save the edited data. Then we open both the newly saved data and the expected data files (the latter copied into the AUT's working directory), and read their entire contents. Finally, we compare the contents of the files using the Boolean test.compare(value1, value2) function. Squish's data handling API (see Test Data Functions) has other useful functions. For example, if we only need to test that a file has been created without concern for its contents we can call the Boolean testData.exists(filename) function. And if we want to remove a file in the course of a test we can call the testData.remove(filename) function.
https://doc-snapshots.qt.io/squish/how-to-create-and-use-shared-data-and-shared-scripts.html
CC-MAIN-2022-33
refinedweb
4,177
62.58
IEEE/The Open Group 2013 Aliases: environ(3p), execl(3p), execle(3p), execlp(3p), execv(3p), execve(3p), execvple, execlp, execv, execve, execvp, fexecve — execute a fileve(const char *path, char *const argv[], char *const envp[]); int execvp(const char *file, char *const argv[]); int fexecve(int fd, char *const argv[], char *const envp[]); DESCRIPTION.-2008, string descriptor 0, 1, or 2 would otherwise be closed after a successful call to one of the exec family of functions, implementations may open an unspecified file for the file descriptor in the new process image. If a standard utility or a conforming application is executed with file descriptor 0 not open for reading or with file descriptor 1 or 2 not open for writing, the environment in which the utility or application is executed shall be deemed non-conforming, and consequently the utility or application might not behave as described in this standard.. The new process shall inherit at least the following attributes from the calling process image:The initial thread of the new process shall inherit at least the following attributes from the calling thread: All other process attributes defined in this volume of POSIX.1-2008 shall be inherited in the new process image from the old process image. All other thread attributes defined in this volume of POSIX.1-2008 shall be inherited in the initial thread in the new process image from the calling thread in the old process image. The inheritance of process or thread attributes not defined by this volume of POSIX.1-2008. RETURN VALUE If one of the exec functions returns to the calling process image, an error has occurred; the return value shall be -1, and errno shall be set to indicate the error. ERRORS The exec functions shall fail if: The following sections are informative. EXAMPLES Using execl() The following example executes the ls command, specifying the pathname of the executable ( /bin/ls) and using arguments supplied directly to the command to produce single-column output. #include <unistd.h> int ret; ... ret = execl ("/bin/ls", "ls", "-1", (char *)0); Using execle(). #include <unistd.h> int ret; char *cmd[] = { "ls", "-l", (char *)0 }; ... ret = execvp ("ls", cmd); APPLICATION USAGE as the global locale in the new process image should call setlocale() with the appropriate parameters. When assigning a new value to the environ variable, applications should ensure that the environment to which it will point contains at least the following called. RATIONALE Early proposals required that the value of argc passed to main() be ‘‘one POSIX.1-2008 string associated with the process being started. Although some existing applications pass a pathname rather than a filename string in some circumstances, a filename string ‘‘login POSIX.1-2008. \(dq#!\(dq:Some implementations provide a third argument to main() called envp. This is defined as a pointer to the environment. The ISO C standard specifies invoking main() with two arguments, so implementations must support applications written this way. Since this volume of POSIX.1-2008 POSIX.1-2008 specifies that signals set to SIG_IGN remain set to SIG_IGN, and that the new process image inherits the signal mask of the thread that called exec in the old process image. cooperating) POSIX.1-2008 POSIX.1-2008 is to be used if there is no user-provided environ to take precedence. At least three implementations are known to exist that solve this problem. Alternatively, an function like openat() can be used to open a file which has been found by reading the content of a directory using readdir(). FUTURE DIRECTIONS None. SEE ALSO alarm(), atexit(), chmod(), close(), confstr(), exit(), fcntl(), fork(), fstatvfs(), getenv(), getitimer(), getrlimit(), mknod(), mmap(), nice(), open(), posix_spawn(), posix_trace_create(), posix_trace_event(), posix_trace_eventid_equal(), pthread_atfork(), pthread_sigmask(), putenv(), readdir(), semop(), setlocale(), shmat(), sigaction(), sigaltstack(), sigpending(), system(), times(), ulimit(), umask() The Base Definitions volume of POSIX.1-2008, Chapter 8, Environment Variables, .
https://reposcope.com/man/en/3p/exec
CC-MAIN-2019-51
refinedweb
643
51.07
User Details - User Since - Apr 5 2014, 8:26 PM (311 w, 6 d) Jan 10 2020 Oct 14 2018 Oct 7 2018 Thanks, What changed in SWIG 3.0.11? Oct 6 2018 Changing title as it looks like this is not a Windows-only problem:. Sep 18 2017 Maybe LLDB should use qAttached to determine if there's an active process? OpenOCD seems to implement that one correctly. Sorry, for not catching this regression! I've checked that attaching to a standard gdbserver still worked, but was not aware of the other scenarios. Sep 17 2017 FYI - this broke at least Windows, because the default behavior of Process::WillResume() changed from success to an error and WindowsProcess does not override WillResume(). Not sure what other platforms are in the same boat. Sep 15 2017 This is what I see in the log: < 16> send packet: $qfThreadInfo#bb < 5> read packet: $l#6c And here's code that generates it: Jul 5 2017 Jul 1 2017 Eli, I can commit this if you are busy. Just give a nod. Jun 30 2017 Tested Eli's version and was able to build all of rustc's standard library for the wasm32-... target. Jun 22 2017 Jun 16 2017 Jun 15 2017 I'm definitely not an expert on this part of LLVM, but to me this change seems very fragile, as it assumes things about the types of certain DAG nodes, which may be true now, but may change in the future. Jun 6 2017 Rust and Go are not the only missing languages. Looks like all of the newly-added DWARF5 language codes are not covered here. Jun 2 2017 Though... wouldn't "category_lang == valobj_lang" be a sane default behavior for any languages not mentioned specifically below? Jan 27 2017 Jan 26 2017 Could we make CMAKE_INSTALL_UCRT_LIBRARIES the default when building for Windows? Would there be any downside to that? Jan 25 2017 Dec 21 2016 Ping! Should I ask somebody else to review? Dec 6 2016 Nov 2 2015 Nov 1 2015 @rnk, Sounds like compiler-rt *is* a drop-in replacement for libgcc, so let's add 64-bit versions of chkstk/alloca for gcc objects. Oct 26 2015 Oct 25 2015 Sorry, one more revision. Apparently chkstk needs triple underscore... <sigh> On second thought, elimination of probe for the last page is not correct - that final push of the return address could land on the next page... Also, I've figured out a better way to preserve eax. Oct 24 2015 After playing with this some more - it's no fun linking with gcc-generated libraries, because they actually do use __checkstk_ms, so you have to pull in libgcc as well, and end up with duplicate symbols. Let's add _chkstk as an extra, not as replacement. Oct 22 2015 Hi! So apparently LLVM lowers alloca's of large buffers into a call to _alloca (makes sense I guess - if the buffer is larger than a page). Why wasn't it added along with _chkstk? Is _alloca available from some other mingw library? Dec 9 2014 Dropped "-fPIC" part of the change, dropped #ifdef WIN32_ check. Dec 6 2014 Hi, You guys seem to be the most active in compiler-rt repo. Can you please review and commit? (or suggest somebody more appropriate). Thanks! Dec 4 2014 Aug 1 2014 Implemented 'SEH_Epilogue' approach. Jun 30 2014 Jun 27 2014 Jun 23 2014 @chapuni, Which tests broke? Is there a PR? I saw that MultiJitTest.JitPool fails, but it was failing before my change too, so I ignored it. Hmm, something must be wrong at the MC layer. When I assemble the output of llc with gnu assembler (after replacing register numbers with names in seh directives), it seems to produce a correct .obj. Jun 22 2014 Jun 20 2014 FYI - this commit broke LLVM build using win32 threads flavor of the mingw toolchain. I am getting error: 'recursive_mutex' in namespace 'std' does not name a type. Not sure if this would be considered a problem for LLVM... Jun 19 2014 Fixed x86-64-static-relo-movl.ll and rebased. Is 'x86_64-pc-win32-macho' a valid target? Windows 64 ABI in OSX object file seems like a weird combination. Jun 18 2014 Yes, please commit, if you don't mind running format yourself. Jun 13 2014 Addressed review comments. Jun 12 2014 Jun 10 2014 Whoops, looks like I got .cfi_offset and .cfi_rel_offset mixed up. The original offsets in bigstructret2.ll test were actually correct. Also, rebased on top of master. Jun 9 2014 I've updated my patch. It should now solve your problem too. Jun 8 2014 @sanjoy, I wonder what happens with your patch in case of stack re-alignment. Sorry, I can't figure out how to get git to apply your diff. Could you please try it on the following IR: Jun 7 2014 Looking at the llc output you provided in the bug, I notice that it spilled and emitted CFI info for XMM registers. What target was that compiled for? AFAIK, only Windows 64 ABI specifies XMMs as callee-saved. So if it was for Win64, my patch would directly address your problem. Jun 6 2014 With more context Hi Sanjay, Please take a look at my preliminary patch to support Win64 SEH I've put here: (specifically stuff in X86FrameLowering.cpp). Not directly related to 19905, however, it touches the same code, and could benefit from the same refactoring. May 2 2014 This patch doesn't work right. I am seeing stuff like this in the emitted code: pushq %rbp .seh_pushreg %rdi Which, I guess, makes sense, because MCAsmStreamer::EmitRegisterName performs DWARF->LLVM register index mapping before emitting the name. Apr 28 2014 @nrieck, you've said above "I believe it's not necessary to change the prologue emission for Win64". However I don't see how would one express 'and ..., %rsp' with SEH unwind instructions, because the effective RSP offset here is not a compile-time constant. Apr 25 2014 There's been much back-and-forth on the mailing list thread, so I am no longer sure which problems absolutely need to be fixed, and which were mentioned just in passing. It would be helpful to restate them in one place (here probably). Ping... It's been a week since anything happened on this review. Is there any action that can be taken to un-stall this?
https://reviews.llvm.org/p/vadimcn/
CC-MAIN-2020-16
refinedweb
1,081
74.69
Investors in Whirlpool Corp (Symbol: WHR) saw new options become available today, for the July 15th expiration. At Stock Options Channel, our YieldBoost formula has looked up and down the WHR options chain for the new July 15th contracts and identified one put and one call contract of particular interest. The put contract at the $170.00 strike price has a current bid of $9.40. If an investor was to sell-to-open that put contract, they are committing to purchase the stock at $170.00, but will also collect the premium, putting the cost basis of the shares at $160.60 (before broker commissions). To an investor already interested in purchasing shares of WHR, that could represent an attractive alternative to paying $171.41 5.53% return on the cash commitment, or 35.41% annualized — at Stock Options Channel we call this the YieldBoost. Below is a chart showing the trailing twelve month trading history for Whirlpool Corp, and highlighting in green where the $170.00 strike is located relative to that history: Turning to the calls side of the option chain, the call contract at the $175.00 strike price has a current bid of $9.00. If an investor was to purchase shares of WHR stock at the current price level of $171.41/share, and then sell-to-open that call contract as a "covered call," they are committing to sell the stock at $175.00. Considering the call seller will also collect the premium, that would drive a total return (excluding dividends, if any) of 7.34% if the stock gets called away at the July 15th expiration (before broker commissions). Of course, a lot of upside could potentially be left on the table if WHR shares really soar, which is why looking at the trailing twelve month trading history for Whirlpool Corp, as well as studying the business fundamentals becomes important. Below is a chart showing WHR's trailing twelve month trading history, with the $175.00 strike highlighted in red: Considering the fact that the $175.25% boost of extra return to the investor, or 33.62% annualized, which we refer to as the YieldBoost. Meanwhile, we calculate the actual trailing twelve month volatility (considering the last 253 trading day closing values as well as today's price of $171.41) to be 32%. For more put and call options contract ideas worth looking at, visit StockOptionsChannel.com. The views and opinions expressed herein are the views and opinions of the author and do not necessarily reflect those of Nasdaq, Inc.
https://www.nasdaq.com/articles/whr-july-15th-options-begin-trading
CC-MAIN-2022-27
refinedweb
429
64.2
SSMs Directly from Images DeepSSM is a deep learning framework that estimates statistical representations of shape directly from unsegmented images once trained. DeepSSM includes a data augmentation process and a convolutional neural network (CNN) model. This documentation provides an overview of the DeepSSM process; see relevant papers for a full explanation.. What is DeepSSM? The input to the DeepSSM network is unsegmented 3D images of the anatomy of interest, and the output is the point distribution model (PDM). DeepSSM requires training examples of image/PDM pairs that are generated via the traditional Shapeworks grooming and optimization pipeline or other particle distribution models. Once the network has been trained on these examples, it can predict the PDM of unseen examples given only images of the same anatomy/object class, bypassing the need for labor-intensive segmentation, grooming, and optimization parameter tuning. Why DeepSSM? The benefits of the DeepSSM pipeline include: - Less Labor: DeepSSM does not require segmentation, only a bounding box about where the anatomy of interest lies in the image. - End-to-end: Does not require separate grooming and optimization steps; it is an end-to-end process. This also reduces memory requirement as images do not need to be saved after intermediate grooming steps. - Faster Results: Once a DeepSSM network has been trained, it can be used to predict the shape model on a new image in seconds on a GPU. The DeepSSM network is implemented in PyTorch and requires a GPU to run efficiently. DeepSSM Steps 1. Data Augmentation The first step to creating a DeepSSM model is generating training data. Deep networks require thousands of training instances and since medical imaging data is typically limited, data augmentation is necessary. The data augmentation process is described here: Data Augmentation for Deep Learning. The data augmentation process involves reducing the PDM's to a low-dimensional space via Principal Component Analysis (PCA), preserving a chosen percentage of the variation. The PCA scores are saved and used as the target output for DeepSSM prediction. The PCA scores are deterministically mapped back to the PDM (i.e., shape space) using the eigenvalues and vectors once the DeepSSM model makes a prediction. 2. Creation of Data Loaders The next step is to reformat the data (original and augmented) into PyTorch tensors. 80% of the data is randomly selected to be training data, and the remaining 20% of the data is used as a validation set. The input images are whitened and turned into tensors. They can also be optionally downsampled to a smaller size to allow for faster training. The corresponding PCA scores are also normalized or whitened to avoid DeepSSM learning to favor the primary modes of variation and are then turned to tensors. PyTorch data loaders are then created with a batch size specified by the user. 3. Training PyTorch is used in constructing and training DeepSSM. The network architecture is defined to have five convolution layers followed by two fully connected layers, as illustrated in the figure below. Parametric ReLU activation is used, and the weights are initialized using Xavier initialization. The network is trained for the specified number of epochs using Adam optimization to minimize the L2 loss function with a learning rate of 0.0001. The average training and validation error are printed and logged each epoch to determine convergence. 4. Testing The trained model is then used to predict the PCA score from the images in the test set. These PCA scores are then un-whitened and mapped back to the particle coordinates using the eigenvalues and eigenvectors from PCA. Thus a PDM is acquired for each test image. 5. Evaluation To evaluate the accuracy of DeepSSM output, we compare a mesh created from the ground truth segmentation to a mesh created from the predicted PDM. To obtain the original mesh, we use the ShapeWorks MeshFromDistanceTransforms command to the isosurface mesh from the distance transform created from the true segmentation. To obtain the predicted mesh, we use the ShapeWorks ReconstructSurface command with the mean and predicted particles to reconstruct a surface. We then compare the original mesh to the predicted mesh via surface-to-surface distance. To find the distance from the original to the predicted, we consider each vertex in the original and find the shortest distance to the predicted mesh's surface. This process is not symmetric as it depends on the vertices of one mesh, so the distance from the predicted to the original will be slightly different. We compute the Hausdorff distance that takes the max of these vertex-wise distances to return a single value as a measure of accuracy. We also consider the vertex-wise distances as a scalar field on the mesh vertices and visualize them as a heat map on the surface. This provides us with a way of seeing where the predicted PDM was more or less accurate. Using the DeepSSM Python Package The ShapeWorks DeepSSM package, DeepSSMUtils, is installed to the ShapeWorks anaconda environment when conda_installs.sh is run. Activate shapeworks environment Each time you use ShapeWorks and/or its Python packages, you must first activate its environment using the conda activate shapeworks command on the terminal. To use the DeepSSMUtils package, make sure you have the shapeworks conda environment is activated and add the following import to your Python code: import DeepSSMUtils Get train and validation torch loaders This function turns the original and augmented data into training and validation torch loaders. The data provided is randomly split so that 80% is used in the training set and 20% is used in the validation set. DeepSSMUtils.getTrainValLoaders(out_dir, data_aug_csv, batch_size=1, down_sample=False) Input arguments: out_dir: Path to the directory to store the torch loaders. data_aug_csv: The path to the csv containing original and augmented data, which is the output when running data augmentation as detailed in Data Augmentation for Deep Learning. batch_size: The batch size for training data. The default value is 1. down_sample: If true, the images will be downsampled to a smaller size to decrease the time needed to train the network. If false, the full image will be used. The default is false. Get test torch loader This function turns the provided data into a test torch loader. DeepSSMUtils.getTestLoader(out_dir, test_img_list, down_sample) Input arguments: out_dir: Path to the directory to store the torch loader. test_img_list: A list of paths to the images that are in the test set. down_sample: If true, the images will be downsampled. If false, the full image will be used. This should match what is done for the training and validation loaders. The default is false. Train DeepSSM This function defines a DeepSSM model and trains it on the data provided. DeepSSMUtils.trainDeepSSM(loader_dir, parameters, out_dir) Input arguments: loader_dir: Path to directory where train and validation torch loaders are. parameters: A dictionary of network parameters with the following keys. epochs: The number of epochs to train for. learning_rate: The value of the learning rate. val_freq: How often to evaluate on the validation set. 1 means test on the validation set every epoch, 2 means every other epoch, and so on. out_dir: Directory to save the model and training/validation logs. Test DeepSSM This function gets predicted shape models based on the images provided using a trained DeepSSM model. DeepSSMUtils.testDeepSSM(out_dir, model_path, loader_dir, PCA_scores_path, num_PCA) Input arguments: out_dir: Path to directory where predictions are saved. model_path: Path to train DeepSSM model. loader_dir: Path to the directory containing test torch loader. PCA_scores_path: Path to eigenvalues and eigenvectors from data augmentation that are used to map predicted PCA scores to particles. num_PCA: The number of PCA scores the DeepSSM model is trained to predict. Analyze Results This function analyzes the shape models predicted by DeepSSM by comparing them to the true segmentation. DeepSSMUtils.analyzeResults(out_dir, DT_dir, prediction_dir, mean_prefix) Input arguments: out_dir: Path to the directory where meshes and analysis should be saved. DT_dir: Path to the directory containing distance transforms based on the true segmentations of the test images. prediction_dir: Path to the directory containing predicted particle files from testing DeepSSM. mean_prefix: Path to the mean particle and mesh files for the dataset.
http://sciinstitute.github.io/ShapeWorks/deep-learning/deep-ssm.html
CC-MAIN-2021-04
refinedweb
1,355
54.93
No Duplication, No Decoupling - The Generic Data Transfer Object Lazy loading and binary dependencies are the main problem of direct exposure of persistent domain objects in stateless architectures. The user has know in advance, what path (subgraph) of lazy relations has to be loaded. The invocation of not yet loaded relations in a unmanaged entity will result in exceptions and errors. Typesafe DTOs are often introduced - only to enforce the eager loading of the entities. Such DTOs are very similar - if not identical to the persistent entities - what causes repetition and actually decreases the maintainability. Furthermore a client is not always interested in a type safe structure, rather than in rich metadata and reflective APIs. A UI can be even partially generated from the DTO's meta data in that case. The solution is simple - a usual java.util.Map is a perfect tool for data transportation between layers. It was only wrapped in a GenericDTO for convenience: public class GenericDTO implements Serializable { private static final long serialVersionUID = 1L; private Map<String, Attribute> attributes = null; private Map<String, Set<GenericDTO>> relations = null; private String name = null; public GenericDTO(String name) { notNull(name, "The name of the DTO cannot be null..."); this.attributes = new HashMap<String, Attribute>(); this.relations = new HashMap<String, Set<GenericDTO>>(); this.name = name; } public GenericDTO add(String name, Attribute attribute) { notNull(name, "Attribute name cannot be null"); notNull(attribute, "Attribute with name: " + name + " is null!"); this.attributes.put(name, attribute); return this; } public GenericDTO addString(String name, String value) { notNull(name, "Attribute name cannot be null"); notNull(value, "Attribute with name: " + name + " is null!"); this.attributes.put(name, new StringType(null,value)); return this; } //some book keeping methods omitted. The GenericDTO will never change it structure - what makes your APIs binary compatible. This is only possible because, the GenericDTO's content and not the structure transports the type information. Your code will always compile - but not always run. With GenericDTO you, and not the compiler, are responsible for type checks. Furthermore you will have to give up auto-completion support in IDEs. Working with GenericDTOs requires lot of plumbing, but on the other hand, they can be easily constructed and read using the Java's reflection mechanism: @Test public void construction(){ GenericDTO dto = null; String description = "description"; String name = "name"; String numberOfPages = "numberOfPages"; try { dto = new GenericDTO("Book"). addString(description, "Duke's Adventures"). addString(name, "Java"). addInt(numberOfPages, 10). validate(); } catch (CompositeValidationException ex) { fail("Not excected " + ex); } The GenericDTOs payload are not primitive types / wrappers, rather than implementations of the Attribute interface: public interface Attribute<T> extends Serializable{ public void validate() throws ValidationException; public void instantiateFromString(String content); public void setRegexp(String regExp); public void setId(); public T getValue(); public boolean isId(); } All the concrete Attribute implementations are able to validate, as well as construct itself from a String. This can be leveraged to automatically create attributes from the user input in the UI. This flexibility comes with price: a GenericDTO needs an order of magnitude more instances at runtime, than an usual, type safe DTO. By the way a GenericDTO: is a DTO, not a VO. The whole example with attribute implementations and unit tests was pushed into: [See Generic DTO, page 162 in "Real World Java EE Patterns Rethinking Best Practices" book for more in-depth performance / maintainability - "Your code will always compile - but not always run." - "Working with GenericDTOs requires lot of plumbing..." No need to say more! This reminds me of Struts' DynaActionForms and the long road we've taken since then. Do we really need to go back? Posted by John on September 25, 2009 at 12:37 PM CEST # @John, I used this approach in the past for CRUD-use cases. It worked very well. However, it is not a general best practice (as all other patterns). If you decided to use GDTOs / SDOs (Service Data Objects), you shouldn't touch them in the IDE, rather than populate them from the meta data / reflection and leverage fully the "Convention Over Configuration" principle, thanks!, adam Posted by Adam Bien on September 25, 2009 at 12:52 PM CEST # I was wondering what your experience with generic DTOs is. Currently I'm in a project where a new project lead has stepped in and started to make this pattern a general pattern to be used everywhere where a client (flex, java, etc.) would communicate using generic DTOs. Almost 100% of client-server communication is done through remoting using this generic DTO, the number of users on this system is going to be close to a 4 digits number. That pattern introduces quite some bad consequences ->no compiler checks -> ->refactorings are a nightmare -> no longer code complete support by the IDE ->quite a lot of serialization going on (probably even more than with classic DTO classes) -> there are many many more cons ... I think that pattern should only be applied with strong arguments for flexible data structure but not as a general means of data transport! Posted by Martin Ahrer on September 25, 2009 at 02:00 PM CEST # I've always considered DTO an anti-pattern (rather than a pattern). It it a sign that something is broken in the communication channel between the bits that "need" the DTO. Quite often the broken bit isn't broken it's more an enforced pattern that simply should never have been used. DTO was an unfortunate by-product (protection against revolving door performance anti-pattern) of EJB 1.x, 2.x.... We're over EJB 2.x... and thus we should relegate it to the dustbin where it belongs. My question is, isn't GDTO along the same lines? Regards, Kirk Posted by kirk on September 27, 2009 at 08:12 PM CEST # This pattern was discussed in detail in Floyd's 'EJB Design Patterns' in 2002 and even at that time it rather counted as an antipattern.. I agree with the guys here, we shouldn't really advocate this. Posted by Kristof on September 28, 2009 at 10:38 AM CEST # Type safety is a fundamental feature of Java. Well designed applications should avoid generic objects VOs, DTOs etc.. and use pure domain POJOs as much as possible. I agree this is an anti-pattern. Posted by Ashish on October 01, 2009 at 09:05 AM CEST # Maps are absolutely wonderful. They are of course the mainstay of every "associated array" based scripting language (perl, js, php). They are also, fundamentally, evil. (Hey, if they were not, we would all be using those languages full time and we would not bother with the hassle of typed languages like C++ or Java, right?) Developers writing raw code with maps just don't have any meta-data to know what is allowable in the map: there isn't any. This is a problem. This problem of 'the intent' is why Java has classes and strong types. It gives developers some meta-data to explain the allowable/intended content of any given object. If you have a team with a dozen guys and you use maps then within a month someone will start stuffing some random state into the map to pass around as 'convenience'. By 'convenience' read: "could not be bothered to refactor the code so since we are passing maps I can use them as a trojan horse to pass some information around the layers of the system without refactoring the formal API fix the problem I am solving". To catch such crap with peer code review you are going to have to read all the code anyone else writes on the system - that scales about as well as writing it all yourself. Client code which doesn't know Java (JSON JavaScript or Flash) is a tiny excuse to downgrade serverside J2EE by the use of Maps; and only as boundary 'outbound/inbound' data transfer objects. If you just downgrade to speak to a type unsafe client then by all means do so, just don't call it anything other than a tactical impedance mis-match solution. Anyone looking to use maps to solve an OO or ORM problem is basically saying "I have found a corner case which is hard to do with OO - so lets not use OO". That's fine for Hibernate dynamic map mode. And fine for ZK framework code that creates CRUD table editing screens on the fly by looking at meta-data of your database tables. Such framework code knows the meta-data of what keys are allowable to be set within any map for a given screen/table. They have a truly hard on-the-fly-problem where using types would require on the fly class generation. If your not solving a complex on-the-fly problem and don't have a proper solution to manage the meta-data of your system then using maps is usually a bad idea. Posted by simbo1905 on October 20, 2009 at 04:17 AM CEST #
http://adambien.blog/roller/abien/entry/no_duplication_no_decoupling_the
CC-MAIN-2017-09
refinedweb
1,494
60.65
文章目录 - 1 First Steps to Scala - 2 Step 1. Download and install Scala - 3 Step 2. Learn to use the Scala interpreter - 4 Step 3. Define some variables - 5 Step 4. Define some methods - 6 Step 5. Write some Scala scripts - 7 Step 6. Loop with while, decide with if - 8 Step 7. Iterate with foreach and for - 9 Step 8. Parameterize Arrays with types - 10 Step 9. Use Lists and Tuples - 11 Step 10. Use Sets and Maps - 12 Step 11. Understand classes and singleton objects - 13 Step 12. Understand traits and mixins - 14 Conclusion - 15 Share your opinion - 16 End notes - 17 Resources First Steps to Scala by Bill Venners, Martin Odersky, and Lex Spoon May 9, 2007 In this article, you'll follow twelve steps that are designed to help you understand and gain some basic skills in the Scala programming language. Scala is a statically typed, object-oriented programming language that blends imperative and functional programming styles. Scala is designed to integrate easily with applications that run on modern virtual machines, primarily the Java virtual machine (JVM). The main Scala compiler, scalac, generates Java class files that can be run on the JVM. However, another Scala compiler exists that generates binaries that can be run on the .NET CLR, as Scala is designed to integrate with both the Java and .NET worlds. In the Java world, the Scala language can be used alongside the Java language—either as an alternative to Java—to build applications that run on the JVM. Scala was developed starting in 2003 by Martin Odersky's group at EPFL, Lausanne, Switzerland. Previously, Martin had been active in the Java field. He co-designed the first version of Java generics and was the original author of the current javac compiler. The work on Scala was motivated by the desire to overcome limitations imposed by backwards compatibility with Java. So Scala is not a superset of Java, but it retains seamless interoperability. One reason you might want to use Scala is that it allows you to increase your productivity compared to Java while leveraging JVM execution speed, your existing investments in Java code, knowledge, and the vast array of APIs available for the JVM. It has the conciseness of a dynamic language like Ruby or Python, but it is statically typed, like Java. Another reason is that Scala comes with an Erlang-like Actors library that greatly simplifies concurrent programming, but runs on the JVM. In Italian, Scala means staircase. In this article, we'll take you up twelve steps that will help you start becoming skilled in Scala. The best way to make use of this article is to try each example out with the Scala interpeter or compiler. Step 1 explains how to download and install the Scala distribution. Step 1. Download and install Scala To run the examples in this article, you should download Scala from the Scala Downloads page. The examples in this article were run with Scala version 2.5.0-RC1, so make sure you download a version at least as recent as 2.5.0-RC1. Once you download an archive file, create a directory wherever you prefer (perhaps named scala), and unzip (or untar, etc.) the archive file in that empty directory. Among the subdirectories created will be the bin directory that contains the Scala executables, including the compiler and interpeter. To make Scala convenient to use, add the full pathname of the bin directory to your PATH environment variable. The only other requirement you'll need to fulfill is an installation of Java 1.4 or above, which you can download from. You can also use Scala via plug-ins for Eclipse and IntelliJ, but for the steps in this article, we'll assume you're using the Scala distribution from scala-lang.org. Step 2. Learn to use the Scala interpreter The easiest way to get started with Scala is by using the Scala interpreter, which is an interactive “shell” for writing Scala expressions and programs. Simply type an expression into the interpreter and it will evaluate the expression and print the resulting value. The interactive shell for Scala is simply called scala. You use it like this: $ scala This is an interpreter for Scala. Type in expressions to have them evaluated. Type :help for more information. scala> After you type an expression, such as 1 + 2, and hit return: scala> 1 + 2 The interpreter will print: unnamed0: Int = 3 This line includes: - an automatically assigned or user-defined name to refer to the computed value ( unnamed0) - a colon ( :) - the type of the expression and its resulting value ( Int) - an equals sign ( =) - the value resulting from evaluating the expression ( 3) The type Int names the class Int in the package scala. Values of this class are implemented just like Java's int values. In fact, Scala treats int as an alias for scala.Int. More generally, all of Java's primitive types are defined as aliases for classes in the scala package. For example, if you type boolean in a Scala program, the type you'll actually get is scala.Boolean. Or if you type float, you'll get scala.Float. When you compile your Scala code to Java bytecodes, however, Scala will compile these types to Java's primitive types where possible to get the performance benefits of Java's primitive types. The unnamedX identifier may be used in later lines. For instance, since unnamed0 was set to 3 previously, unnamed0 * 3 will be 9: scala> unnamed0 * 3 unnamed1: Int = 9 To print the necessary, but not sufficient, Hello, world! greeting, type: scala> println("Hello, world!") Hello, world! unnamed2: Unit = () The type of the result here is scala.Unit, which is Scala's analogue to void in Java. The main difference between Scala's Unit and Java's void is that Scala lets you write down a value of type Unit, namely (), whereas in Java there is no value of type void. (In other words, just as 1, 2, and 3, are potential values of type int in both Scala and Java, () is the one and only value of type Unit in Scala. By contrast, there are no values of type void in Java.) Except for this, Unitand void are equivalent. In particular, every void-returning method in Java is mapped to a Unit-returning method in Scala. Step 3. Define some variables Scala differentiates between vals, variables that are assigned once and never change, and vars, variables that may change over their lifetime. Here's a val definition: scala> val msg = "Hello, world!" msg: java.lang.String = Hello, world! This introduces msg as a name for the value "Hello world!". The type of the value above is java.lang.String, because Scala strings are also Java strings. (In fact every Java class is available in Scala.) This example also points out an important and very useful feature of Scala: type inference. Notice that you never said the word java.lang.String or even String in the val definition. The Scala interpreter inferred the val's type to be the type of its initialization assignment. Since msg was initialized to "Hello, world!", and since "Hello, world!" is type java.lang.String, the compiler gave msg the type java.lang.String. When the Scala interpreter (or compiler) can infer a type, it is usually best to let it do so rather than fill the code with unnecessary, explicit type annotations. You can, however, specify a type explicitly if you wish. (For example, you may wish to explicitly specify the types of public members of classes for documentation purposes.) In contrast to Java, where you specify a variable&8217;s type before its name, in Scala you specify a variable's type after its name, separated by a colon. For example: scala> val msg2: java.lang.String = "Hello again, world!" msg2: java.lang.String = Hello, world! Or, since java.lang types are visible with their simple names in Scala programs, simply: scala> val msg3: String = "Hello yet again, world!" msg3: String = Hello yet again, world! Going back to our original msg, now that it is defined, you can then use the msg value as you'd expect, as in: scala> println(msg) Hello, world! unnamed3: Unit = () What you can't do with msg, given that it is a val not a var, is reassign it. For example, see how the interpreter complains when you attempt the following: scala> msg = "Goodbye cruel world!" <console>:5 error: assignment to non-variable val unnamed4 = {msg = "Goodbye cruel world!";msg} If reassignment is what you want, you'll need to use a var, as in: scala> var greeting = "Hello, world!" greeting: java.lang.String = Hello, world! Since greeting is a variable (defined with var) not a value (defined with val), you can reassign it later. If you are feeling grouchy later, for example, you could change your greeting to: scala> greeting = "Leave me alone, world!" greeting: java.lang.String = Leave me alone, world! Step 4. Define some methods Now that you've worked with Scala variables, you'll probably want to write some methods. Here's how you do that in Scala: scala> def max(x: Int, y: Int): Int = if (x < y) y else x max: (Int,Int)Int Method definitions start with def instead of val or var. The method's name, in this case max, is followed by a list of parameters in parentheses. A type annotation must follow every method parameter, preceded by a colon in the Scala way, because the Scala compiler (and interpreter, but from now on we'll just say compiler) does not infer method parameter types. In this example, the method named max takes two parameters, x and y, both of type Int. After the close parenthesis of max's parameter list you'll find another “ : Int” type specifier. This one defines the result type of the max method itself. Sometimes the Scala compiler will require you to specify the result type of a method. If the method is recursive1, for example, you must explicitly specify the method result type. In the case of max however, you may leave the result type specifier off and the compiler will infer it. Thus, the max method could have been written: scala> def max2(x: Int, y: Int) = if (x < y) y else x max2: (Int,Int)Int Note that you must always explicitly specify a method's parameter types regardless of whether you explicitly specify its result type. The name, parameters list, and result type, if specified, form a method's signature. After the method's signature you must put an equals sign and then the body of the method. Since max's body consists of just one statement, you need not place it inside curly braces, but you can if you want. So you could also have written: scala> def max3(x: Int, y: Int) = { if (x < y) y else x } max3: (Int,Int)Int If you want to put more than one statement in the body of a method, you must enclose them inside curly braces. Once you have defined a method, you can call it by name, as in: scala> max(3, 5) unnamed6: Int = 5 Note that if a method takes no parameters, as in: scala> def greet() = println("Hello, world!") greet: ()Unit You can call it with or without parentheses: scala> greet() Hello, world! unnamed7: Unit = () scala> greet Hello, world! unnamed8: Unit = () The recommended style guideline for such method invocations is that if the method may have side effects4, you should provide the parentheses even if the compiler doesn't require them. Thus in this case, since the greet method prints to the standard output, it has side effects and you should invoke it with parentheses to alert programmers looking at the code. Step 5. Write some Scala scripts Although Scala is designed to help developers build large systems, it also scales down nicely such that it feels natural to write scripts in it. A script is just a sequence of statements in a file that will be executed sequentially. (By the way, if you're still running the scala interpreter, you can exit it by entering the :quit command.) Put this into a file named hello.scala: println("Hello, world, from a script!") then run: >scala hello.scala And you should get yet another greeting: Hello, world, from a script! Command line arguments to a Scala script are available via a Scala array named args. In Scala, arrays are zero based, as in Java, but you access an element by specifying an index in parentheses rather than square brackets. So the first element in a Scala array named steps is steps(0), not steps[0]. To try this out, type the following into a new file named helloarg.scala: // Say hello to the first argument println("Hello, " + args(0) + "!") then run: >scala helloarg.scala planet In this command, "planet" is passed as a command line argument, which is accessed in the script as args(0). Thus, you should see: Hello, planet! Note also that this script included a comment. As with Java, the Scala compiler will ignore characters between // and the next end of line, as well as any characters between /* and */. This example also shows strings being concatenated with the + operator. This works as you'd expect. The expression "Hello, " + "world!" will result in the string "Hello, world!". By the way, if Which should yield: Hello, globe! Step 6. Loop with while, decide with if You write while loops in Scala in much the same way you do in Java. Try out a while by typing the following into a file name printargs.scala: var i = 0 while (i < args.length) { println(args(i)) i += 1 }, similar to the way you get the length of an array in Java.: Scala is fun For even more fun, type the following code into a new file named echoargs.scala: var i = 0 while (i < args.length) { if (i != 0) print(" ") print(args(i)) i += 1 } println() In this version, you've replaced the println call with many of them, Scala does use semi-colons to separate statements as in Java, except that in Scala the semi-colons are very often optional, giving some welcome relief to your right pinky finger. If you had been in a more verbose mood, therefore, you could have written the echoargs.scala script as follows: var i = 0; while (i < args.length) { if (i != 0) { print(" "); } print(args(i)); i += 1; } println(); If you type the previous code into a new file named echoargsverbosely.scala, and run it with the command: > scala echoargsverbosely.scala In Scala semicolons are often optional You should see the output: In Scala semicolons are often optional Note that because you had no parameters to pass to the println method, you could have left off the parentheses and the compiler would have been perfectly happy. But given the style guideline that you should always use parentheses when calling methods that may have side effects—coupled with the fact that by printing to the standard output, println will indeed have side effects—you specified the parentheses even in the concise echoargs.scala version. One of the benefits of Scala that you can begin to see with these examples, is that Scala gives you the conciseness of a scripting language such as Ruby or Python, but without requiring you to give up the static type checking of more verbose languages like Java or C++. Scala's conciseness comes not only from its ability to infer both types and semicolons, but also its support for the functional programming style, which is discussed in the next step. Step 7. Iterate with foreach and for Although you may not have realized it, when you wrote the while loops in the previous step, you were programming in an imperative style. In the imperative style, which is the style you would ordinarily use with languages like Java, C++, and C, you give one imperative command at a time, iterate with loops, and often mutate state shared between different functions or methods. Scala enables you to program imperatively, but as you get to know Scala better, you'll likely often find yourself programming in a more functional style. In fact, one of the main aims of the Scalazine will be to help you become as competent at functional programming as you are at imperative programming, using Scala as a an anonymous function (one with no name), which takes one parameter named arg. The code of the anonymous function is println(arg). If you type the above code into a new file named pa.scala, and execute with the command: scala pa.scala Concise is nice You should see: Concise is nice In the previous example, the Scala interpreter infers type of arg to be String, since Strings are what the array on which you're calling foreach is holding. If you'd prefer to be more explicit, you can mention the type name, but when you do you'll need to wrap the argument portion in parentheses (which is the normal form of the syntax anyway). Try typing this into a file named epa.scala. args.foreach((arg: String) => println(arg)) Running this script has the same behavior as the previous one. With the command: scala epa.scala Explicit can be nice too You'll get: Explicit can be nice too If instead of an explicit mood, you're in the mood for even more conciseness, you can take advantage of a special case in Scala. If an anonymous function consists of one method application that takes a single argument, you need not explicitly name and specify the argument. Thus, the following code also works: args.foreach(println) To summarize, the syntax for an anonymous function is a list of named parameters, in parentheses, a right arrow, and then the body of the function. This syntax is illustrated in Figure 1. Figure 1. The syntax of a Scala anonymous function. Now, by this point you may be wondering what happened to those trusty for loops you have been accustomed to using in imperative languages such as Java. In an effort to guide you in a functional direction, only a functional relative of the imperative for (called a for comprehension) is available in Scala. While you won't see their full power and expressiveness in this article, we will give you a glimpse. In a new file named forprintargs.scala, type the following: for (arg <- args) println(arg) The parentheses after the for in this for comprehension contain arg <- args. To the left of the <- symbol, which you can say as “in”, is a declaration of a new \@val@ (not a \@var@) named arg. To the right of <- is the familiar argsarray. When this code executes, arg will be assigned to each element of the args array and the body of the for, println(arg), will be executed. Scala's for comprehensions can do much more than this, but this simple form is similar in functionality to Java 5's: // ... for (String arg : args) { // Remember, this is Java, not Scala System.out.println(arg); } // ... or Ruby's for arg in ARGV # Remember, this is Ruby, not Scala puts arg end When you run the forprintargs.scala script with the command: scala forprintargs.scala for is functional You should see: for is functional Step 8. Parameterize Arrays with types In addition to being functional, Scala is object-oriented. In Scala, as in Java, you define a blueprint for objects with classes. From a class blueprint, you can instantiate objects, or class instances, by using new. For example, the following Scala code instantiates a new String and prints it out: val s = new String("Hello, world!") println(s) In the previous example, you parameterize the String instance with the initial value "Hello, world!". You can think of parameterization as meaning configuring an instance at the point in your program that you create that instance. You configure an instance with values by passing objects to a constructor of the instance in parentheses, just like you do when you create an instance in Java. If you place the previous code in a new file named paramwithvalues.scala and run it with scala paramswithvalues.scala, you'll see the familiar Hello, world! greeting printed out. In addition to parameterizing instances with values at the point of instantiation, you can in Scala also parameterize them with types. This kind of parameterization is akin to specifying a type in angle brackets when instantiating a generic type in Java 5 and beyond. The main difference is that instead of the angle brackets used for this purpose in Java, in Scala you use square brackets. Here's an example: val greetStrings = new Array[String](3) greetStrings(0) = "Hello" greetStrings(1) = ", " greetStrings(2) = "world!\n" for (i <- 0 to 2) print(greetStrings(i)) In this example, greetStrings is a value of type Array[String] (say this as, “an array of string”) that is initialized to length 3 by passing the value 3 to a constructor in parentheses in the first line of code. Type this code into a new file called paramwithtypes.scala and execute it with scala paramwithtypes.scala, and you'll see yet another Hello, world! greeting. Note that when you parameterize an instance with both a type and a value, the type comes first in its square brackets, followed by the value in parentheses. Had you been in a more explicit mood, you could have specified the type of greetStrings explicitly like this: val greetStrings: Array[String] = new Array[String](3) // ... Given Scala's type inference, this line of code is semantically equivalent to the actual first line of code in paramwithtypes.scala. But this form demonstrates that while the type parameterization portion (the type names in square brackets) form part of the type of the instance, the value parameterization part (the values in parentheses) do not. The type of greetStrings is Array[String], not Array[String](3). The next three lines of code in paramwithtypes.scala initializes each element of the greetStrings array: // ... greetStrings(0) = "Hello" greetStrings(1) = ", " greetStrings(2) = "world!\n" // ... As mentioned previously, arrays in Scala are accessed by placing the index inside parentheses, not square brackets as in Java. Thus the zeroeth element of the array is greetStrings(0), not greetStrings[0] as in Java. These three lines of code illustrate an important concept to understand about Scala concerning the meaning of val. When you define a variable with val, the variable can't be reassigned, but the object to which it refers could potentially still be mutated. paramwithtypes.scala contain a for comprehension that prints out each greetStrings array element in turn. // ... for (i <- 0 to 2) print(greetStrings(i)) The first line of code in this for comprehension illustrates another general rule of Scala: if a method takes only one parameter, you can call it without a dot or parentheses. to is actually a method that takes one Int argument. The code 0 to 2 is transformed into the method call 0.to(2). (This to method actually returns not an Array but a Scala iterator that returns the values 0, 1, and 2.) Scala doesn't technically have operator overloading, because it doesn't actually have operators in the traditional sense. Characters such as +, -, *, and /, have no special meaning in Scala, but they can be used in method names. Thus, the expression 1 + 2, which was the first Scala code you typed into the interpreter in Step 1, is essential in meaning to 1.+(2), where + is the name of a method defined in class scala.Int. Another important idea illustrated by this example will give you insight into why arrays are accessed with parentheses in Scala. Scala has fewer special cases than Java. Arrays are simply instances of classes like any other class in Scala. When you apply parentheses to a variable and pass in some arguments, Scala will transform that into an invocation of a method named apply. So greetStrings(i) gets transformed into greetStrings.apply(i). Thus accessing the element of an array in Scala is simply a method call like any other method call. What's more, the compiler will transform any application of parentheses with some arguments on any type into an apply method call, not just arrays. Of course it will compile only if that type actually defines an apply method. So it's not a special case; it's a general rule. Similarly, when an assignment is made to a variable that is followed by some arguments in parentheses, the compiler will transform that into an invocation of an update method that takes two parameters. For example, greetStrings(0) = "Hello" will essentially be transformed into greetStrings.update(0, "Hello") Thus, the following Scala code is semantically equivalent to the code you typed into paramwithtypes.scala: as the programmer don't have to remember lots of special cases, such as the differences in Java between primitive and their corresponding wrapper types, or between arrays and regular objects. However, it is significant to note that in Scala this uniformity does not usually come with a performance cost as it often has in other languages that have aimed to be pure in their object orientation. The Scala compiler uses Java arrays, primitive types, and native arithmetic where possible in the compiled code. Thus Scala really does give you the best of both worlds in this sense: the conceptual simplicity of a pure object-oriented language with the runtime performance characteristics of language that has special cases for performance reasons. Step 9. Use Lists and Tuples One of the big ideas of the functional style of programming is that methods should not have side effects. The only effect of a method should be to compute the value or values that are returned by the method. Some benefits gained when you take this approach are that methods become less entangled, and therefore more reliable and reusable. Another benefit of the functional style in a statically typed language is that everything that goes into and out of a method is checked by a type checker, so logic errors are more likely to manifest themselves as type errors. To apply this functional philosophy to the world of objects, you would make objects immutable. A simple example of an immutable object in Java is String. If you create a String with the value "Hello, ", it will keep that value for the rest of its lifetime. If you later call concat("world!") on that String, it will not add "world!" to itself. Instead, it will create and return a brand new String with the value Hello, world!".. An immutable, and therefore more functional-oriented, sequence of objects that share the same type is Scala's List. As with Arrays, a List[String] contains only Strings. Scala's List, scala.List, differs from Java's java.util.List type in that Scala Lists are always immutable (whereas Java Lists can be mutable). But more importantly, Scala's List is designed to enable a functional style of programming. Creating a List is easy, you just say: val oneTwoThree = List(1, 2, 3) This establishes a new \@val@ named oneTwoThree, which initialized with a new List[Int] with the integer element values 1, 2 and 3. (You don't need to say new List because “ List” is defined as a factory method on the scala.Listsingleton object. More on Scala's singleton object construct in Step 11.) Because Lists are immutable, they behave a bit like Java Strings in that when you call a method on one that might seem by its name to imply the List will be mutated, it instead creates a new List with the new value and returns it. For example, List has a method named ::: that concatenates a passed List and the List on which ::: was invoked..") Type this code into a new file called listcat.scala and execute it with scala listcat.scala, and you should type the following code into a file named consit.scala: val twoThree = List(2, 3) val oneTwoThree = 1 :: twoThree println(oneTwoThree) And execute it with scala consit.scala, you should see: List(1, 2, 3) Given that a shorthand way to specify an empty List is Nil, one way to initialize new Lists is to string together elements with the cons operator, with Nil as the last element. For example, if you type the following code into a file named consinit.scala: val oneTwoThree = 1 :: 2 :: 3 :: Nil println(oneTwoThree) And execute it with scala consinit.scala, you should again see: List(1, 2, 3) Scala's List is packed with useful methods, many of which are shown in Table 1. Table 1. Some List methods and usages. List, one other ordered collection of object elements that's very useful in Scala is the tuple. Like Lists, tuples are immutable, but unlike Lists, tuples can contain different types of elements. Thus whereas a list might be a List[Int]or a List[String], a tuple could contain both an Intand a String. For example, type the following code into a file named luftballons.scala: val pair = (99, "Luftballons") println(pair._1) println(pair._2) In the first line of this code, you create a new tuple that contains an Int with the value 99 as its first element, and a String with the value with scala luftballons.scala, you'll see: 99 Luftballons The actual type of a tuple depends upon the number and of elements it contains and the types of those elements. Thus, the type of (99, "Luftballons") is Tuple2[Int, String]. The type of ('u', 'r', "the", 1, 4, "me") is Tuple6[Char, Char, String, Int, Int, String]. Step 10. Use Sets and Maps Step 12.) Scala then provides two subtraits, one for mutable Sets, and another for immutable Sets. As you can see in Figure 2, these three traits all share the same simple name, Set. Their fully qualified names differ, however, because they each reside in a different package. Concrete Set classes in the Scala API, such as the HashSet classes shown in Figure 2, extend either the mutable or immutable Set trait. (Although in Java you implement interfaces, in Scala you “extend” traits.) Thus, if you want to use a HashSet, you can choose between mutable and immutable varieties depending upon your needs. Figure 2. Class hierarchy for Scala Sets. To try out Scala Sets, type the following code into a file named jetset.scala: import scala.collection.mutable.HashSet val jetSet = new HashSet[String] jetSet += "Lear" jetSet += ("Boeing", "Airbus") println(jetSet.contains("Cessna")) The first line of jetSet.scala imports the mutable HashSet. As with Java, the import allows you to use the simple name of the class, HashSet, in this source file. After a blank line, the third line initializes jetSet with a new HashSet that will contain only Strings. Note that just as with Lists and Arrays, when you create a Set, you need to parameterize it with a type (in this case, String), since every object in a Set must share the same type. The subsequent two lines add three objects to the mutable Set via the += method. As with most other symbols you've seen that look like operators in Scala, += is actually a method defined on class HashSet. Had you wanted to, instead of writing jetSet += "Lear", you could have written jetSet.+=("Lear"). Because the += method takes a variable number of arguments, you can pass one or more objects at a time to it. For example, jetSet += "Lear" adds one String to the HashSet, but jetSet += ("Boeing", "Airbus") adds two Strings to the set. Finally, the last line prints out whether or not the Set contains a particular String. (As you'd expect, it prints false.) Another useful collection class in Scala is Maps. As with Sets, Scala provides mutable and immutable versions of Map, using a class hierarchy. As you can see in Figure. Figure 3. Class hierarchy for Scala Maps. Implementations of Map, such as the HashMaps shown in the class hierarchy in Figure 3, implement either the mutable or immutable trait. To see a Map in action, type the following code into a file named treasure.scala. // In treasure.scala import scala.collection.mutable.HashMap val treasureMap = new HashMap[Int, String] treasureMap += 1 -> "Go to island." treasureMap += 2 -> "Find big X on ground." treasureMap += 3 -> "Dig." println(treasureMap(2)) On the first line of treasure.scala, you import the mutable form of HashMap. After a blank line, you define a val named treasureMap and initialize it with a new mutable HashMap whose keys will be Ints and values Strings. On the next three lines you add key/value pairs to the HashMap using the -> method. As illustrated in previous examples, the Scala compiler transforms an binary operation expression like 1 -> "Go to island." into 1.->("Go to island."). Thus, when you say 1 -> "Go to island.", you are actually calling a method named -> on an Int with the value 1, and passing in a String with the value "Go to island." This -> method, which you can invoke on any object in a Scala program3, returns a two-element tuple containing the key and value. You then pass this tuple to the += method of the HashMap object to which treasureMap refers. Finally, the last line prints the value that corresponds to the key 2 in the treasureMap. If you run this code, it will print: Find big X on ground. Because maps are such a useful programming construct, Scala provides a factory method for Maps that is similar in spirit to the factory method shown in Step 9 that allows you to create Lists without using the new keyword. To try out this more concise way of constructing maps, type the following code into a file called numerals.scala: // In numerals.scala val romanNumeral = Map(1 -> "I", 2 -> "II", 3 -> "III", 4 -> "IV", 5 -> "V") println(romanNumeral(4)) In numerals.scala you take advantage of the fact that the the immutable Map trait is automatically imported into any Scala source file. Thus when you say Map in the first line of code, the Scala interpreter knows you mean scala.collection.immutable.Map. In this line, you call a factory method on the immutable Map's companion object5, passing in five key/value tuples as parameters. This factory method returns an instance of the immutable HashMapcontaining the passed key/value pairs. The name of the factory method is actually apply, but as mentioned in Step 8, if you say Map(...) it will be transformed by the compiler to Map.apply(...). If you run the numerals.scala script, it will print IV. Step 11. Understand classes and singleton objects Up to this point you've written Scala scripts to try out the concepts presented in this article. For all but the simplest projects, however, you will likely want to partition your application code into classes. To give this a try, type the following code into a file called greetSimply.scala: // In greetSimply.scala class SimpleGreeter { val greeting = "Hello, world!" def greet() = println(greeting) } val g = new SimpleGreeter g.greet() greetSimply.scala is actually a Scala script, but one that contains a class definition. This first, example, however, illustrates that as in Java, classes in Scala encapsulate fields and methods. Fields are defined with either val or var. Methods are defined with def. For example, in class SimpleGreeter, greeting is a field and greet is a method. To use the class, you initialize a val named g with a new instance of SimpleGreeter. You then invoke the greet instance method on g. If you run this script with scala greetSimply.scala, you will be dazzled with yet another Hello, world!. Although classes in Scala are in many ways similar to Java, in several ways they are quite different. One difference between Java and Scala involves constructors.. To see this in action, type the following code into a file named greetFancily.scala: // In greetFancily.scala class FancyGreeter(greeting: String) { def greet() = println(greeting) } val g = new FancyGreeter("Salutations, world") g.greet Instead of defining a constructor that takes a String, as you would do in Java, in greetFancily.scala you placed the greeting parameter of that constructor in parentheses placed directly after the name of the class itself, before the open curly brace of the body of class FancyGreeter. When defined in this way, greeting essentially becomes a value (not a variable—it can't be reassigned) field that's available anywhere inside the body. In fact, you pass it to println in the body of the greet method. If you run this script with the command scala greetFancily.scala, it will inspire you with: Salutations, world! This is cool and concise, but what if you wanted to check the String passed to FancyGreeter's primary constructor for null, and throw NullPointerException to abort the construction of the new instance? Fortunately, you can. Any code sitting inside the curly braces surrounding the class definition, but which isn't part of a method definition, is compiled into the body of the primary constructor. In essence, the primary constructor will first initialize what is essentially a final field for each parameter in parentheses following the class name. It will then execute any top-level code contained in the class's body. For example, to check a passed parameter for null, type in the following code into a file named greetCarefully.scala: // In greetCarefully.scala class CarefulGreeter(greeting: String) { if (greeting == null) { throw new NullPointerException("greeting was null") } def greet() = println(greeting) } new CarefulGreeter(null) In greetCarefully.scala, an if statement is sitting smack in the middle of the class body, something that wouldn't compile in Java. The Scala compiler places this if statement into the body of the primary constructor, just after code that initializes what is essentially a final field named greeting with the passed value. Thus, if you pass in null to the primary constructor, as you do in the last line of the greetCarefully.scala script, the primary constructor will first initialize the greeting field to null. Then, it will execute the if statement that checks whether the greeting field is equal to null, and since it is, it will throw a NullPointerException. If you run greetCarefully.scala, you will see a NullPointerException stack trace. In Java, you sometimes give classes multiple constructors with overloaded parameter lists. You can do that in Scala as well, however you must pick one of them to be the primary constructor, and place those constructor parameters directly after the class name. You then place any additional auxiliary constructors in the body of the class as methods named this. To try this out, type the following code into a file named greetRepeatedly.scala: // In greetRepeatedly.scala class RepeatGreeter(greeting: String, count: Int) { def this(greeting: String) = this(greeting, 1) def greet() = { for (i <- 1 to count) println(greeting) } } val g1 = new RepeatGreeter("Hello, world", 3) g1.greet() val g2 = new RepeatGreeter("Hi there!") g2.greet() RepeatGreeter's primary constructor takes not only a String greeting parameter, but also an Int count of the number of times to print the greeting. However, RepeatGreeter also contains a definition of an auxiliary constructor, the this method that takes a single String greeting parameter. The body of this constructor consists of a single statement: an invocation of the primary constructor parameterized with the passed greeting and a count of 1. In the final four lines of the greetRepeatedly.scala script, you create two RepeatGreeters instances, one using each constructor, and call greet on each. If you run greetRepeatedly.scala, it will print: Hello, world Hello, world Hello, world Hi there! Another area in which Scala departs from Java is that you can't have any static fields or methods in a Scala class. Instead, Scala allows you to create singleton objects using the keyword object. A singleton object cannot, and need not, be instantiated with new. It is essentially automatically instantiated the first time it is used, and as the “singleton” in its name implies, there is ever only one instance. A singleton object can share the same name with a class, and when it does, the singleton is called the class's companion object. The Scala compiler transforms the fields and methods of a singleton object to static fields and methods of the resulting binary Java class. To give this a try, type the following code into a file named WorldlyGreeter.scala: // In WorldlyGreeter.scala // The WorldlyGreeter class class WorldlyGreeter(greeting: String) { def greet() = { val worldlyGreeting = WorldlyGreeter.worldify(greeting) println(worldlyGreeting) } } // The WorldlyGreeter companion object object WorldlyGreeter { def worldify(s: String) = s + ", world!" } In this file, you define both a class, with the class keyword, and a companion object, with the object keyword. Both types are named WorldlyGreeter. One way to think about this if you are coming from a Java programming perspective is that any static methods that you would have placed in class WorldlyGreeter in Java, you'd put in singleton object WorldlyGreeter in Scala. In fact, when the Scala compiler generates bytecodes for this file, it will create a Java class named WorldlyGreeter that has an instance method named greet (defined in the WorldlyGreeter class in the Scala source) and a static method named worldify (defined in the WorldlyGreeter companion object in Scala source). Note also that in the first line of the greet method in class WorldlyGreeter, you invoke the singleton object's worldify method using a syntax similar to the way you invoke static methods in Java: the singleton object name, a dot, and the method name: // Invoking a method on a singleton object from class WorldlyGreeter // ... val worldlyGreeting = WorldlyGreeter.worldify(greeting) // ... To run this code, you'll need to create an application. Type the following code into a file named WorldlyApp.scala: // In WorldlyApp.scala // A singleton object with a main method that allows // this singleton object to be run as an application object WorldlyApp { def main(args: Array[String]) { val wg = new WorldlyGreeter("Hello") wg.greet() } } Because there's no class named WorldlyApp, this singleton object is not a companion object. It is instead called a stand-alone. object. Thus, a singleton object is either a companion or a stand-alone object. The distinction is important because companion objects get a few special privileges, such as access to private members of the like-named class., WorldlyGreeter.scala and WorldlyApp.scala. Neither WorldlyGreeter.scala nor WorldlyApp.scala are scripts, because they end in a definition. A script, by contrast, must end in a result expression. Thus if you try to run either of these files as a script, for example by typing: scala WorldlyGreeter.scala # This won't work! The Scala interpreter will complain that WorldlyGreeter.scala does not end in a result expression. Instead, you'll need to actually compile these files with the Scala compiler, then run the resulting class files. One way to do this is to use scalac, which is the basic Scala compiler. Simply type: scalac WorldlyApp.scala WorldlyGreeter.scala Given that the scalac compiler starts up a new JVM instance each time it is invoked, and that the JVM often has a perceptible start-up delay, the Scala distribution also includes a Scala compiler daemon called fsc (for fast Scala compiler). You use it like this: fsc WorldlyApp.scala WorldlyGreeter.scala The the JVM6 as you did in every previous example, in this case you'll give it the name of a class containing a main method. Similar to Java, any Scala class with a main method that takes a single parameter of type Array[String] and returns Unit7 can serve as the entry point to an application. In this example, WorldlyApp has a main method with the proper signature, so you can run this example by typing: scala WorldlyApp At which point you should see: Hello, world! You may recall seeing this output previously, but this time it was generated in this interesting manner: - The scalaprogram fires up a JVM with the WorldlyApp's mainmethod as the entry point. WordlyApp's mainmethod creates a new WordlyGreeterinstance via new, passing in the string "Hello"as a parameter. - Class WorldlyGreeter's primary constructor essentially initializes a final field named greetingwith the passed value, "Hello"(this initialization code is automatically generated by the Scala compiler). WordlyApp's mainmethod initializes a local \@val@ named wgwith the new WorldlyGreeterinstance. WordlyApp's mainmethod then invokes greeton the WorldlyGreeterinstance to which wgrefers. - Class WordlyGreeter's greetmethod invokes worldifyon singleton object WorldlyGreeter, passing along the value of the final field greeting, "Hello". - Companion object WorldlyGreeter's worldifymethod returns a Stringconsisting of the value of a concatenation of the sparameter, which is "Hello", and the literal String ", world!". - Class WorldlyGreeter's greetmethod then initializes a \@val@ named worldlyGreetingwithplaces the "Hello, world!" Stringreturned from the worldifymethod. - Class WorldlyGreeter's greetmethod passes the "Hello, world!" Stringto which worldlyGreetingrefers to println, which sends the cheerful greeting, via the standard output stream, to you. Step 12. Understand traits and mixins As first mentioned in Step 10, Scala includes a construct called a trait, which is similar in spirit to Java's interface. One main difference between Java interfaces and Scala's traits are that whereas all methods in Java interfaces are by definition abstract, you can give methods real bodies with real code in Scala traits. Here's an example: trait Friendly { def greet() = "Hi" } In this example, the greet method returns the String "Hi". If you are coming from Java, this greet method may look a little funny to you, as if greet() is somehow a field being initialized to the String value "Hi". What is actually going on is that lacking an explicit return statement, Scala methods will return the value of the last expression. In this case, the value of the last expression is "Hi", so that is returned. A more verbose way to say the same thing would be: trait Friendly { def greet(): String = { return "Hi" } } Regardless of how your write the methods, however, the key point is that Scala traits can actually contain non-abstract methods. Another difference between Java interfaces and Scala traits is that whereas you implement Java interfaces, you extend Scala traits. Other than this implements/ extends difference, however, inheritance when you are defining a new type works in Scala similarly to Java. In both Java and Scala, a class can extend one (and only one) other class. In Java, an interface can extend zero to many interfaces. Similarly in Scala, a trait can extend zero to many traits. In Java, a class can implement zero to many interfaces. Similarly in Scala, a class can extend zero to many traits. implements is not a keyword in Scala. Here's an example: class Dog extends Friendly { override def greet() = "Woof" } In this example, class Dog extends trait Friendly. This inheritance relationship implies much the same thing as interface implementation does in Java. You can assign a Dog instance to a variable of type Friendly. For example: var pet: Friendly = new Dog println(pet.greet()) When you invoke the greet method on the Friendly pet variable, it will use dynamic binding, as in Java, to determine which implementation of the method to call. In this case, class Dog overrides the greet method, so Dog's implementation of greet will be invoked. Were you to execute the above code, you would get Woof ( Dog's implementation of greet), not Hi ( Friendly's implementation of greet). Note that one difference with Java is that to override a method in Scala, you must precede the method's def with override. If you attempt to override a method without specifying override, your Scala code won't compile. Finally, one quite significant difference between Java's interfaces and Scala's traits is that in Scala, you can mix in traits at instantiation time. For example, consider the following trait: trait ExclamatoryGreeter extends Friendly { override def greet() = super.greet() + "!" } Trait ExclamatoryGreeter extends trait Friendly and overrides the greet method. ExclamatoryGreeter's greet method first invokes the superclass's greet method, appends an exclamation point to whatever the superclass’s greet method returns, and returns the resulting String. With this trait, you can mix in its behavior at instantiation time using the with keyword. Here's an example: val pup: Friendly = new Dog with ExclamatoryGreeter println(pup.greet()) Given the initial line of code, the Scala compiler will create a synthetic8 type that extends class Dog and trait ExclamatoryGreeter and instantiate it. When you invoke a method on the synthetic type, it will cause the correct implementation to be invoked. When you run this code, the pup variable will first be initialized with the new instance of the synthetic type, then when greet is invoked on pup, you'll see "Woof!". Note that had pup not been explicitly defined to be of type Friendly, the Scala compiler would have inferred the type of pup to be Dog with ExclamatoryGreeter. To give all these concepts a try, type the following code into a file named friendly.scala: trait Friendly { def greet() = "Hi" } class Dog extends Friendly { override def greet() = "Woof" } class HungryCat extends Friendly { override def greet() = "Meow" } class HungryDog extends Dog { override def greet() = "I'd like to eat my own dog food" } trait ExclamatoryGreeter extends Friendly { override def greet() = super.greet() + "!" } var pet: Friendly = new Dog println(pet.greet()) pet = new HungryCat println(pet.greet()) pet = new HungryDog println(pet.greet()) pet = new Dog with ExclamatoryGreeter println(pet.greet()) pet = new HungryCat with ExclamatoryGreeter println(pet.greet()) pet = new HungryDog with ExclamatoryGreeter println(pet.greet()) When you run the friendly.scala script, it will print: Woof Meow I'd like to eat my own dog food Woof! Meow! I'd like to eat my own dog food! Conclusion As you may have glimpsed by reading this article, the promise of Scala is that you can get more productivity while leveraging existing investments. Scala's basic conciseness of syntax and support for the functional programming style promise increased programmer productivity compared to the Java langauge, while enabling you to continue to take advantage of all the great things about the Java platform. You can complement Java code with Scala code and continue to leverage your existing Java code and APIs, the many APIs available for the Java platform, the runtime performance offered by JVMs, and your own knowledge of the Java platform. With the knowledge you've gained in this article, you should already be able to get started using Scala for small tasks, especially scripts. In future articles, we will dive into more detail in these topics, and introduce other topics that weren't even hinted at here. Have a question or opinion about Scala? Discuss this article in the Articles Forum topic, First Steps to Scala. End notes 1. A method is recursive if it calls itself. 2. Actually, the very attentive reader may have noticed something amiss with the associativity of the ::: method, but it is actually a simple rule to remember. If a method is used as an operator, as in a * b or a ::: b, the method is invoked on the left hand operand, as in a.*(b), unless the method name ends in a colon. If the method name ends in a colon, then the method is invoked on the right hand operand, as in b.:::(a). 3. The Scala mechanism that allows you to invoke -> on any object is called implicit conversion, which will be covered in a future article. 4. A method has side effects if it changes state outside the method. 5. Companion objects will be covered in Step 11. 6. The actual mechanism that the scala program uses to “interpret” a Scala source file is that it compiles the Scala source code to bytecodes in memory, loads them immediately via a class loader, and executes them. 7. As mentioned in Step 2, Unit in Scala is similar to void in Java. Whereas in Java, a main method must return void, in Scala, it must return Unit. 8. A synthetic type is generated automatically by the compiler rather than being written by hand by the programmer. Resources The Scala programming language home page is at: The Scala mailing list: The Scala wiki: A Scala plug-in for Eclipse: A Scala plug-in for IntelliJ: The lift Web Framework runs inside a Java web container and uses Scala for coding:. Martin Odersky is the creator of the Scala language. As a professor at EPFL in Lausanne, Switzerland he is working. Lex Spoon divides his time between working at EPFL in Switzerland and at IBM Research in New York State. He holds a Ph.D. from Georgia Tech. He is interested in programming language design and implementation, with special focus on packaging, pluggable types, and static analysis for optimization, safe software evolution, and verification of domain-specific properties.
http://www.jmzhang.top/wordpress/stories/
CC-MAIN-2021-31
refinedweb
8,857
63.39
Farewell To the Floppy Disk 616." Windows installer requires them (Score:5, Informative) (I bring this up because I had to install a floppy on a computer I was reinstalling XP on the other day so I could use the SATA drive! I kinda felt dirty after doing that!) Re:Windows installer requires them (Score:4, Insightful) Re:Windows installer requires them (Score:5, Insightful) Given the abundance of USB-Flash keys, I would hope that most modern PCs can be booted off USB devices. Re:Windows installer requires them (Score:5, Informative) Hint: format the USB key as a 1.2MB floppy. If you ask nice, I'll tell you how. If you ask naughty, go Google it yersef. I did. Took me most of an hour to figure it out, and most of a day to get it approved. Slick. Of course, WIN Server 2K/2K3 and the F6 floppy idea still rots, but it's NOT impossible. -rick Re: (Score:3, Informative) What I ended up doing was just partitio Re: (Score:3, Informative) Re:Windows installer requires them (Score:4, Funny) Re:So, XP and below are doomed by this. (Score:4, Funny) Re:Windows installer requires them (Score:4, Insightful) Re: (Score:3, Insightful) Re: (Score:3, Funny) Re: (Score:2) Re:Windows installer requires them (Score:5, Informative) Personally, I haven't had a floppy in any of my PCs for at least 5 years. For the odd time I needed a win98 boot floppy or such, then I have floppy images on several bootable DVDs (there's lots of them out there if you're too lazy to do it yourself or don't know how). However, I still have an old floppy drive (and a trusty LS120) somewhere on a shelf, for the odd time it might come in handy (rescue data, reflash a BIOS from dos - although I prefer to do that from a hard disk as floppies are unreliable, and things like that). Re: (Score:2) Though if you want fun I do have a Magento Optical drive and a couple of disks floating around. It uses a SCSI interface so good luck. Re: (Score:2) Re: (Score:2) Re:Windows installer requires them (Score:5, Funny) Re: (Score:3, Informative) Re:Windows installer requires them (Score:5, Funny) Ok, so do I invest in 2.5 gigs of memory, or do I use an unused teac and floppy. Mod storage medium down (Score:5, Funny) Re:Mod storage medium down (Score:4, Funny) (-1, Insertful) Hey I still have punch cards! (Score:5, Interesting) I well remember moving to 8 inch, then 5.25 inch floppies. My wife made me a few shirts with extra big pockets which could take a couple of 5.25s. Even with all these fond memories, I prefer CD. Re:Hey I still have punch cards! (Score:5, Interesting) Writing and running a program consisted of: 1. Typing out your source code, one line of code per card. 2. Getting the 'compiler/assembler' program card deck out of storage. 3. Reading the 'compiler/assembler' deck into the computer and starting it running. 4. Loading your source code deck as data cards. 5. The compiler/assembler would churn away and then punch out your object card deck. 6. Move the object card deck from the card punch 'out' bin to the card reader 'in' bin. 7. Load your 'object' card deck into the computer and start it running. For each pass, and each change to your program, the computer would have to punch out a new 'object' deck. There was no other intermediate storage available. I'm pretty sure I am remembering this right. Dad was a programmer a long, long time ago, and I only know this process from him telling it to me. Re: (Score:3, Informative) huh? (Score:2) Also, this is not news. Re: (Score:2) Personally, I remember the cases of them that I had for the various software that I used. Re: (Score:3, Funny) Sadly... Good! (Score:5, Informative) Since '95 the quality control on floppy disks has been so low that it hasn't been worth buying them anyway. At one time a SS/DD 5.25" could be used as a DS/DD reliably for five years or more without errors "just appearing". Maybe a patent ran out or QA began paying more attention to HD and CD manufacturing. Whatever it was, though, after '95 the floppy disks which I've bought have an average lifespan of about three months before random errors begin appearing on the media. Re:Sadly... Good! (Score:5, Funny) The !silver lining is that because of their poor reliability and the stress it's caused me, whenever I see floppies (or tapes) I throw them to the ground and stomp them to bits. Even if they're not mine. Floppy disk reliability (Score:5, Interesting) Floppy drives are rarely used and have outside air continuously drawn through them while the computer is on, collecting a significant amount of dust. When they're called into service again, the vibration of operation drops the dust and debris into the disk, and the full-contact readwrite head ensures that the dust is ground in nicely. Back in the days when floppy drives were used daily, there wasn't opportunity for this amount of dust to build up. One strategy to improve floppy disk reliability these days is to pop in a "sacrificial disk" and do a few operations on it before putting in the actual disk you want to read/write. Another alternative is to use a positive pressure case with an air filter on the intake. Re: (Score:3, Informative) I have 25+-year-old Commodore drives around here somewhere; I haven't looked at 'em in a decade, but I'll bet that they, too, have sacrificial disks in them at this very moment. The nice thing about my scheme is that whatever dust would fall to the bottom of the drive falls on the disk; you spin the disk every now and then, the dust gets trapped inside the disk; you pop the disk out, boom, the drive is already clean and ready to g Re:Sadly... Good! (Score:5, Funny) 1999 called.... (Score:2, Funny) The dawn of time called... (Score:4, Funny) BIOS Upgrades... (Score:5, Informative) Re: (Score:2) Re: (Score:2) Re: (Score:3, Interesting) Old Archives (Score:4, Interesting) I recently found an old 3.5" floppy with some useless, but nostalgic data on it. So, I dug through my box of spare 'parts' and found an old drive. As I went to install the drive in my desktop machine to pull the data off the floppy I realized an important fact: that box has no floppy controller. In that sense, the floppy has already been gone for some of us for awhile now. Floppy's are dying, not dead... (Score:2) Vista supports other media on that front, but even today, I see people buy the floppy option on even new PE2950 even if they support USB boot. Floppys are fairly gone from desktop, but even I had to install it for firmware updates to my desktop system. How proper is the way to honor? (Score:2) Today the clouds are dry, and the birds have deaf and mute. Re:How proper is the way to honor? (Score:4, Funny) the only thing that stores more with a hole in it. How is this new news? (Score:4, Informative) I think what should be news is that although everyone is retiring the floppy drive and sending all the disks to the bone yard, nobody has come up with an alternative way to flash device BIOS's. Companies for RAID, Network and other devices sometimes still only release a floppy self-writing image file. Re: (Score:3, Informative) Nobody? Nobody but me apparently. h0 h0 h0. Seriously though, everyone but you has already figured this out. It's a bit of a PITA but all you need to is use vmware (or similar) with an OS that can read your self-extracting-floppy-making image. Write to a virtual floppy file. Now take that floppy image and use it as Hasta la Vista? (Score:2) Re: (Score:2) Not for me (Score:5, Informative) Yes, you can do that with the nifty-keen gaming motherboard on your gaming computer, but my army of Dell Optiplex GX150s and 260s still need me to use floppies (USB sticks aren't allowed in the building for ludicrously retarded "security" reasons). jokes (Score:2, Funny) 1998 (Score:5, Insightful) Re: (Score:3, Informative) Nah, in 1998 CD burners weren't in my college's computer labs. They had CD readers, but those handy US flash drives weren't really around back in 1998. I actually sunk some money into an external zip drive because I could connect it to all the computers that I had access to, and it would wor Re: (Score:3, Insightful) I disagree, especially for typical iMac users in 1998. Remember, this was before CD burners, USB keys, and home broadband were mainstream. If you ever saw an Mac computer lab in those days, you'd have noticed an ugly external USB floppy drive hanging off every iMac. I thought Apple dropped floppy drives at least a year too early. To move data to Steve Jobs first tried to kill floppies in 1988 (Score:3, Interesting) Another of Jobs' projects, the original NeXTcube [wikipedia.org], also came without a floppy drive. Instead it had a cutting-edge but oddball 256MB magneto-optical drive. Too bad disks cost about $100 and pretty much nobody else used them. I remember that at the time Jobs disparaged floppy drives as "1970s technology," and I thought: Yeah, and keyboards are 19th century technology, but I wouldn't want a computer without one. Eventually he caved and by 1990 the NeXTstation had a 2.88MB floppy drive. Joy (Score:2) Non-standard disk drivers and windows installs, requirement - floppy. That one computer your company has had since the dawn of time that simply sits there and prints data to the screen never being turned off never being replaced because no one really knows how it works but it is "needed". Geeks will need the sex jokes about floppy drives and hard disks. I for one am happy to see floppy drives go. I discovered with windows 95 that I am an Floppies won't be missed (Score:5, Interesting) Anyone else ever try to download big files from your school's higher speed Internet connection and then use WinZip or PKZIP to try and zip it up over 40 floppies, only to find when you got home, disk #40 had a bad sector in the readme.txt file and the entire archive was bad? With as many Word documents I had to rescue for friends from those things with ScanDisk, and as many went bad after 6 months or less, I say good riddance to bad rubbish. Of course, the quality went to hell around the era of Windows 95. Before that, companies actually made good floppies that would last on the order of years. Good bye and good riddance (Score:3, Interesting) With el Torito and CD-RW's, it is easy to get by without a floppy drive. move from active-use to shelf-storage (Score:2) I don't build pc's with floppies in them anymore but I do keep a few at home or around (with cables) just in CASE some wonky install needs one. but at this point, I even treat cd/dvd drives like that. they don't get used often enough (for me) to justify keeping them installed in a box. more weight to have to lift (every bit adds up in a chassis) and more air blockage and power consuming for no real return (again, in my case) Save Icon? (Score:5, Funny) Or shall we keep it around as a memorial (and to confuse the next generation)? Nah (Score:4, Interesting) Re: (Score:3, Insightful) Younguns... (Score:2, Funny) What about 8" floppies!!! (Score:3, Interesting) Last time I used a floppy disk... (Score:2) As a result, I could only run my ancient projects by burning them to CD first, then running them from FreeDOS. Kinda cute too, to see what my code looked like back then *shudder* nostalgia (Score:3, Informative) Not ready reading drive A: ()Abort ()Retry (Y)Fail? What's the difference btwn a woman and a computer? (Score:5, Funny) How is a woman like a compiler? (Score:3, Funny) In the Good Old Days. (Score:2) Humph. Those of us who have really been in the IT arena for a while remember when real geeks had 8-inch floppies. Beginning of the end???? (Score:4, Insightful) I bet for a lot of us, we've not handled floppies in several years. And, while my computers still have floppy drives, nothing has been in them for quite a while. It's way too late in the decline of the floppy to call it "the beginning of the end". Cheers Plenty of supply (Score:4, Funny) I've never called the 3 1/2 ones floppies (Score:4, Funny) I prefer to call the 3 1/2 ones "stiffies". Re: (Score:3, Funny) Re: (Score:3, Informative) Old-school (Score:4, Interesting) Re: (Score:3, Informative) Those of us who've been in IT for a long while remember when the OS and power application lived on 80 column cards. (OK, I don't, but my boss tells me about it all the time and I have screwed around with the manual punch machine we still have) 8 in floppy (Score:3, Informative) The first job I had at Zenith Electronics about 25 years ago had me building a dual 8 inch floppy drive Heath Kit that I had to use. I recall when a single sided, single density floppy for the Commodore 64 cost around $8.00. I had to buy a USB floppy for a system at work because some POS software assumed that data backup went to drive A: and I could not convince the user to use a mapped portion of her hard drive instead. I remenber several applicatins assuming that drive A: existed. It's (Score:5, Funny) about [INSERT DISK TO CONTINUE] time. [INSERT DISK TO CONTINUE] Anybody [INSERT DISK TO CONTINUE] remem [INSERT DISK TO CONTINUE] ber the [INSERT DISK TO CONTINUE] 128K [INSERT DISK TO CONTINUE] Mac? Floppies from Hell (Score:5, Funny) Who cares what PC World says? (Score:5, Informative) I hope someone finds this information useful. When do we get notchable CD's? (Score:5, Funny) Vista still requires them to back up credentials (Score:4, Informative) Melissa The Floppy is not dead (Score:3, Funny) This is news? Shop for a laptop... (Score:3, Insightful) Most new computers don't have floppy drives. They were obsolete when I was A+ certified in '03 and they're obsolete now. Let's grow up and move on. Not dead (Score:3, Interesting) USB flash is everywhere! (Score:5, Interesting) To me the best thing about flash drives is that they work almost EVERYWHERE now. There are drivers out there for Windows 95 ("B" version and up), Windows NT, and even DOS! Ok, here's a link [toastytech.com]. They will work on my Mac, Linux and even the eComstation (that's OS/2) demo CD I tried! I used to think Iomega would rule the world with their Zip drives, but the prices of the disks always remained insanely high and the disks and drives were not as reliable as they should have been. Also, I don't think I ever saw anybody other than Iomega produce zip-compatible drives. Probably patents and BS. News to me. (Score:3, Interesting) I understand adhering to requirements. But floppy disks? I guess the real lesson I'm learning so far is that some people will force you to use stupid old methods or standards or media because they said so and for no other good reason. Might as well tell me to submit it on five-and-a-quarter, it would the same inconvenience at this point. Re:It was just their time, it was just their time. (Score:2) BTW: Since availability is going to be short, everybody had better stock up now! No replacement, but most don't care. (Score:5, Interesting) I used to keep stacks of floppies sitting around, mostly ones conveniently sent to my home by the kind folks at America Online, to give to people when they needed some document or other. I rarely got them back, and it was understood that discs just sort of circulated around, like some sort of valueless currency. When you needed one, you just looked around until you found one (that looked disused) and did whatever you had to do. Email has really replaced floppies. Not just email as a service, because obviously email has been around for decades, and floppies didn't decline in popularity until the last few years, but near-universal access to email, with the capability of receiving nontrivial attachments (greater than a few K but less than a few MB), and always-on connectivity. Before you had that, giving someone a floppy with a document was the most convenient method. Now, email is by far easier. If I was working on something, and needed to give someone a copy, using removable storage wouldn't be my first thought: instead I'd just send it to them. The kind of removable storage you're talking about is only necessary for a few cases, either where the file is too big to be practically attached to an email, or the person doesn't have an email address (rare, these days) or other internet access to receive it. So in those cases, CD-R or CD-RW are made to suffice. Overall, mini CDs or business-card CD-Rs would be a good candidate for replacement (and it's really not hard to put them in a little vinyl sleeve to keep them from getting scratched; 5.25" floppies didn't last long outside a paper sleeve either), but the market for them is just so limited that the economies of scale don't exist to make them as cheap as floppies were. Re:Still no working replacement (Score:4, Interesting) From a technical standpoint, Minidisc is exactly that. Unfortunately, Sony has pretty successfully killed their own format. They're too afraid of piracy, to actually sell decent products. Instead they always offer too little, too late. Re:Still no working replacement (Score:4, Interesting) I liked floppy discs, but the reason that the 3.5" 1.44MB floppy survived so long was that no-one came up with a truly universal successor (the Zip disc had some success in its day, but never became "standard"). Guaranteed bootability, universal support, etc... made it a near-essential even in the face of more advanced technologies that would otherwise have killed it far earlier; but you can see why no-one wanted to pay much for one. I would say that its day was over, but people were saying that 2 years back. Truth is, despite PC World's attention-whoring announcment, the floppy won't die suddenly, it'll just continue fading away. LS-120 and 250 (Score:5, Insightful) The 250 drives went even further, by allowing you to format regular floppies to some ungodly (and ultimately unreliable) capacity in the range of 30 MB. This typically left them readable only by the original drive, even other LS-250s tended not to be able to read them. Also, they had just a wee problem with bit rot. But they could still use 1.44 MB disks in the conventional manner as well, and the older 120 MB disks, and their own 250 MB disks. They were just too little too late -- by then, CD-RW had far surpassed them in the bang-for-the-buck department, as well as the raw space department. CD-RW discs (why the spelling change? I don't know) had dropped below $1 apiece by then, and the 250 MB media were still in the $12-15 range. If you didn't think the disc was ever coming back, CD-R blanks were about 35 cents. Mal-2 Re: (Score:2) but I'll go with "Put in disk 3 and press enter." Or in case of Monkey Island 2: disks 1 through 11. Not too late. (Score:5, Insightful) I wouldn't waste too much time before you archive them, though; drives are only going to get harder to find, and the media itself that you have stuff stored on ain't getting any younger. A slight bit of irony, though: years ago, when I first got an Iomega Zip disk, I was sure that it was going to replace floppies completely. (And for a while it seemed like it; there were some Macs in the late 90s that shipped with Zips in place of the FD drive.) So I dutifully backed up all my old floppies onto Zip disks. Not that long ago, when I decided it was time to retire the Zip for good, I went to pull the data off of its cartridges and back them up on CD-R...only to find that the disks were plagued with the "clicks." I had to go back to the floppies to get the old stuff again. Taught me two good lessons: 1) always roll backups onto new media whenever possible (I should have backed those Zips up to CD-R as soon as I got a disc burner), but more importantly 2) don't ever trust that the new media will be more robust than the old. Even now, I still have the floppies stored along with the CDs (and now DVD+Rs), because I'm not sure which will last longer. Might as well cover all the bases. Re: (Score:3, Informative) ZIP disks WERE poised to take over the floppy market, as an alternative to LS120 and Syquest cartridges. CD burners DID come out at around the same time -- but back then, a Sony Spressa 2X read / 1X burn was worth $2500 and blank CD-Rs worth worth $20 each (figures in Canadian dollars). CDs were also quite finnicky back then, and SCSI controllers for the burners weren't exactly cheap, either (you needed something like an Adaptec 1542, worth about Re: (Score:3, Funny) Re: (Score:3, Informative) The network stack for dos has been available free from Microsoft for years. Basic Netbios & IPX/SPX are pretty easy to setup. (Surely I wasn't the only one to play Doom and Duke Nukem 3D on a LAN.) TCP/IP is also doable but is quite a memory hog; you'll definately want to setup a custom boot sequence to boot with or without network support. I'm not sure how well DOS networking plays with domains, and active directory; it *used* to work a Another publicity stunt from the Dixons group (Score:5, Informative) (1) Death of video recorder (i.e. VCR) in sight [bbc.co.uk] (2) Dixons to end 35mm camera sales [bbc.co.uk]. In the case of the VCR, their announcement was misleading at best, and more likely just a pack of lies. Dixons.co.uk (and the large-format Currys stores) *still* each sell a wide range of standalone VCRs, over 2 years later. (Visit dixons.co.uk [dixons.co.uk] and search for "video recorder"). IIRC the high-street Dixons stores (now called "Currys.Digital", ugh) still sold them long after the supposed phase-out date. I don't know about the 35mm cameras, but even if they were telling the truth in that case, it was a nice publicity stunt for them. Even more so for the floppy discs; you're stopping selling floppy discs and you felt the need to make a big announcement about it?! Of course, the intention behind these announcements- besides the straight publicity- is to give the impression of Dixons and PC World as hi-tech, cutting-edge type places. When in fact they're mediocre at best; sometimes competitive, but just as often overpriced- particularly for more humble items such as USB and Ethernet cables, staffed by salespeople who like to pretend they know more than they do, flogging overpriced warranties and with a poor reputation [ciao.co.uk]. Online shopping is much cheaper, and with a better selection. They got a mention on /. too... (Score:5, Informative) (1) "The UK's largest retailer of electronics is phasing out VHS VCRs." [slashdot.org] (Note that as I pointed out then [slashdot.org], Dixons' "discontinuation" of the VCR took place before DVD recorders (*not* playback-only devices) and HDD-based PVRs had taken off. (2) "Digital Cameras Force Film Off Dixons' Shelves" [slashdot.org] Re: (Score:3, Informative) 8" disks are commonly called floopy disks. 5.25" disks - mini-floppy disks. (unless they were the Lisa ones which were Twiggy Floppys) 3.5" disks - micro-floppy disks. (though micro-floppy was widely used for other formats like the 3 and 2" versions as well.) Cassette tapes were just Cassttes - or in Commodore speak 'datasettes' (I think Adam cassettes were data-packs). Then there were the exatron tapes which were stringy floppies. And the tinly Sinclair QL tapes were micrdodrive cartridg Re: (Score:3, Funny) I got an email about this (Score:5, Funny) Re:thinking of the children...... (Score:5, Insightful) That's right! It doesn't seem silly at all when you think about it. My mom's a writer and routinely sends manuscripts, articles, etc to different publishers. One particular publisher insisted that she send a printed copy, refusing email attachements, CDs or any sort of soft copy, citing that 'the paper medium has been proven to be much more reliable than digital, yada yada..." Ridiculous, what a bunch of luddites I thought. I was already thinking of asking giving them a piece of my mind about that when it occured to me even I couldn't even open my old 1990s files anymore. Not only were some of them in Iomega Zip disks, they were in old proprietary formats. (Well, that's another topic altogether.) Another case more to the point: About a decade ago, my family decided to cobble together some sort of "time capsule" to be opened in about 50 yrs. It had several items including some files on 3.5 floppies. My dad asked me how were my grandkids supposed to read those things by then? I guess the moral is, I shouldn't have been tied down to any (digital) storage medium, arrogantly thinking it'll always be the standard.
http://hardware.slashdot.org/story/07/01/30/217211/farewell-to-the-floppy-disk
CC-MAIN-2014-15
refinedweb
4,515
70.63
Feedback Getting Started Discussions Site operation discussions Recent Posts (new topic) Departments Courses Research Papers Design Docs Quotations Genealogical Diagrams Archives Compelling lecture by John Cook Abstract: R is a strange, deeply flawed language that nevertheless has an enthusiastic and rapidly growing user base. What about R accounts for its popularity in its niche? What can language designers learn from R's success? I did not watch the video but read the slides that are easily readable on the web. Thanks for the efforts to make it easily accessible. I was hoping for some ideas that could be transferred out of the specific statics domain into general domain-specific language design considerations. I was a bit disappointed because I don't think I got that out, but it may very well be that one must watch the recorded talk, instead of just reading the slides, to get the whole picture. The slides say that R is popular despite being ugly, slow and not well tooled, because it is convenient, free, and has an efficient global code sharing place. Two points of interest for me were the mention that R comes from the research community (Bell Labs, then University of Auckland according to Wikipedia), and that it was designed by statisticians. It seems obvious in retrospect, but still, I think it could be fun to go see domain experts¹, ask them to basically invent a programming language for their domain, probably by giving concrete examples, and from that work out a way to develop domain-specific libraries in principled ways. ¹: with as little programming experience as possible, to avoid interference from previous knowledge restricting innovation. My wild, unsubstantiated guess would be that if you teach {Java,C,Python} to domain experts and then ask them to "invent a language for their field", you are likely to get {Java,C,Python} with small variations. My wild, unsubstantiated guess would be that if you teach {Java,C,Python} to domain experts and then ask them to "invent a language for their field", you are likely to get {Java,C,Python} with small variations. According to H.Ford, when doing such an interview you get "faster horses". This claim is not entirely unsubstantiated. I'm working in a domain where we occasionally purchase test tools from vendors because of the test suites. The tests were developed by tool vendors in proprietary languages which are rip offs of Pascal, VB or JavaScript, depending on the time and age the designer looked at the programming language pool. The languages are astoundingly bad and so are the test suites. They are so bad actually that it makes sense to develop a complete test suite on ones own, if only the language was appropriate and one had a working implementation. The time spent for this is not needed to debug those 3rd party tools, of which some are ridiculously buggy but are nevertheless mandated in the certification process. It's so far beyond quality control that it borders fraud. All of this happens in a niche market, so it might not be too interesting as a business model and it also can't go open source, because the specs are proprietary. If you watch the video you'll hear more comments about what's good about R for its specific domain. The thing I found most impressive was its incredibly terse syntax for fitting a regression model. Obviously this is irrelevant for any other domain; it's just fantastic for statisticians. I guess the take-home message from that is that a DSL will be successful if it matches its domain really well, no matter how bad it is in more general terms. The video also has some excellent comments about how even programs which are so buggy that they crash all the time (by which the speaker doesn't mean R, but some other statistical programs) will do well if they enable people to get their work done. Jan Vitek and his students are looking at R a lot recently. Check out their ECOOP 2012 paper: Evaluating the Design of the R Language. Abstract: can assess the impact and success of different language features. According to the above presentation, this misses the point. The language design aspects they consider are largely irrelevant. What matters is how easy it is to get started and do common tasks like linear regression, handling data sets, etc. As he puts it succinctly "DSL: D, not L". Their own conclusions support this. On the choice of old vs. new object system in R: The simplest object system provided by R is mostly used to provide printing method for different data types. The more powerful object system is struggling to gain acceptance. They also conclude that performance is abysmal, but R is still wildly popular. This is of course not such good news for language designers. Jan talked to me about this when he visited in prep for PLDI 2012 (everyone please come to Beijing...). He totally gets that and is pragmatic about what R is, why it is successful, and believes there is a lot of fruit to be had in having PL expertise focus on R rather than thumb are noses at it. There is especially low hanging fruit to be had in the area of performance. I don't think the language design choices are irrelevant, just that many other factors are at play here. "Batteries Included" (D) drives more adoption than language features do, but L tends to be important in the long run. Right, I actually agree that language design is important (and the presenter likely does too). But for adoption it is probably not that important, especially if your audience does not consist of people who are primarily programmers. As you say in the long run it leads to problems. That said the presenter does hit the nail on the head with some of the problems I had with Python/Numpy/Scipy/Matplotlib not being domain specific enough (in the context of physics simulation, not stats). It's just very nice to be able to install 1 standard thing, open a repl and type plot(...) and get a plot instead of having to install a separate package which has intricate ways of plotting that requires documentation hunting, an import statement and a couple of lines to imperatively assemble a plot from its pieces. It is also nice to be able to say A \ b instead of "from numpy.linalg.sparse import spsolve; spsolve(A,b)" for sparse matrices, "from numpy.linalg import solve; solve(A,b)" for square dense matrices, something else for non-square matrices, etc. Language designers can help to design the libraries in a more consistent way. For example a mini language for specifying optimization problems, statistical models, etc. Even on the very small scale they can help. One thing that bothered me in numpy for example is that its vectorization is inconsistent. Many primitive operations are extended to work on arrays. For example you can apply sin(x) to an array and it will apply it to each element. But this principle is not applied consistently. If you transpose a 2 dimensional array, then it will do what you want. But if you transpose a 3 dimensional array it will transpose the outer dimension instead of treating it as an array of 2-dimensional arrays and transposing each of inner ones. I think a language designer with an eye for these things paired together with a domain expert can achieve the best things. One thing that shader languages (HLSL and GSL) do right is universal vectorization of built-in functions, but this is more of a performance concern than an elegance issue (still, it helps a lot). Bling was extremely consistent here, and most functions were designed to work over vectors and matrices of arbitrary lengths and ranks (the hacks I had to do in C#'s type system to get that to work were quite crazy though). Designing a math library is quite fun. We could push much more aggressively on library support in languages. I think that there should be a language and just ONE library, installed aside the language and its dev runtime/environment. There is really no such thing as just a language anymore; people want the whole package programmer experience in one click. If you must have a package management system because your lib ecosystem is too large, make that a part of the library and mostly transparent to the programmer. If people need to share code, do that through the library (using ACLs to protect the code from people you don't want to share with), ditto for versioning. Ok, I've said this many times before. And of course, you'll need the right language abstractions to make that really large library viable. This is where language design can be play a huge role: you want adoption, your users want libraries, boot strap that networking effect in your language. You can do this in Ruby like this ;) def import lib require lib rescue LoadError `gem install #{lib}` require lib end import 'sinatra' import 'json' The `foo` runs shell command "foo" (this is called system("foo") in C). It's an interesting idea and it could really lower barrier to entry for domain specific programmers. Getting stuff up and running is ofen more work and definitely more frustrating than actually writing the small amound of domain specific code that uses the libraries Sean is looking for a system that either provides a uniform very broad standard library, or else provides strong language support for packaging such that a standard corpus of third party languages looks essentially like it always exists on the system. I'm sure plenty of people have noticed that current packaging systems require manual or semi-automated extraction of dependency information that's present in source code, object code headers, and build files, and then redundant storage of this information in some packaging DSL. I think part of Sean's question is "have we seen language features that would better allow languages like R to leverage some large trusted corpus of libraries by reducing the information that must be repeated between source code and the packaging system?" Jules's proposed solution may work to sweep under the rug some mistakes made by package maintainers, but doesn't allow the packaging system to statically resolve and install dependencies. For one, the proposal breaks if the program is installed while connected to the Internet, but is then run in a remote area or restricted environment. For another, I'm not sure if gems is usually setuid root or will automatically install packages in some alternate location if the user running the program has sane (restricted) permissions. More importantly, there appears to be no information available about versioning of libraries or versioning of interfaces/interface semantics. This sort of information is very important in packaging systems, but Jules's proposal doesn't make it explicit and doesn't provide a mechanism for automatically inferring this information. Right, it was just a joke, though it is not hard to imagine an import function that logs its use to a configuration file that is later used for bundling the libraries with the final program. Of course, this doesn't do anything for the problem that Sean is trying to tackle, namely programming with those huge libraries. Its not that bad of a solution actually, and it gets the point across quite clearly. And Javascript allows programmers to reference libraries by URL right? I'm assuming the physical bit problem is easy enough to solve; we have the internet at any rate. But we liked the internet a whole lot more when we could find useful things in it (Google). Which long run are you referring to? Do you mean that adoption will increase later? Or that language features are more important for some type of domain? Vector//Matrix math intrinsics, built in plotting tools, and read//eval//print interactivity were important features for the areas where S-Plus//R and Matlab became popular. Here is a link to a pdf comparing them. My suggested approach to the question would be to divide an conquer: Q1) Why are those features listed above paramount in some application domains? and Q2) What were the important differentiating features in the competition between languages with those features - include Mathematica and other competitors listed here under the heading "language oriented". In the case of R, being a free and open source implementation of S-Plus and getting the be the preferred choice of an active community of academic developers during a time when data mining and machine learning were really taking off application areas off were probably important contributing factors. To understand the appeal of R, it would also be helpful to look at why there was the rapid abandonment of XLISP-STAT in the 1990s. There was much hand-wringing over why people would dump a stable and well-documented system in favor of R. Several articles were written and I think there was even a whole journal issue devoted to it. My own take on the situation was that people had been using XLISP-STAT because it was the only powerful and free system available. People switched as soon as there was an alternative that wasn't Lisp. If I had to pick one defining feature of R, it would be its call-by-value-but-not-really. For example, if you define an R structure foo with fields bar and baz (technically, it's a "data frame", but bear with me), you can then say qplot(bar, baz, data=foo) Notice the lack of quotes. In R is that every expression in the position of a function parameter is, by default, unevaluated. In addition, R lets you *change* the expression scope of an unevaluated expression. So qplot can say, in effect, "get the first two parameters, and evaluate them in this new scope I just constructed". You can use R structures as dictionaries for scope lookup as well; think Javascript-with on steroids. Here's what the R language manual has to say about it (this will make a few of you cringe): [...] R is a functional programming language and allows dynamic creation and manipulation of functions and language objects, and has additional features reflecting this fact. So in practice, this is an extremely convenient way to quickly build little ASTs to be passed into functions. This is used very widely in libraries (so you can fit or plot sqrt(x) instead of x in a model, but where "sqrt" is evaluated in a different scope and it might mean something entirely new) Of course, it also means that debugging is as bad as you're thinking. But it's a fun, crazy little model to think about. This sounds a bit like a DSL I've used, and in this DSL there was some handy use of this "pass by AST" calling convention. For one, it allows ordinary functions to act a bit like macros. The common boilerplate if not key in cache: cache[ key ] = ExpensiveFunction( key ) value = cache[ key ] could be replaced by the much easier to read value = ComponentEnsure( cache, key, ExpensiveFunction( key ) ) where inside ComponentEnsure, the third argument is lazily evaluated in the scope one frame up the call stack. There are things not to like about the DSL, but the calling convention's ability to allow writing of ComponetEnsure as just another library function is nice. Of course, the power of the callee to determine argument strictness and evaluation scope should be used very judiciously. if not key in cache: cache[ key ] = ExpensiveFunction( key ) value = cache[ key ] value = ComponentEnsure( cache, key, ExpensiveFunction( key ) ) Pythons decorators feature is simple yet amazingly useful syntactic sugar. def memo(f): table = dict() def fmemo(x): if x not in table: table[x] = f(x) return table[x] return fmemo @memo def fib(n): if n <= 1: return n else: return fib(n-1) + fib(n-2) fib(100) # this is quick There must be something else "behind the curtain" otherwise there is no obvious link between 'fmemo' and fib: fib code doesn't call fmemo.. fmemo is returned from memo. It is the memoized version of f. The syntactic sugar works like this: @f def g(X): Y ===> g = f(lambda X: Y) This ensures that recursive calls to g also call the wrapped version. Note that f does not even have to return a function, and that f can be an expression itself, so it's quite flexible. For example a common use is to expose functions from request to a HTML response via a web server: @route('/foo/bar') def foobar(req): ... A python decorator is used to re-bind the function it decorates. Consider something like @foo def bar(): return baz() This is de-sugared into def bar(): return baz() bar = foo(bar) Since the memo-decorator returns the fmemo function, fib will be re-bound to that function (which in turn calls the original fib function). @foo def bar(args): code can be understood as def bar(args): code bar = foo(bar) The latter assignment really is a mutation, not a variable shadowing. All further calls to `bar`, including those coming from 'code', will use the updated rather than the original definition. If you wanted to be fully explicit about mutation, in ML you would write: let memo f = let cache = Hashtbl.create 19 in fun x -> try Hashtbl.find cache x with Not_found -> let result = f x in Hashtbl.add cache x result; result (* tie the knot *) let fib = ref (fun _ -> assert false);; fib := function | 0 | 1 -> 1 | n -> !fib (n - 1) + !fib (n - 2);; (* this is slow *) !fib 35;; (* decorate *) fib := memo !fib;; (* this is fast *) !fib 100;; Indeed, if you want to do that without mutation, you should formulate this as a fixpoint operation: `fib_derec : (int -> int) -> (int -> int)`, `fib = fixpoint(memo(fib_derec))`. You can also do this: let rec fib = memo (fun n -> ...) I'm not sure about ML but in F# I think you can (can't test now), and in Python you definitely can. This hides the mutation, and will result in a run time error if you try to call fib before memo returns (which memo does not do). You can't do that in OCaml at least, because the type-checker has a restrictive analysis of recursive definitions that are statically known not to force yet-unitialized recursive values, which of course forbids arbitrary function application (one would need a finer type system for this, which have been discussed previously in this thread). Funnily enough, OCaml recursive modules do not enforce this static safety, so you can write: module rec M : sig val fib : int -> int end = struct let fib = memo (function | 0 | 1 -> 1 | n -> M.fib (n - 1) + M.fib (n - 2)) end Yes, that is precisely what it feels like. And I suspect this is at least partly why the language is described as being inspired by Scheme. Promises remind me of Kernel's fexprs. The differences are that Our paper on R is here. It's a strange world. Thanks. This is interesting. By the way, I always found it ironic that in many cases we find languages with huge libraries, and hence wide adoption, that are sub-optimal for writing libraries (think C); while languages presumably better suited for writing libraries, often have very limited library support (think Ada). I hardly think this is a coincidence. Maybe but I don't think so, for me it's the cost of the Ada tools which hindered Ada adoption: if the DoD had the foresight to start GNAT in the 80s and not in the 90s, then it's possible that we would use Ada instead of C++ in many case.. I so didn't want to focus on the Ada case... In general I agree that the adoption of Ada was to a large extent hindered by extra-linguistic factors. To put more flesh on my provocative statement: I think that languages that privilege library writing at the expense of day-to-day coding (of the kind relevant to the particular language community), will not be adopted, and libraries don't get written for languages that are not used. I think this tension comes up nicely in Jan's paper. I don't know: Java seems to me as a 'not very good' language which has been used to write lots of libraries and is quite successful. So which language in your opinion focus on library writing instead of day-to-day coding? What are the criteria? Java is grist for my mill. Your first sentence mirrors my argument. Scala vs Java might be a good contrast... What contrast are you referring to? Scala's support for powerful abstractions make writing grand libraries (DSLs even) possible. But then the complexity that these abstractions seem to attract discourages mass adoption (those libraries aren't so easy to use), so in a way it is both better and worse than Java. Ehud: "To put more flesh on my provocative statement: I think that languages that privilege library writing at the expense of day-to-day coding (of the kind relevant to the particular language community), will not be adopted..." Scala seems to "privilege library writing" while Java is optimized for "day-to-day coding." I won't make any claims regarding whether the one comes "at the expense of" the other, but that's certainly part of the blogospheric argument over Scala adoption. Yes, I suppose that's a good example (though not an egregious case). To put more flesh on the "at the expense of" part: The point is not that there is a necessary trade off; merely that when day-to-day coding (of the relevant kind) is considered difficult, down the road advantages are seldom enough to get adoption. Divorcing the adoption of Scala from the adoption of Java ignores much of Scala's design and success, and especially when considering libraries. Scala definitely benefits from an existing Java ecosystem of Java libraries and such. But my point was that Scala's value add, its more powerful/typeful abstractions, has attracted a more high-brow ecosystem that many mainstream Java users aren't so excited about. Whereas less expressive languages seem to attract more down-to-earth ecosystems (at least with respect to their targeted users). If I understand correctly, you're saying that one problem with Scala is that it attracts Haskell developers that scare the other people with blogs about union types, continuation-passing style, or higher-kinded types. Could you be more specific about what you call an "ecosystem" here? Is it the to-the-outside communication (are the Haskell-Scala people so noisy because they're so good at communicating, is their visibility proportional to their size in the wider Scala community?), or the internal discussion lists, or maybe also the released libraries (besides Scalaz, do you have examples of visible "high-brow" Scala software)? Do we have any recommendation about how to manage a disparate community of language users from different backgrounds? Do some language feature facilitate finding a common ground, or allow to protect oneself from different and unknown exterior practices? Is this related to the "only one way to do it" vs. "more than one way to do it" debate? Ecosystem = libraries + users (the plants and the animals that eat them). My exposure to Scala in the last couple of years has been through PL-interest blog posts, so I could be way off here, but things like collections 2.8 really seemed like way too much to me. Some libraries are down to earth, like Play, so what do I know? I think you are asking the wrong questions. The community (and ecosystem) will grow organically around the language and you can't really predict the end result. But you can definitely shape the ecosystem, by including (or excluding) features. That an ... interesting point of view. I believe almost anyone who has actually worked with Scala 2.8 collections believes they are the ecosystem's biggest asset. The question was not do programmers using scala like the collections. Rather, is there a reason more programmers are not adopting scala, and are the collections a factor. Those are significantly different questions. The point is not if Scala is appreciated by its base, but how it appears to not-yet potential users, if you are aiming for mass adoption. Higher-kinded types are too much for me personally to take in, they could be completely reasonable for other people. Scala definitely has a very rich ecosystem, this wasn't the argument. The question is...does the nature of the ecosystem prevent mass adoption. For example, imagine if all your users were Haskell refugees, then Scala libraries would gravitate toward more Haskell-like interfaces, third-party documentation would push lazy functional programming, monads, and so on, non-Haskell programmers would begin to stay away. There is also platform bias, being only on the JVM, which could attract more back-end web developers than say, UI programmers (who wants to build Swing UIs anymore?), hence a focus on build tools vs. nice UX. [replying to both Sean and Patrick]. My main frustration with the collections discussion is that collections in Scala after 2.8 are really simple. They are much more intuitive and uniform than collections in any other library I know. Almost everyone who has even a little bit of practical experience with them confirms this. So it's much more a matter of perception than anything else. Btw: Higher kinded types are not a part of client facing collection APIs. Their only usage is if you want to pull in a helper class to construct a rich collection factory. That's completely optional and reserved for people implementing collections, people using collections do not see these types at all. Yes, for better or worse, perception and culture matter at least as much as, probably more than, a rational technical evaluation when it comes to programming language adoption. In general I agree that the adoption of Ada was to a large extent hindered by extra-linguistic factors. It seems to me that in almost all cases, language adoption (or lack thereof) is largely driven by extra-linguistic factors... Java/C# being prime examples. And, presumably, the argument will be that the "good" languages did not succeed because they lacked such support, or were hindered by extra-linguistic factors. So why wasn't CLU a great success? Why didn't Modula-2 (or, heck -3) conquer the world? I could go on, but I think the point is clear. CLU is an easy case; as far as I know, it was largely confined to the (relatively uncommon) Honeywell architecture that the CLU team was using. Certainly, being available for the right architectures at the right times is hugely important, though certainly not sufficient to guarantee success either. I really can't speak to Modula-2, other than my impression is that it was largely overshadowed by its predecesor, Pascal, which itself was soon overshadowed by C. (Though, I suppose why this occurred is an interesting question...) Modula-3, I'm a little unsure. The SRC implementation was open source and gratis and available for a wide variety of architectures, though Digital never supported and promoted it the way Sun did Java, which largely overshadowed it. And it was open source at the right time, though it never developed the community to sustain the language the way say, the GNU Compiler Collection or Python did. I think the SRC implementation really did miss an opportunity with the open source route, by not embracing the concept fully enough. I think if you could go back in time to 1994-95 and convince Digital to release it under a GPL-compatible license so that it might become an official part of the GCC, pay attention to distributing it on Linux and FreeBSD, and invest resources into developing a community and making it easier to contribute patches to the mainline compiler, we might be living in a different world today. (And, if that doesn't work, implement a Modula-3 compiler free of Digital's license.) And heck, because you are from the future, you should promptly set up something like CTAN/CPAN/CRAN while you are at it. Of course I'd want add support for explict tail calls and functional closures, but the point is this almost certainly wouldn't make a difference with respect to adoption. Also, if you had a trip back to 1994-ish to influence PL, would you spend it on Modula-3? I seriously doubt I'd bother. Languages like R, Javascript, PHP, have a razer focus on their domains and don't worry about getting "it right." Its good enough just to be good enough, release at the right time, and be useful. Notice that many of these languages weren't even designed professionally on big budgets (counter examples being C# and Java), they were designed by people with some knowledge of existing work and a very good understanding of the problems in their domain. Also note that marketing didn't have as much to do with it as we often claim, these languages were just good for their domains. PL research is more useful as a feeder into production languages. Hopefully a research language will capture the right person's attention at the right time (e.g., Scheme/Self's influence on Javascript). That is how we should define success. Yep. Hopefully there are more ways for people from the research community to have impact on those "right persons"? You basically describe laying around and making noise in hope to be just lucky. Could research results also have impact during an open design process (or do your notion of "good enough" implies that no one hears of the language until design is settled?), or to help the latter evolution of the language? (Javascript current evolution is, since a few years already, informed by a lot of people that know about language design; the R thread mentioned ongoing work that could have impact. I would like to say the same for PHP, but I really don't know.) Guy Steele calls for care in "Growing a language". Should we study more the question of "Fixing a language"? We put out knowledge, the knowledge gets disseminated (maybe slowly) but eventually, if its good enough, will have some influence. Our goals as PL researchers should be to experiment with language features, build new languages that push the envelope in extreme ways, and then reflect on what we've done. I think that "Growing a Language" has not come to pass as the "right way;" even "fixing a language" is very limited. The so-called committees you talk about have limited influence: Javascript will evolve but not in any drastic ways; its initial design stands and all we can do is move it a little one way or the other. There is no heavy duty language design going on there; a lot of bike shedding perhaps. PL research has the most impact when the language is initially conceived and designed; at which point it is not on the language researcher's radar who would join committees for already popular languages as a matter of prestige. There is no such thing as a viable open design process; design-by-committee fails often and almost all successful languages have been designed by a small number of people (often = 1) in a closed process. Languages like R, Javascript, PHP, have a razer focus on their domains and don't worry about getting "it right." Sure, that's one path of language adoption, but what about Python, Lua, or Ruby? None had a particularly specific domain in mind, at least not in the way that R, PHP, or JavaScript did. Yet Python is comparable in popularity to PHP and JavaScript, Ruby isn't too far behind, and Lua is more popular than R. Also, Python, Ruby, and particularly Lua are concerned with "getting it right". JavaScript and R too, to a lesser extent. PHP seems to be the one language that has outright hostile attitude towards "the right thing". I should have said "don't obsess over elegance" rather than "don't worry about getting it right." I had the pleasure of hearing Roberto talk about Lua in March; the slides are here. Some of the trade offs made would make us academic/research PL designers cringe (can't we be more elegant than assoc arrays everywhere?) but it turns out to be a very good combination for their targeted domain; there is a lot of thought put into it. Huh? Lua was explicitly made for embedded systems (and, similar to Scala's success in finance, was bolstered by government policies). I thought Python originated as a new OS scripting language. I don't know about the original design of Ruby, but it effectively didn't matter until Rails (which was the real domain-specific design). Perhaps Lua was helped by public money in the beginning (like many other languages), but since the game developers found out about it, it seems to have done all right on its own merits. Lua also has the advantage of being able to rid itself of bad design decisions by moulting. It wasn't just public money for building the language, but a restriction on languages that local developers could use. Likewise, I suspect that the embedding concerns it was designed for carried over to the game space. I'd go further with the molting: adoption has important natural social benefits in terms of technology evolution such as social learning and adaptation. This is an old comment but... At the time Ruby was invented there was a scripting war between Perl and Python. While both had limited object oriented support neither was fully object oriented. Ruby was created to offer all the power of the scripting languages, including functional manipulations but an objected oriented structure. What domain is javascript focussed on like a razor? Of the reasons I can list for its popularity, that would not make the top 10, if it would make the list at all. I'm not sure what your point is? JS definitely has a "domain," web programming, and contains abstractions that support that (at least, you can define libraries like JQuery). Its turned out pretty well for them also. Luke Tierney, the main author of XLispStat who switched to R at some point, has slides on his website about some work he is doing to improve the efficiency of R. He'd likely be interested in a copy of your paper. Sorry for the mis-threading - I meant that as a reply to Jan Vitek Luke is indeed working on a bytecode implementation of R. We talk from time to time. The fact that he, as a statistician, has to learn about how to implement a bytecode compiler points out to our failure as a community. He should be spending his energy on problems that are relevant to his domain rather than re-inventing Java bytecode. And we should be providing him with an efficient implementation as well as advice on how to evolve the language. R like many scripting languages has the advantage of a low barrier to entry for users. The statistic department at Purdue teaches R in one week. (For comparison we take four months to teach Java). But as pointed out above it is a lousy language for writing libraries. It has no concurrency. No encapsulation. Etc. It is a shame that we can't come up with a way to nudge the large R user base towards a better programming model. Despite being a statistician I feel it's good only if you need to perform some taks which is already implemented *exactly* in the way you want in some library and do it in a simple interactive session or script. For anything else it's a mess: - incredibily slow: most interpreted languages are not very fast (with notable exceptions) but non-vectorised R is tipically 1/1000 the speed of a C program. So in then end 99% of the libraries are coded in C for efficiency reasons! - very inconsistent: some functions follow the a.funcion convenction, some a_function, some aFunction, some ... (and this in the core R as well) Other inconsistencies are present at syntax and semantics levels - while it's easy to like being able to write "qplot(bar, baz, data=foo)", this will hunt you in non-trivial programs: the scoping and environments rules are very complicated. You will *not* be happy when debugging any program - the implementation it's not exactly "elegant", as neither is the design of the types/structures involved in the C implementation (it suffice to read the code) - no way to compile R ouside gcc/mingw, especially in Visual Studio (it's C!) - the data containers available makes it impossible to implement some algorithms with optimal computational complexity - operations you may think are easy to do are not or may leave data structures in inconsistent state (adding a row or col to a data.frame?) The advantages are that the huge majority of stats libraries / implementations of research papers are in R (:") and the ggplot2 + rply + reshape combination allow tearse syntax for a number of problems, but that's it... I don't know anything about R. Could you say a bit more about what ggplot2 + rply + reshape are, or provide pointers? By googling around I found this on ggplot and a related reshape page (but it seems to be talking about melt/cast commands that supplant an existing "reshape" command; are you talking about the reshape command or the reshape package?); nothing about rply. The ggplot library definitely seems LtU-relevant -- and would interest people resurrecting the STEPS thread. The Grammar of Graphics [6] presents a comprehensive grammar with which to describe graphics. The key concept is that a graphic is produced by mapping data values to aesthetic attributes of graphical objects (grobs). For example, a scatterplot maps the values of the x and y variables to the position of the points. A bubble plot additionally maps the area of the points to a third variable. Mappings range from simple, e.g. a linear mapping from data value to position on the screen, to complex, e.g. mapping a transformed variable to a colour scale. These mappings are supplemented by guides, such as legends and axes, to complete the graphic. The grammar of graphics concentrates on static graphics. A detailed grammar for interactive and dynamic graphics has yet to be developed, although some efforts have been made in that direction [5]. Sorry, I meant plyr (not rply) :P Everything has been developed by this guy: I suggest reading the papers (linked on the respective pages of his website) published in JSS. These three packages toghther allows for easy data reorganisation (reshape), devide and conquer, or mapreduce if you like, functionality (plyr) and plotting (ggplot). That's exactly what I thought about R, after some limited experience with this language a few years ago. From what I know, it seems that the people who likes this language most are those from biology background. They don't care about the language, they just need a few of lines codes (which they can happily copy from tutorials, documentations and examples) to get their job done. Even though R seems very popular now in the relevant fields, I believe it may fade away eventually, when the fields evolve or there is a better alternative. For example, in bioinformatics, the first language that became popular in the field was Perl, then it came R, now Python. Clearly the choice of language is highly correlated with the kind of problems needed to be solved in the field: first a lot of text processing, then a lot of statistics, now many bioinformatics problems have gone beyond text processing and statistics, python start getting popular. So the fate of R in bioinformatics might be the same as the fate of Perl in this field: relevant, but unlikely be the first choice (for new comers of course). Everything fades. In the meantime, what matters is libraries. Stats, Bio, Finance, all have massive amounts of code written in R or easily callable from R. There is a very large R community of users. There are many books teaching the language. There are many classes using R. I am afraid that it is here for a few more years (it's been around for 15 by now). Also, I don't think that R and Python are really competing. It more like R is the academic alternative to Excel, or Matlab. That's what I said as well in my initial comment, and the reason I use it when some library is readily available for some specific task :-) I'm just disappointed about the "language itself", intended as its core functions + semantics + syntax + implementation. Excel is awful and I am not sure whether Matlab is better or worse than R, I'm not proficient enough in Matlab to comment on this...
http://lambda-the-ultimate.org/node/4503
CC-MAIN-2016-26
refinedweb
6,922
60.35
08 August 2011 17:59 [Source: ICIS news] LONDON (ICIS)--Stocks in the European chemical sector were dragged further down by a sharp fall in the global markets on Monday following the US debt downgrade by Standard & Poor’s and on continuing fears over the eurozone’s debt crisis. At 15:47 GMT the Dow Jones Euro Stoxx Chemicals index was trading down 4.53%, as shares in many of ?xml:namespace> Among Europe’s top producers, German major BASF’s shares had dropped 4.61% at 16:20 GMT, Bayer had fallen 3.52%, Dutch coatings firm AkzoNobel was down 4.61%, while The European Central Bank’s (ECB's) decision on Sunday to step into the bond markets and buy Italian and Spanish debt in order to ensure eurozone price stability appeared to have had little positive impact in an extremely nervous market environment which mirrored sentiment in Asia. At 16:21 GMT, the Share prices had dropped sharply in The market turmoil helped drive oil prices lower. At 16:00 GMT, Brent September futures were at $105.99/bbl, down $3.38/bbl, while September WTI was down $3.19/bbl at $83.69/bbl. Naphtha was trading around $894–902/tonne, down $1/ton
http://www.icis.com/Articles/2011/08/08/9483458/chemical-stocks-hit-hard-as-european-share-prices-slump.html
CC-MAIN-2015-18
refinedweb
208
65.93
CloudPAN - Never install pure Perl modules again version 1.130561 use CloudPAN; { package Foo; use Moo; has bar => (is => 'rw'); sub baz { $_[0]->bar } } print Foo->new(bar => 3)->baz . "\n"; # 3 ... # Or if you want to persist what you've downloaded: use CloudPAN { persistence_location => '/home/nicholas/cloudpan' }; Ever wanted to load modules from the "cloud"? Love the concept of MetaCPAN and want to exercise it? Then this module is for you. Simply use this module before using any other module that doesn't require compilation (ie. XS modules) and you're set. Note that this doesn't work on all modules (especially ones that mess around with @INC too). (HashRef) import takes a HashRef of options. CloudPAN can either use temp files created with File::Temp, or it can persist what you have previously downloaded from MetaCPAN. To enable persistence, pass it the option 'persistence_location' with an absolute path to the directory you'd like CloudPAN to store things. There is no real authentication that happens when accessing MetaCPAN. Someone could easily Man-In-The-Middle your connection and feed you bogus code to run. Seriously, don't use this in production code..
http://search.cpan.org/~nperez/CloudPAN-1.130561/lib/CloudPAN.pm
CC-MAIN-2014-52
refinedweb
195
67.15
1.0 Signals Signals are notifications delivered asynchronously to a process by the kernel. Signals are grouped in two categories. First, there are standard signals, which have been there since the early days of Unix. Second, there are POSIX real-time signals which are specified in POSIX.1b, or, IEEE Std 1003.1b-1993, for Real-time Extensions for POSIX compliant Operating Systems. In this post we will look at POSIX real-time signals in Linux. 2.0 Characteristics of POSIX real-time signals The Linux kernel supports real-time signals range defined by macros SIGRTMIN and SIGRTMAX. Unlike the standard signals, the real-time signals do not have predefined names individually. Applications can identify the real-time signals by using an expression like (SIGRTMIN + n), where n is an integer between 0 and (SIGRTMAX - SIGRTMIN). The default action for a real-time signal is to terminate the receiving process. Real-time signals are queued to the receiving process. This applies even when the same real-time signal is received multiple times. In contrast, if a standard signal is blocked and multiple instances of it are to be delivered to a process, only one becomes pending and the rest are discarded. If multiple real-time signals are queued to a process, they are delivered in the ascending order of their signal numbers, that is, lower real-time signal first. In contrast, the order of delivery of queued multiple standard signals is unspecified. If multiple instances of the same real-time signal are queued to a process, they are delivered in the chronological order. If both standard and real-time signals are queued to a process, the standard signals are delivered first. This matches with the concept that the lower numbered signals are delivered first. If a real-time signal is sent using the sigqueue function, a value or a pointer can be sent along with the signal. This value or the pointer can be retrieved by the receiving process from the second parameter of the real-time signal handler, the pointer to siginfo_t. The value or the pointer is stored in si_value or si_ptr members respectively. 3.0 Setting the signal action The signal handler is installed with the sigaction system call. #include <signal.h> int sigaction (int signum, const struct sigaction *act, struct sigaction *oldact); The struct sigaction is, struct sigaction { void (*sa_handler) (int); void (*sa_sigaction) (int, siginfo_t *, void *); sigset_t sa_mask; int sa_flags; void (*sa_restorer) (void); }; If SA_SIGINFO is specified in sa_flags, the pointer to function, sa_sigaction is the signal handler to be set in the sigaction call. When the signal comes, the signal handler is called with pointer to the siginfo_t structure as the second argument. The signal handler can get information about the signal from the siginfo_t structure. The siginfo_t structure is,_call_addr; /* Address of system call instruction (since Linux 3.5) */ int si_syscall; /* Number of attempted system call (since Linux 3.5) */ unsigned int si_arch; /* Architecture of attempted system call (since Linux 3.5) */ } The above structure is for information about the members only. For the actual structure, please refer to the sub-directories under /usr/include. In the actual structure, members given above might have different names and / or organized in unions, and, some members might not be present. The member si_code specifies the reason for the signal. Some of the values of si_code are, An important characteristic of real-time signals is to communicate information and not just the signal id. It is the capability to pass an integer or a pointer, which is elaborated below in the description of the sigqueue function. The signal handler can get more information about the signal from this integer or pointer. 4.0 System calls 4.1 sigqueue #include <signal.h> union sigval { int sival_int; void *sival_ptr; }; int sigqueue (pid_t pid, int sig, const union sigval value); The sigqueue function sends the signal sig to the process identified by pid. It also sends data, a value, along with the signal. The value is a union of an integer and a pointer. If the receiving process has installed a signal handler using the SA_SIGINFO flag, it can get the value using the si_value field of the siginfo_t structure. 4.2 sigwaitinfo #include <signal.h> int sigwaitinfo (const sigset_t *set, siginfo_t *info); sigwaitinfo is an improvement on the sigwait system call. Like sigwait, it blocks till a signal specified in the set becomes pending. However, sigwaitinfo has a second parameter, a pointer to typedef siginfo_t, in which data about the signal is returned. Like, sigwait, the signals specified in the set should be blocked before making the call. On success, sigwaitinfo returns the accepted signal, a value greater than zero, and the signal is removed from the set of pending signals for the thread. In case of failure, -1 is returned and errno is set accordingly. 4.3 sigtimedwait #include <signal.h> struct timespec { long tv_sec; /* seconds */ long tv_nsec; /* nanoseconds */ } int sigtimedwait (const sigset_t *set, siginfo_t *info, const struct timespec *timeout); sigtimedwait is similar to sigwaitinfo, except that the maximum time of wait is as specified in the structure pointed by the third parameter, timeout. If timeout occurs and no signal is pending, sigtimedwait returns -1 with errno set to EAGAIN. 5.0 An example: Using real-time signal As an example, consider a limited over cricket match being played between two teams. Cricket matches are good to watch and we tend to concentrate on the players. However, there are a lot of organizers who stay in the background, do the hard word and make the show possible. We will refer to two such persons here. One is a manager and the other is the scorer. The manager's list of jobs to do is a myriad; he has to take care that spectators are seated, lights are working, ground support staff is available, and what not. Suffice to say, he is a very busy person. As much as he would like, he is not able to follow the match because he has to look after so many things. Then there is the scorer, whose work is well defined. He has to note the runs scored, balls bowled, partnerships, maiden overs, etc. Because of the nature of his job, the scorer is able to follow the match. So the scorer decides to help his friend, the manager. The scorer can not describe the match ball by ball to the manager, nor is the manager free enough for that. The scorer tells the manager that whenever a four or a six is scored, and also, whenever a wicket falls, he would signal to the manager, so that the latter has some idea about what is happenning. It turns out that the manager and the scorer can use POSIX real time signals for this quite well. And, here are the programs. 5.1 The manager program /* * * manager.c: Manager program * */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <sys/types.h> #include <errno.h> #include <unistd.h> #include <signal.h> void syserror (const char * const str); void sig_rtmin_handler (int signum, siginfo_t *siginfo, void *context); int main (int argc, char **argv) { struct sigaction act; memset (&act, 0, sizeof (act)); // set signal handler for SIGRTMIN act.sa_sigaction = sig_rtmin_handler; act.sa_flags = SA_SIGINFO; if (sigaction (SIGRTMIN, &act, NULL) == -1) syserror ("sigaction"); // Do important work while (1) sleep (10); } void sig_rtmin_handler (int signum, siginfo_t *siginfo, void *context) { switch (siginfo -> si_value.sival_int) { case '4': write (2, "Four runs scored.\n", 18); break; case '6': write (2, "Six runs scored.\n", 17); break; case 'W': write (2, "A wicket has fallen.\n", 21); break; default: write (2, "Unclear communication\n", 22); } } void syserror (const char * const str) { perror (str); exit (EXIT_FAILURE); } 5.2 The scorer program /* scorer.c: signal the manager when a batsman hits a 4 or a 6, or, when a wicket falls */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <sys/types.h> #include <errno.h> #include <unistd.h> #include <signal.h> void syserror (const char * const str); int get_option (void); int main (int argc, char **argv) { int option; if (argc != 2) { printf ("Usage: scorer manager-pid\n"); exit (1); } pid_t manager_pid = atoi (argv [1]); while (1) { printf ("Action: \n"); printf ("\t1\tBatsman hit 4\n"); printf ("\t2\tBatsman hit 6\n"); printf ("\t3\tWicket falls\n\n"); printf ("\t0\tQuit\n\n\n"); printf ("Enter action: "); scanf ("%d", &option); if (option == 0) break; if (option >= 1 && option <= 3) { // send signal union sigval sigval; switch (option) { case 1: sigval.sival_int = '4'; break; case 2: sigval.sival_int = '6'; break; case 3: sigval.sival_int = 'W'; break; } if (sigqueue (manager_pid, SIGRTMIN, sigval) == -1) syserror ("sigqueue"); } else printf ("Illegal option, try again\n\n"); } } void syserror (const char * const str) { perror (str); exit (EXIT_FAILURE); } We can compile and run the manager and scorer programs. $ gcc manager.c -o manager $ gcc scorer.c -o scorer And, we run the two programs.
https://www.softprayog.in/programming/posix-real-time-signals-in-linux
CC-MAIN-2021-17
refinedweb
1,485
65.42
After several hours of searching, videos, articles, and forums I need help from the gurus. I have a simple dataset table with a list of trips. I want the dropdown, currently correctly displaying the country list, to onChange: filter the table to only display said countries. I'm not a javascript coder but can read it if someone explains. I can't figure out the correct javascript. Thanks. Hay martinlopezfl, What you want to do is have an onChange event handler on the dropdown that sets a filter to the dataset of the table. It should look some like the following - Thanks Yoav! it doesn't quite work as intended. The dataset table does not filter out other rows. It kind of "filters" or rearranges the rows. I had to modify the code a bit, but not sure if selectedValue' at the end needed a ' in the beginning. I tried multiple ways to no avail. I wonder if this is the issue: The dynamic page's url is set to .../Expeditions. That is the dataset. I don't have any filters {country}. On this page, all countries display (good). When I select a specific country from the dropdown, the country field in the table shuffles but the other countries still show. Should part of the script tell the page to refresh with the .../Expeditions/country-1 filter? A bit confused. Here is my script: Ok, I figured it out. 1) Dropdown input field is disconnected from dataSet and all values have to be manually added (for now- testing other way). 2) The values have to be Capitalized if the cell content is Capitalized. This will be the filtering system so the column entries are the actual filter values. 3) Here is the code underneath: import wixData from "wix-data"; // For full API documentation, including code examples, visit $w.onReady(function () { //TODO: write your page related code here... }); export function selectCountry_onChange() { //Dropdown field console.log("Trying filtering items to " + $w("#selectCountry").value); if ($w("#selectCountry").value === 'all') { //Default manual value $w("#expDataset").setFilter(wixData.filter()); //Set the dataset filter to all rows } else { $w("#expDataset").setFilter(wixData.filter().contains('country', $w("#selectCountry").value)) //country is my table column name, selected value now in the dropdown now becomes the new filter .catch((error) => { let errorMsg = error.message; let code = error.code; }); } }
https://www.wix.com/corvid/forum/community-discussion/filter-table-from-dropdown-menu-solved
CC-MAIN-2019-47
refinedweb
389
60.51
Windows Phone 8: Using C++ in your Applications - Date: November 1, 2012 from 4:15PM to 5:15PM - Day 3 - B92 Magellan - 3-049 - Speakers: Peter Torr - 18,917 Great news!!! At 17:40 of the clip, if I want the 'public ref class' to be inheritable, the 'sealed' must be moved but then I can't compile it successfully. In win8 app the class should be derived from an existing unsealed base class such as Windows::UI::Xaml::DependencyObject (). In wp8, should I derive it from System.Windows::DependencyObject? I tried but the namespace "System" can't be found. Do I miss anything? Yanger, WinRT doesn't really support the notion of inheritance for classes. A special case is made for XAML controls in Windows 8, but we don't support C++ XAML on Windows Phone 8. Please note that the slides available on this page are NOT the ones I presented; please see the slides from the repeat talk to get the actual slides (but sadly several of my demos failed during that talk, so you should watch the video on this page!) Well, I hope that somebody in Microsoft realized that Windows8/WP8 is only platform on world which have different language set and even really big changes in API for tablet/mobile platforms ? All of us, who spent lot of man-hours with moving their projects C++ into WinRT/C++/CX for Windows8, is good to know that we can't use them on WP8 and we have to rewrite them to C#/C++ mixed mode or to DirectX. Maybe developers in MS start thinking - why I should learn two languages and two slightly different API's when iOS and Android needs only changes in UI files and code behind can be almost universal for tablet/mobile platforms ? Sometimes it looks that part of MS developers want continue in C++ and part of MS developers want keep up with .NET And we, 3rd party developers which are pushed to use Visual Studio because there is no support for 3rd part tools and WinRT/WP8 , now have to use C++ for DX games (RIP XNA) and C# for XAML UI and C++ for components/reusing old code. How, the hell, can be problematic support C++ XAML on WP8 ? Performance of mobiles is almost same as performance of Surface (( Your website is broken, and is a piece of * trash. good day. Remove this comment Remove this threadclose
http://channel9.msdn.com/Events/Build/2012/3-049
CC-MAIN-2013-48
refinedweb
409
65.46
- Multiple submit buttons in a single form ? - Panel - render event - does it happen after rendering - ComboBox: droplist render problem - [Solved]Textfield bug - not displaying until forced redraw - Problem on submit form - how to replace a calendar with yui caledar in grid - How to highlight selected TreeNode (is not a leaf) - How can i display a picture on cilent .? - Ext with Air Beta 3.0 - disabled & invalid textfield - how to add and remove plug-in for a panel dynamically - [HELP] Setting Form Values Dynamicly - how to replace tree node ui's checkbox with Ext.form.Radio - [Form submit] Transaction failed - Add content in Treepanel? - my columsheaders disappear after changing renderTo: - how to add footer in Windows - How do I make a default selection in ComboBox ? - switching between tabs - grouping grids - performance problems when displaying many rows - More tutorials/examples - data from grid to formPanel - [2.0] Scrollbar in tabpanel or viewport - Problem with Grid data in Internet Explorer, in Firefox works - How to hide paging toolbar when there's 1 page in the result grid? - HtmlEditor don't get correct height - [SOLVED] simple XMLReader example? - Panels - Proper way of adding grid to dialog/Win - load ext-base.js and ext-all.js via dynamic method - adding ComboBox items - Add namespace attributes on fly - DataView in Panel won't load - how to disable a cell in the grid - IE6 - Select Menus Through Window Mask - How to Hide/Remove Column Headers in Grid Panel? - [Solved]Autoload non active tabs - Customizing TreePanel + Get the Selected Item - How to display paging bar in Gridpanel? - Ext Events and HTMLEditor contextmenu - post textfield data to php using load()? - Working/loaded/visible panels "undefined" in console?! - checkbox align problem in firefox ( formpanel in window) - Tab disappearing - Grid Editing... - Cannot retrieve Combobox value at php side. - * width alignment in FormPanel - strange error ! - Creating a link to a GridPanel - Can You Put a Tooltip on a Titlebar Icon? - Sorting/Unsorting part of a tree - Tree Example Modification - Handling Sessions - What is the 2.0 equivilent of collapsedTitle? - [Solved]Textfield and Radio Button Label Widths - [Solved]Combobox Size Bug !! - Aggregating Multiple Datastores - THESE CHICKS NEED GROUPING! - ERROR: Component returned failure code: 0x80004003 (NS_ERROR_INVALID_POINTER) - Submitting Form data as XML - Same DIV to display different panel - Unable to access Nested DIV in Nested Layout - Setting up source for the Store object - What is the HTML Form Tag equalent for multiple select - Creating a Menu When a Titlebar Icon is Pressed - Getting the value from a radio group - Collapse on page load - sortInfo and GroupSummary - How to add buttons to the tab itself? - Problem with grid rendering - change text color of selected row in grid panel - [Solved]Ext will not load in IE6 - When I use activeX control in Viewport tabpanel sometime it disappear - when columns turn on/off ,GridPanel show normal in Firefox,but unnormal in IE? - How to handle BasicForm.submit submission? - Panel example for an invoice screen - IE7: 'Enter' in ComboBox causes refresh - ToolBar Calendar event - how to return message from ajax page in ext tab - "Autoload" for the Items of a FormPanel - Send easy data <--> PHP - window autload not working - EditorGridPanel editor's question - panel not showing in firefox - drag'n'drop row in gridPanel - 7 EditorGrids using 1 ColumnModel --> Editor issue - pass getSelection() result to DWR remote method - Ext.PagingToolbar - adding extjs controls inside tab panel - Controls are not visible inside tab panel - GridPanel is displayed in TabPanel respectively - [2.0] window.open('popup.html'); - How to give password field (encrypted format) - Radio/checkbox checked on same inputValue - fckeditor fckstyles problem - How to get content from external file and render to tabpanel? - Combobox Value Question - Wrap long single word in a textarea - Can I turn off col headers in a PropertyGrid? - how to get the active cell in cellcontextmenu ? - [HELP] Strange Error on Tabs - display issues in IE7 - A plugin with extension :P [SOLVED] - xtype and performance - Script only works when I close Firebug. Why: - [ solved ] How Add new item in Accordion? - need help getting XMLReader response - Adding "edit row" to grid for global changes - dynamic search filter UI - like iTunes "smart playlist" builder - Image flicker when collapse/expand - EditorGridPanel() and CheckboxSelectionModel() incompatible? - Accessing JSON Data - grid do not run in my remote server ... why ? - Rendering Child Nodes Using TreeLoader - Dynamic Results Per Page?? - simple load mask question - Ext.Window.show() do not execute javascript - show Ext.window twice - How Do I Obtain The Window Title From an Event Handler? - expander - is it possible to expand only some rows? - [2.0][CLOSED] viewport resizing problem - performance: JSON Vs. XML - [Solved]Ext.Window mask question - How load data into form panel?? - VType Examples? - Extends basic modules class - My reusable component... - Form Input Styles - [Solved]convert string to json object (c#) - Grid column widths? - comboxbox.selectByValue() error - [Solved]What are plugins? - refreshing/recalculating grid column widths? - why function(){..blah..blah..} - CheckBox as a Column in a Grid - HELP how to get an array of values from XML - How to get data out of XmlReader - [2.0][CLOSED] Ext.PagingToolbar - the displayMsg stay on top de button - Using Date in JSON - [SOLVED] Help with the ColumnModel - TreePanel Drag & Drop Confirmation? - New and need help with accordion - how to get xml appoint node's childnode? - Which way is the correct way to extend Ext2.0 class on earth? - [Solved]Ext2.0 Textfield not showing in IE6 - How can I remove the node icons in a TreePanel? - Few Basic Doubts - Add TabPanel Problem - fieldLabel position - View window at image - [2.0]Add components from separate pages? - Ajax call on the success property of a submit - Using form load with DWR and JSON - how can i hide some nodes in the tree before they are rendered? - It is possible to put a checkbox to the left with boxLabel occuping all rest of space - Ext.form Public Event 'show' not working ? - How can I add the component defined in the separate page to the main layout once it's - Grid - using sortInfo and sum - Banal Question on Grid - [Solved]Menu in north region doesn't show up - How to transfer a variable from one window in another? - Refresh panel from xml data - [Solved]CardLayout deferredRender property always false - Disable checkbox in a editable tree? - Cannot "load" from separate JSP file - [solved]Grid Cookies DISABLE!!! - How can I pass an object name as argument? - how can i refresh my grid - Callback from a returned code - [2.0 Desktop] Resize Ext.Window on tab change. | Need help - [OT]: Connecting an extjs grid and Propel - Ajax Request - "this.fireEvent is not a function" - Cancel Upload Form Submission? - document set url - Formpanel within CardLayout not rendering fields - Combobox display / AppendChild / accessing objects - [Solved]redirect after login - [Solved]Strange Behaviour in IE - [Solved]Desktop 2.0 Error in FormPanel - JSON data & ETag - Change the store of a grid - [SOLVED] Scroll when Ext.get('anything').on('click', function(){ - clone/move object between frames - Problem with draggable (no header) window in IE - XTemplate & Arbitrary Code - Answer for gurus - Help with form colums - loadResponse is never invoked in DWRProxy - DateField time problem - [solved]view contents of an object - Nested grids in an expander - row expander - Treepanel problem in IE - [Solved]HtmlEditor and Submit not posting complete data - Add, remove and update xml data via Grid - Adding <fieldset> and <input> dynamically... - Assigning grid rows to a form. - minHeight/Height of Buttons - GridPanel not showing data - Portlet resizing help - Grid with paging bar - [solved] Bullets in treeview - [Solved]iconCls help for TreeNode...property not working for me - Decoding JSON strings returned by form submit - [SOLVED] Border problems with FormPanel + FieldSet + ColumnLayout - XHTML +SVG +MathML - Re-sizing border layout makes unrelated region 'grow' - panel.updater.update is slow - Problem with Grid Summary - building simple class - Inserting HTML into a form - Form Panel Question - Minimum code needed for Ext.data.ScriptTagProxy - fortunatur.com - Adding controls into tab panel - AsyncTreeNode slow - help! trouble with docs - direct href link on subpanel html content to a new browser window or iframe panel/win - Trying to implement ColumnTree with column content wrapping - hide some nodes in tree problem! - EXT with YUI - Panel Header with ComboBox - How Can I create this? - to prevent render some nodes - passing parameter - viewport panel closed, extra info wanted - Error: E.fireFn has no properties - html editor for text field with more characters - addling 2 panel to the east side - [Solved]Activating a hidden panel in a tabpanel without add()? - Grid with parent / child drill dowm - Problem - Grid with parent / child drill dowm - Problem - Append an element into another - Sending XML Data to a Servlet - How to include only the files needed? - onEsc behavior in Window - intended or bug? - No Tutorials? - How to load data into Grid by ID from Tree - Enable/Disable Tab on radio events - Anchoring not working in nested panels - How to iterate trough nodes in a treepanel - GroupingView : Trouble grouping columns with HTML as data (a bug...?) - Visibility of objects change on load/focus on internet explorer 7 - Add & Remove using Ext.getCmp() - search as you type locally (not remotely) - Window without border/header/tbar - Grid Editable Fields not Working Properly in Firefox - [Grid] How to have custom html into a grid cell - Catch error "on load" - how to make forum layout at example by using window??
https://www.sencha.com/forum/archive/index.php/f-9-p-23.html?s=f2cb27bacb03270d1667eb669ebad85b
CC-MAIN-2020-05
refinedweb
1,543
53.81
Linaro is an industry consortium dedicated to improving the functionality and performance of Linux on the ARM processor; its list of members includes many of the companies working in this area. Quite a bit of engineering work is done under the Linaro banner, to the point that it was the source of 4.6% of the changes going into the 3.8 kernel. A lot of Linaro's developers are employed by member companies and assigned to Linaro, but the number of developers employed by Linaro directly has been growing steadily. All told, there are hundreds of people whose work is related to Linaro in some way. Given that those people work for a lot of different companies and are spread across the world, it makes sense that they would all want to get together on occasion. That is the purpose of the Linaro Connect events. These conferences are open to any interested attendee, but they are focused on Linaro employees and assignees who otherwise would almost never see each other. The result is that, in some ways, Linaro Connect resembles an internal corporate get-together more than a traditional Linux conference. So, for example, the opening session was delivered by George Grey, Linaro's CEO; he used it to update attendees on recent developments in the Linaro organization. The Linaro Enterprise Group (LEG) was announced last November; at this point there are 25 engineers working with LEG and 14 member companies. More recently, the Linaro Networking Group was announced as an initiative to support the use of ARM processors in networking equipment. This group has 12 member companies, two of which have yet to decloak and identify themselves. Life is good in the ARM world, George said; some 8.7 billion ARM chips were shipped in 2012. There are many opportunities for expansion, not the least of which is the data center. He pointed out that, in the US, data centers are responsible for 2.2% of all energy use; ARM provides the opportunity to reduce power costs considerably. The "Internet of things" is also a natural opportunity for ARM, though it brings its own challenges, not the least of which is security: George noted that he really does not want his heart rate to be broadcast to the world as a whole. And, he said, the upcoming 64-bit ARMv8 architecture is "going to change everything." The event resembled a company meeting in other ways; for example, one of the talks on the first day was an orientation for new employees and assignees. Others were mentoring sessions aimed at helping developers learn how to get code merged upstream. One of the sessions on the final day was for the handing out of awards to the people who have done the most to push Linaro's objectives forward. And a large part of the schedule (every afternoon, essentially) was dedicated to hacking sessions aimed at the solution of specific problems. It was, in summary, a focused, task-oriented gathering meant to help Linaro meet its goals. There were also traditional talk sessions, though the hope was for them to be highly interactive and task-focused as well. Your editor was amused to hear the standard complaint of conference organizers everywhere: despite their attempts to set up and facilitate discussions, more and more of the sessions seem to be turning into lecture-style presentations with one person talking at the audience. That said, your editor's overall impression was of an event with about 350 focused developers doing their best to get a lot of useful work done. If there is a complaint to be made about Linaro Connect, it would be that the event, like much in the mobile and embedded communities, is its own world with limited connections to the broader community. Its sessions offered help on how to work with upstream; your editor, in his talk, suggested that Linaro's developers might want to work harder to be the upstream. ARM architecture maintainer Russell King was recently heard to complain about Linaro Connect, saying that it works outside the community and that "It can be viewed as corporate takeover of open source." It is doubtful that many see Linaro in that light; indeed, even Russell might not really view things in such a harsh way. But Linaro Connect does feel just a little bit isolated from the development community as a whole. In any case, that is a relatively minor quibble. It is clear that the ARM community would like to be less isolated, and Linaro, through its strong focus on getting code upstream, is helping to make that happen. Contributions from the mobile and embedded communities have been steadily increasing for the last few years, to the point that they now make up a significant fraction of the changes going into the kernel. That can be expected to increase further as ARM developers become more confident in their ability to work with the core kernel, and as ARM processors move into new roles. Chances are, in a few years, we'll have a large set of recently established kernel developers, and that quite a few of them will have gotten their start at events like Linaro Connect. [Your editor would like to thank Linaro for travel assistance to attend this event.] It should come as a surprise to few readers that Facebook is big. The company claims 1 billion users across the planet. Over 350 million photographs are uploaded to Facebook's servers every day; Jason suggested that, perhaps 25% of all photos taken end up on Facebook. The company's servers handle 4.2 billion "likes," posts, and comments every day and vast numbers of users checking in. To be able to handle that kind of load, Facebook invests a lot of money into its data centers; that, in turn, has led naturally to a high level of interest in efficiency. Facebook sees a server rack as its basic unit of computing. Those racks are populated with five standard types of server; each type is optimized for the needs of one of the top five users within the company. Basic web servers offer a lot of CPU power, but not much else, while database servers are loaded with a lot of memory and large amounts of flash storage capable of providing high I/O operation rates. "Hadoop" servers offer medium levels of CPU and memory, but large amounts of rotating storage; "haystack" servers offer lots of storage and not much of anything else. Finally, there are "feed" servers with fast CPUs and a lot of memory; they handle search, advertisements, and related tasks. The fact that these servers run Linux wasn't really even deemed worth mentioning. There are clear advantages to focusing on a small set of server types. The machines become cheaper as a result of volume pricing; they are also easier to manage and easier to move from one task to another. New servers can be allocated and placed into service in a matter of hours. On the other hand, these servers are optimized for specific internal Facebook users; everybody else just has to make do with servers that might not be ideal for their needs. Those needs also tend to change over time, but the configuration of the servers remains fixed. There would be clear value in the creation of a more flexible alternative. Facebook's servers are currently all built using large desktop processors made by Intel and AMD. But, Jason noted, interesting things are happening in the area of mobile processors. Those processors will cross a couple of important boundaries in the next year or two: 64-bit versions will be available, and they will start reaching clock speeds of 2.4 GHz or so. As a result, he said, it is becoming reasonable to consider the use of these processors for big, compute-oriented jobs. That said, there are a couple of significant drawbacks to mobile processors. The number of instructions executed per clock cycle is still relatively low, so, even at a high clock rate, mobile processors cannot get as much computational work done as desktop processors. And that hurts because processors do not run on their own; they need to be placed in racks, provided with power supplies, and connected to memory, storage, networking, and so on. A big processor reduces the relative cost of those other resources, leading to a more cost-effective package overall. In other words, the use of "wimpy cores" can triple the other fixed costs associated with building a complete, working system. Facebook's solution to this problem is a server board called, for better or worse, "Group Hug." This design, being put together and published through Facebook's Open Compute Project, puts ten ARM processor boards onto a single server board; each processor has a 1Gb network interface which is aggregated, at the board level, into a single 10Gb interface. The server boards have no storage or other peripherals. The result is a server board with far more processors than a traditional dual-socket board, but with roughly the same computing power as a server board built with desktop processors. These ARM server boards can then be used in a related initiative called the "disaggregated rack." The problem Facebook is trying to address here is the mismatch between available server resources and what a particular task may need. A particular server may provide just the right amount of RAM, for example, but the CPU will be idle much of the time, leading to wasted resources. Over time, that task's CPU needs might grow, to the point that, eventually, the CPU power on its servers may be inadequate, slowing things down overall. With Facebook's current server architecture, it is hard to keep up with the changing needs of this kind of task. In a disaggregated rack, the resources required by a computational task are split apart and provided at the rack level. CPU power is provided by boxes with processors and little else — ARM-based "Group Hug" boards, for example. Other boxes in the rack may provide RAM (in the form of a simple key/value database service), high-speed storage (lots of flash), or high-capacity storage in the form of a pile of rotating drives. Each rack can be configured differently, depending on a specific task's needs. A rack dedicated to the new "graph search" feature will have a lot of compute servers and flash servers, but not much storage. A photo-serving rack, instead, will be dominated by rotating storage. As needs change, the configuration of the rack can change with it. All of this has become possible because the speed of network interfaces has increased considerably. With networking speeds up to 100Gb/sec within the rack, the local bandwidth begins to look nearly infinite, and the network can become the backplane for computers built at a higher level. The result is a high-performance computing architecture that allows systems to be precisely tuned to specific needs and allows individual components to be depreciated (and upgraded) on independent schedules. Interestingly, Jason's talk did not mention power consumption — one of ARM's biggest advantages — at all. Facebook is almost certainly concerned about the power costs of its data centers, but Linux-based ARM servers are apparently of interest mostly because they can offer relatively inexpensive and flexible computing power. If the disaggregated rack experiment succeeds, it may well demonstrate one way in which ARM-based servers can take a significant place in the data center. [Your editor would like to thank Linaro for travel assistance to attend this event.]. In the late 1980s, he noted, client-server applications were not yet the default, and in the early 1990s, client/server applications running over the Internet were still comparatively new. In addition, the entire "copyleft hack" that makes the GPL work is centered around distribution, as it functions in copyright law. To the creators of copyleft, making private modifications to a work has never required publishing one's changes, he said, and that is the right stance. Demanding publication in such cases would violate the user's privacy. Nevertheless, when web applications took off, the copyleft community did recognize that web services represented a problem. In early 2001, someone at an event told Kuhn "I won’t release my web application code at all, because the GPL is the BSD license of the web." In other words, a service can be built on GPL code, but can incorporate changes that are never shared with the end user, because the end user does not download the software from the server. Henry Poole, who founded the web service company Allseer to assist nonprofits with fundraising, also understood how web applications inhibited user freedom, and observed that "we have no copyleft." Poole approached the Free Software Foundation (FSF) looking for a solution, which touched off the development of what became the AGPL. Allseer eventually changed its name to Affero, after which the AGPL is named, but before that license was written, several other ideas to address the web application problem were tossed back and forth between Poole, Kuhn, and others. The first was the notion of "public performance," which is a concept already well-established in copyright law. If running the software on a public web server is a public performance, then perhaps, the thinking went, a copyleft license's terms could specify that such public performances would require source distribution of the software. The trouble with this approach is that "public performance" has never been defined for software, so relying on it would be somewhat unpredictable—as an undefined term, it would not be clear when it did and did not apply. Establishing a definition for "public performance" in software terms is a challenge in its own right, but without a definition for software public performance, it would be difficult to write a public performance clause into (for example) the GPL and guarantee that it was sufficiently strong to address the web application issue. Kuhn has long supported adding a public performance clause anyway, saying it would be at worst a "no op," but so far he has not persuaded anyone else. The next idea floated was that of the Ouroboros, which in antiquity referred to a serpent eating its own tail, but in classic computer science terminology also meant a program that could generate its own source code as output. The idea is also found in programs known as quines, Kuhn said, although he only encountered the term later. Perhaps the GPL could add a clause requiring that the program be able to generate its source code as output, Kuhn thought. The GPLv2 already requires in §2(c) that an interactive program produce a copyright notice and information about obtaining the license. Thus, there was a precedent that the GPL can require adding a "feature" for the sole purpose of preserving software freedom. In September 2002, Kuhn proposed adding the "print your own source code" feature as §2(d) in a new revision of the GPL, which would then be published as version 2.2 (and would serve as Poole's license solution for Affero). Once the lawyers started actually drafting the language, however, they dropped the "computer-sciencey" focus of the print-your-own-source clause and replaced it with the AGPL's now-familiar "download the corresponding source code" feature requirement instead. Poole was happy with the change and incorporated it into the AGPLv1. The initial draft was "buggy," Kuhn said, with flaws such as specifying the use of HTTP, but it was released by the FSF, and was the first officially sanctioned fork of the GPL. The GPLv2.2 (which could have incorporated the new Affero-style source code download clause) was never released, Kuhn said, even though Richard Stallman agreed to the release in 2003. The reasons the release was never made were mostly bad ones, Kuhn said, including Affero (the company) entering bankruptcy. But there was also internal division within the FSF team. Kuhn chose the "wrong fork," he said, and spent much of his time working on license enforcement actions , which distracted him from other tasks. Meanwhile, other FSF people started working on the GPLv3, and the still-unreleased version 2.2 fell through the cracks. Kuhn and Poole had both assumed that the Affero clause was safely part of the GPLv3, but those working on the license development project left it out. By the time he realized what had happened, Kuhn said, the first drafts of GPLv3 appeared, and the Affero clause was gone. Fortunately, however, Poole insisted on upgrading the AGPLv1, and AGPLv3 was written to maintain compatibility with GPLv3. AGPLv3 was not released until 2007, but in the interim Richard Fontana wrote a "transitional" AGPLv2 that projects could use to migrate from AGPLv1 to the freshly-minted AGPLv3. Regrettably, though, the release of AGPLv3 was made with what Kuhn described as a "whimper." A lot of factors—and people—contributed, but ultimately the upshot is that the Affero clause did not revolutionize web development as had been hoped. In the time that elapsed between the Affero clause's first incarnation (in 2002) and the release of AGPLv3 (in 2007), Kuhn said, the computing landscape had changed considerably. Ruby on Rails was born, for example, launching a widely popular web development platform that had no ties to the GPL community. "AJAX"—which is now known simply as JavaScript, but at the time was revolutionary—became one of the most widely-adopted way to deliver services. Finally, he said, the possibility of venture–capital funding trained new start-ups to build their businesses on a "release everything but your secret sauce" model. Open source had become a buzzword-compliance checkbox to tick, but the culture of web development did not pick copyleft licenses, opting instead largely for the MIT License and the three-clause BSD License. The result is what Kuhn called "trade secret software." It is not proprietary in the old sense of the word; since it runs on a server, it is not installed and the user never has any opportunity to get it. The client side of the equation is no better; web services deliver what they call "minified" JavaScript: obfuscated code that is intentionally compressed. This sort of JavaScript should really be considered a compiled JavaScript binary, Kuhn said, since it is clearly not the "preferred form for modifying" the application. An example snippet he showed illustrated the style:();)which is not human-readable. Microsoft understands the opportunity in this approach, he added, noting that proprietary JavaScript can be delivered to run even on an entirely free operating system. Today, the "trade secret" server side plus "compiled JavaScript" client side has become the norm, even with services that ostensibly are dedicated to software freedom, like the OpenStack infrastructure or the git-based GitHub and Bitbucket. In addition to the non-free software deployment itself, Kuhn worries that software freedom advocates risk turning into a "cloistered elite" akin to monks in the Dark Ages. The monks were literate and preserved knowledge, but the masses outside the walls of the monastery suffered. Free software developers, too, can live comfortably in their own world as source code "haves" while the bulk of computer users remain source code "have-nots." Repairing such a bifurcation would be a colossal task. Among other factors, the rise of web application development represents a generational change, Kuhn said. How many of today's web developers have chased a bug from the top of the stack all the way down into the kernel? Many of them develop on Mac OS X, which is proprietary but is of very good quality (as opposed to Microsoft, he commented, which was never a long term threat since its software was always terrible...). Furthermore, if few of today's web developers have chased a bug all the way down the stack, as he suspects, tomorrow's developers may not ever need to. There are so many layers underneath a web application framework that most web developers do not need to know what happens in the lowest layers. Ironically, the success of free software has contributed to this situation as well. Today, the best operating system software in the world is free, and any teenager out there can go download it and run it. Web developers can get "cool, fun jobs" without giving much thought to the OS layer. Perhaps this shift was inevitable, Kuhn said, and even if GPLv2.2 had rolled out the Affero clause in 2002 and he had done the best possible advocacy, it would not have altered the situation. But the real question is what the software freedom community should do now. For starters, he said, the community needs to be aware that the AGPL can be—and often is—abused. This is usually done through "up-selling" and license enforcement done with a profit motive, he said. MySQL AB (now owned by Oracle) is the most prominent example; because it holds the copyright to the MySQL code and offers it under both GPL and commercial proprietary licenses, it can pressure businesses into purchasing commercial proprietary licenses by telling them that their usage of the software violates the GPL, even if it does not. This technique is one of the most frequent uses of the AGPL (targeting web services), Kuhn said, and "it makes me sick," because it goes directly against the intent of the license authors. But although using the AGPL for web applications does not prevent such abuses, it is still the best option. Preserving software freedom on the web demands more, however, including building more federated services. There are a few examples, he said, including Identi.ca and MediaGoblin, but the problem that such services face is the "Great Marketing Machine." When everybody else (such as Twitter and Flickr) deploys proprietary web services, the resulting marketing push is not something that licensing alone can overtake. The upshot, Kuhn said, is that "we’re back to catching up to proprietary software," just as GNU had to catch up to Unix in earlier decades. That game of catch-up took almost 20 years, he said, but then again an immediate solution is not critical. He is resigned to the fact that proprietary software will not disappear within his lifetime, he said, but he still wants to think about 50 or 100 years down the road. Perhaps there were mistakes made in the creation and deployment of the Affero clause, but as Kuhn's talk illustrated, the job of protecting software freedom in web applications involves a number of discrete challenges. The AGPL is not a magic bullet, nor can it change today's web development culture, but the issues that it addresses are vital for the long term preservation of software freedom. The other wrinkle, of course, is that there are a wide range of opinions about what constitutes software freedom on the web. Some draw the line at whatever software runs on the user's local machine (i.e., the JavaScript components), others insist that public APIs and open access to data are what really matters. The position advocated by the FSF and by Kuhn is the most expansive, but because of it, developers now have another licensing option at their disposal. Page editor: Jonathan Corbet Security At SCALE 11x in Los Angeles, Gazzang's Casey Marshall presented his work developing Hockeypuck, an alternative public PGP keyserver. Although the company developed Hockeypuck to support one of its own products, the AGPL-licensed server is capable of running a standalone key service, and is compatible with Synchronizing Key Server (SKS), the tool used by almost all public key services. Keyservers are a critical component in the public key infrastructure (PKI), even though they rarely attract significant attention. They enable PGP-aware client applications to search for and retrieve users' public keys, which is what enables parties to encrypt messages to one another without prior agreement. In addition to sender's and recipient's keys, PGP relies on a "web of trust" built up by verifiable signatures from other PGP keys. Aside from secure private email, PGP encryption is also used in an increasing number of other tasks, such as verifying software package signatures. Marshall observed that this system is in essence a globally distributed social network; the Internet's keyservers share identities in a distributed fashion across a truly global pool. Because keyservers distribute the load and can synchronize, it is very hard for an attacker to tamper with or otherwise undermine the keys. SKS is by far the most commonly used keyserver, Marshall said, and it offers a powerful set of features. It uses an efficient "set reconciliation" algorithm to keep the global database of keys in sync between remote peers, and it uses Berkeley DB for data storage. Although there is an older, email-based protocol for querying and retrieving keys, SKS is built around the HTTP Keyserver Protocol (HKP), which Marshall described as being RESTful before REST was popular. Marshall got into keyserver development while working on a Gazzang product called zTrustee. The product is a closed source storage service that uses OpenPGP keys to encrypt data. Because the service relies on generating and storing separate keys for separate objects, it quite naturally processes keys in heavy volume, which is not the typical workload for a keyserver. The company has been using SKS to distribute keys to clients, he said, but SKS is very write-heavy, and under sufficient load it was found to cause unacceptable delays. Hoping to improve on the situation, Marshall started writing Hockeypuck. It is not yet ready to replace SKS in zTrustee, but interested developers can test it out. The project is hosted at Launchpad.net and mirrored on Github. Binary packages are already available for Ubuntu 13.04, and there is a publicly accessible instance of the server running at hockeypuck.gazzang.net. GPG users can query the server by supplying it as a command line switch, for example: gpg --keyserver hockeypuck.gazzang.net --search-keys Santa The public server's web interface presents a minimalist "Google-style" search page (which, as he pointed out, includes an "I'm Feeling Lucky" button that is not really intended for serious usage). Hockeypuck does not participate in the global set reconciliation algorithm of the SKS keyservers, but the public server was initialized with a dump file provided by an SKS server six months ago, so it contains a significant subset of the total global key pool. Hockeypuck is written in Go, which Marshall said he selected for several reasons. Its simplicity and modularity make it fun to write in, he said, but it also offers useful features and high-performance message passing. The wide assortment of libraries available included an OpenPGP implementation, which he used, although he noted that there are not many OpenPGP implementations to choose from—most PGP development takes the form of additional services built on top a small set of OpenPGP stacks. At the moment, Hockeypuck uses MongoDB for storage; Marshall said he would be adding PostgreSQL support next, and perhaps other database connectors later. The server architecture is fairly straightforward, he said. A separate goroutine handles each HTTP request, opening a channel to a worker that queries the database. Scaling the system could be as simple as running one worker per CPU, or more sophisticated techniques could be employed depending on the database backend. Indeed, Marshall said, the choice of MongoDB has come with its share of problems. It was easy to develop with, he said; Go even has a library for it. "You give it a struct, and you get a struct back." But not being a real relational database imposes limitations, starting with the fact that you cannot index something just because you want to. The Hockeypuck database is indexed on the uid field (which contains names and email addresses), thus it cannot also run searches on other fields (like key-ID); a truly full-text search is not possible. He also found it necessary to reverse the order of key fingerprints, placing the shorter key-ID at the beginning of the record so that it can be read and searched faster. Maintaining performance has also been tricky, he said; loading data into MongoDB is very quick, but updates must be aggregated for write efficiency. Ultimately, he concluded, MongoDB makes it very easy to write database applications, but it shifts more work onto configuration and deployment. Maintaining the public Hockeypuck server has also imparted its share of lessons, he said. For example, an unknown user downloaded Marshall's own key, added new email addresses as uid fields, then re-uploaded the key to the server. An OpenPGP client application would not have been fooled by the deception because the grafted-on fields were not signed by the primary key, but the incident pointed out to Marshall that Hockeypuck needed to do its part as well. He quickly added code that checked the signatures on uploads, and reloaded the SKS key database just to be on the safe side. Technically, he observed, keyservers themselves are not meant to be trusted entities—the keys are designed to be verified or rejected cryptographically—but maintaining a tidy and valid database is important too. Hockeypuck's key loading is quite fast already, Marshall said; it can load about two million keys in 24 hours. Queries, in turn, are "reasonably fast," and the database appears to be the bottleneck. But apart from increasing performance, he has several other important items on his to-do list. For example, one improvement is support for OpenPGP version 3 signatures. Version 4 signatures are the standard today, but version 3 signatures can still be found in the wild. A far bigger task (which Marshall regards as the missing "killer feature") is implementing the SKS reconciliation algorithm. This will allow Hockeypuck to interoperate with the global pool of public keys. He has started work on an implementation of the algorithm (that he named conflux), which he hopes will be general-purpose enough to serve as a synchronization library outside of the keyserver itself. Conflux is "getting there," he said; the mathematical portions are passing unit tests, but he still has work to do on the network protocol itself. Further down the line, he speculated that Hockeypuck could serve as an SSH keyserver as well, and perhaps work with other authentication schemes like Password Authenticated Key Exchange by Juggling (J-PAKE) or convergence.io. Despite the fact that Hockeypuck "competes" with SKS, Marshall said he has found the SKS community to be very friendly, and many were excited to hear about Hockeypuck and its implementation of the set reconciliation algorithm. An independent implementation of the feature is good news for any project, but especially for infrastructure projects like SKS, because the "web of trust" that it implements is so crucial. Marshall concluded his talk by asking attendees to examine the web of trust and how it functions. We trust different identity credentials for very different reasons, he said: we trust PGP keys because of either the signatures of other PGP users or our participation in key-signing events; we trust SSH keys because they are the same key we encountered the first time we connected; we trust SSL/TLS certificates because they contain a signature from a certificate authority that our browser trusts. Our trust will have a stronger foundation if it includes multiple factors, he said; perhaps, for example, PGP keys need to incorporate notions of identity beyond email addresses alone. Keyservers could also play a role in advancing the conversation about identity management, he suggested. As he noted at the beginning of the session, the SKS global key pool has functioned as a decentralized social network for years—perhaps there are ways to leverage it, such as linking PGP keys to OpenID or OAuth accounts, or to make SSH user authentication as widely accepted as SSH host authentication already is. Of course, PGP is still in use by just a fraction of global email users; its critics have long argued that public key encryption and the PKI are too complicated for mass appeal. That is a difficult claim to prove, particularly since it is hard to disentangle the ideas of PKI from its client software implementations. But even for those who understand and use PGP on a regular basis, the accidental monoculture of SKS keyservers poses its own potential risks. Hockeypuck might never overtake SKS in popularity, but by offering an additional choice and by shining new light on HKP and other factors, it may strengthen critical pieces of PKI anyway. Brief items.. New vulnerabilities Page editor: Jake Edge Kernel development Brief items Stable updates: no stable updates have been released in the last week. As of this writing, the 3.8.3, 3.4.36, and 3.0.69 updates are in the review process; they can be expected on or after March 14.. Al? Please don't make me wear that golden bikini. In a recent posting of the overlayfs patch set, developer Miklos Szeredi asked if it could be considered for inclusion in the 3.10 development cycle. He has made such requests before, but, this time, Linus answered: At Linus's request, Al Viro has agreed to review the patches again, though he noted that he has not been entirely happy with them in the past. Unless something serious and unfixable emerges from that review, it looks like overlayfs is finally on track for merging into the mainline kernel. Kernel development news One of the features merged in the 3.9 development cycle was TCP and UDP support for the SO_REUSEPORT socket option; that support was implemented in a series of patches by Tom Herbert. The new socket option allows multiple sockets on the same host to bind to the same port, and is intended to improve the performance of multithreaded network server applications running on top of multicore systems. The basic concept of SO_REUSEPORT is simple enough. Multiple servers (processes or threads) can bind to the same port if they each set the option as follows: int sfd = socket(domain, socktype, 0); int optval = 1; setsockopt(sfd, SOL_SOCKET, SO_REUSEPORT, &optval, sizeof(optval)); bind(sfd, (struct sockaddr *) &addr, addrlen); So long as the first server sets this option before binding its socket, then any number of other servers can also bind to the same port if they also set the option beforehand. The requirement that the first server must specify this option prevents port hijacking—the possibility that a rogue application binds to a port already used by an existing server in order to capture (some of) its incoming connections or datagrams. To prevent unwanted processes from hijacking a port that has already been bound by a server using SO_REUSEPORT, all of the servers that later bind to that port must have an effective user ID that matches the effective user ID used to perform the first bind on the socket. SO_REUSEPORT can be used with both TCP and UDP sockets. With TCP sockets, it allows multiple listening sockets—normally each in a different thread—to be bound to the same port. Each thread can then accept incoming connections on the port by calling accept(). This presents an alternative to the traditional approaches used by multithreaded servers that accept incoming connections on a single socket. The first of the traditional approaches is to have a single listener thread that accepts all incoming connections and then passes these off to other threads for processing. The problem with this approach is that the listening thread can become a bottleneck in extreme cases. In early discussions on SO_REUSEPORT, Tom noted that he was dealing with applications that accepted 40,000 connections per second. Given that sort of number, it's unsurprising to learn that Tom works at Google. The second of the traditional approaches used by multithreaded servers operating on a single port is to have all of the threads (or processes) perform an accept() call on a single listening socket in a simple event loop of the form: while (1) { new_fd = accept(...); process_connection(new_fd); }() are two other noteworthy points about Tom's patches. The first of these is a useful aspect of the implementation. Incoming connections and datagrams are distributed to the server sockets using a hash based on the 4-tuple of the connection—that is, the peer IP address and port plus the local IP address and port. This means, for example, that if a client uses the same socket to send a series of datagrams to the server port, then those datagrams will all be directed to the same receiving server (as long as it continues to exist). This eases the task of conducting stateful conversations between the client and server. The other noteworthy point is that there is a defect in the current implementation of TCP SO_REUSEPORT. If the number of listening sockets bound to a port changes because new servers are started or existing servers terminate, it is possible that incoming connections can be dropped during the three-way handshake. The problem is that connection requests are tied to a specific listening socket when the initial SYN packet is received during the handshake. If the number of servers bound to the port changes, then the SO_REUSEPORT logic might not route the final ACK of the handshake to the correct listening socket. In this case, the client connection will be reset, and the server is left with an orphaned request structure. A solution to the problem is still being worked on, and may consist of implementing a connection request table that can be shared among multiple listening sockets. The SO_REUSEPORT option is non-standard, but available in a similar form on a number of other UNIX systems (notably, the BSDs, where the idea originated). It seems to offer a useful alternative for squeezing the maximum performance out of network applications running on multicore systems, and thus is likely to be a welcome addition for some application developers. Full Story (comments: 18) A February linux-kernel mailing list discussion of a patch that extends the use of the CAP_COMPROMISE_KERNEL capability soon evolved into a discussion of the specific uses (or abuses) of the CAP_SYS_RAWIO capability within the kernel. However, in reality, the discussion once again exposes some general difficulties in the Linux capabilities implementation—difficulties that seem to have no easy solution. The discussion began when Kees Cook submitted a patch to guard writes to model-specific registers (MSRs) with a check to see if the caller has the CAP_COMPROMISE_KERNEL capability. MSRs are x86-specific control registers that are used for tasks such as debugging, tracing, and performance monitoring; those registers are accessible via the /dev/cpu/CPUNUM/msr interface. CAP_COMPROMISE_KERNEL (formerly known as CAP_SECURE_FIRMWARE) is a new capability designed for use in conjunction with UEFI secure boot, which is a mechanism to ensure that the kernel is booted from an on-disk representation that has not been modified. If a process has the CAP_COMPROMISE_KERNEL capability, it can perform operations that are not allowed in a secure-boot environment; without that capability, such operations are denied. The idea is that if the kernel detects that it has been booted via the UEFI secure-boot mechanism, then this capability is disabled for all processes. In turn, the lack of that capability is intended to prevent operations that can modify the running kernel. CAP_COMPROMISE_KERNEL is not yet part of the mainline kernel, but already exists as a patch in the Fedora distribution and Matthew Garrett is working towards its inclusion in the mainline kernel. H. Peter Anvin wondered whether CAP_SYS_RAWIO did not already suffice for Kees's purpose. In response, Kees argued that CAP_SYS_RAWIO is for governing reads: "writing needs a much stronger check". Kees went on to elaborate: This in turn led to a short discussion about whether a capability was the right way to achieve the goal of restricting certain operations in a secure-boot environment. Kees was inclined to think it probably was the right approach, but deferred to Matthew Garrett, implementer of much of the secure-boot work on Fedora. Matthew thought that a capability approach seemed the best fit, but noted: In the current mainline kernel, the CAP_SYS_RAWIO capability is checked in the msr_open() function: if the caller has that capability, then it can open the MSR device and perform reads and writes on it. The purpose of Kees's patch is to add a CAP_COMPROMISE_KERNEL check on each write to the device, so that in a secure-boot environment the MSR devices are readable, but not writeable. The problem that Matthew alludes to is that this approach has the potential to break user space because, formerly, there was no capability check on MSR writes. An application that worked prior to the introduction of CAP_COMPROMISE_KERNEL can now fail in the following scenario: The last of the above steps would formerly have succeeded, but, with the addition of the CAP_COMPROMISE_KERNEL check, it now fails. In a subsequent reply, Matthew noted that QEMU was one program that was broken by a scenario similar to the above. Josh Boyer noted that Fedora has had a few reports of applications breaking on non-secure-boot systems because of scenarios like this. He highlighted why such breakages are so surprising to users and why the problem is seemingly unavoidable: Really though, the main issue is that you cannot introduce new caps to enforce finer grained access without breaking something. Shortly afterward, Peter stepped back to ask a question about the bigger picture: why should CAP_SYS_RAWIO be allowed on a secure-boot system? In other words, rather than adding a new CAP_COMPROMISE_KERNEL capability that is disabled in secure-boot environments, why not just disable CAP_SYS_RAWIO in such environments, since it is the possession of that capability that permits compromising a booted kernel? That led Matthew to point out a major problem with CAP_SYS_RAWIO: To see what Matthew is talking about, we need to look at a little history. Back in January 1999, when capabilities first appeared with the release of Linux 2.2, CAP_SYS_RAWIO was a single-purpose capability. It was used in just a single C file in the kernel source, where it governed access to two system calls: iopl() and ioperm(). Those system calls permit access to I/O ports, allowing uncontrolled access to devices (and providing various ways to modify the state of the running kernel); hence the requirement for a capability in order to employ the calls. The problem was that CAP_SYS_RAWIO rapidly grew to cover a range of other uses. By the time of Linux 2.4.0, there were 37 uses across 24 of the kernel's C source files, and looking at the 3.9-rc2 kernel, there are 69 uses in 43 source files. By either measure, CAP_SYS_RAWIO is now the third most commonly used capability inside the kernel source (after CAP_SYS_ADMIN and CAP_NET_ADMIN). CAP_SYS_RAWIO seems to have encountered a fate similar to CAP_SYS_ADMIN, albeit on a smaller scale. It has expanded well beyond its original narrow use. In particular, Matthew noted: Peter had some choice words to describe the abuse of CAP_SYS_RAWIO to protect operations on SCSI devices. The problem, of course, is that in order to perform relatively harmless SCSI operations, an application requires the same capability that can trivially be used to damage the integrity of a secure-boot system. And that, as Matthew went on to point out, is the point of CAP_COMPROMISE_KERNEL: to disable the truly dangerous operations (such as MSR writes) that CAP_SYS_RAWIO permits, while still allowing the less dangerous operations (such as the SCSI device operations). All of this leads to a conundrum that was nicely summarized by Matthew. On the one hand, CAP_COMPROMISE_KERNEL is needed to address the problem that CAP_SYS_RAWIO has become too diffuse in its meaning. On the other hand, the addition of CAP_COMPROMISE_KERNEL checks in places where there were previously no capability checks in the kernel means that applications that drop all capabilities will break. There is no easy way out of this difficulty. As Peter noted: "We thus have a bunch of unpalatable choices, **all of which are wrong**". Some possible resolutions of the conundrum were mentioned by Josh Boyer earlier in the thread: CAP_COMPROMISE_KERNEL could be treated as a "hidden" capability whose state could be modified only internally by the kernel. Alternatively, CAP_COMPROMISE_KERNEL might be specially treated, so that it can be dropped only by a capset() call that operates on that capability alone; in other words, if a capset() call specified dropping multiple capabilities, including CAP_COMPROMISE_KERNEL, the state of the other capabilities would be changed, but not the state of CAP_COMPROMISE_KERNEL. The problem with these approaches is that they special-case the treatment of CAP_COMPROMISE_KERNEL in a surprising way (and surprises in security-related APIs have a way of coming back to bite in the future). Furthermore, it may well be the case that analogous problems are encountered in the future with other capabilities; handling each of these as a special case would further add to the complexity of the capabilities API. The discussion in the thread touched on a number of other difficulties with capabilities. Part of the solution to the problem of the overly broad effect of CAP_SYS_RAWIO (and CAP_SYS_ADMIN) might be to split the capability into smaller pieces—replace one capability with several new capabilities that each govern a subset of the operations governed by the old capability. Each privileged operation in the kernel would then check to see whether the caller had either the old or the new privilege. This would allow old binaries to continue to work while allowing new binaries to employ the new, tighter capability. The risk with this approach is, as Casey Schaufler noted, the possibility of an explosion in the number of capabilities, which would further complicate administering capabilities for applications. Furthermore, splitting capabilities in this manner doesn't solve the particular problem that the CAP_COMPROMISE_KERNEL patches attempt to solve for CAP_SYS_RAWIO. Another general problem touched on by Casey is that capabilities still have not seen wide adoption as a replacement for set-user-ID and set-group-ID programs. But, as Peter noted, that may well be With 502 uses in the 3.9-rc2 kernel, CAP_SYS_ADMIN is the most egregious example of this problem. That problem itself would appear to spring from the Linux kernel development model: the decisions about which capabilities should govern new kernel features typically are made by individual developer in a largely decentralized and uncoordinated manner. Without having a coordinated big picture, many developers have adopted the seemingly safe choice, CAP_SYS_ADMIN. A related problem is that it turns out that a number of capabilities allow escalation to full root privileges in certain circumstances. To some degree, this is probably unavoidable, and it doesn't diminish the fact that a well-designed capabilities scheme can be used to reduce the attack surface of applications. One approach that might help solve the problem of overly broad capabilities is hierarchical capabilities. The idea, mentioned by Peter, is to split some capabilities in a fashion similar to the way that the root privilege was split into capabilities. Thus, for instance, CAP_SYS_RAWIO could become a hierarchical capability with sub-capabilities called (say) CAP_DANGEROUS and CAP_MOSTLY_HARMLESS. A process that gained or lost CAP_SYS_RAWIO would implicitly gain or lose both CAP_DANGEROUS and CAP_MOSTLY_HARMLESS, in the same way that transitions to and from an effective user ID of 0 grant and drop all capabilities. In addition, sub-capabilities could be raised and dropped independently of their "siblings" at the same hierarchical level. However, sub-capabilities are not a concept that currently exists in the kernel, and it's not clear whether the existing capabilities API could be tweaked in such a way that they could be implemented sanely. Digging deeper into that topic remains an open challenge. The CAP_SYS_RAWIO discussion touched on a long list of difficulties in the current Linux capabilities implementation: capabilities whose range is too broad, the difficulties of splitting capabilities while maintaining binary compatibility (and, conversely, the administrative difficulties associated with defining too large a set of capabilities), the as-yet poor adoption of binaries with file capabilities vis-a-vis traditional set-user-ID binaries, and the (possible) need for an API for hierarchical capabilities. It would seem that capabilities still have a way to go before they can deliver on the promise of providing a manageable mechanism for providing discrete, non-elevatable privileges to applications. John started by reviewing the existing Android kernel patches by category, starting with the core code: the binder interprocess communication mechanism, the ashmem shared memory mechanism, the Android logger, and monotonic event timestamps. The timestamp patch is needed to get timestamps from the monotonic clock for input events; otherwise it is hard to be sure of the timing between events, which makes gesture recognition hard. The problem is that these events cannot be added without breaking the kernel's ABI, so they cannot be just merged without further consideration. There is a set of changes that John categorized as performance and power-consumption improvements. At the top of the list is the infamous "wakelock" mechanism, used by Android to know when the system as a whole can be suspended to save power. There is a special alarm device that can generate alarms that will wake the system from a suspended state. The Android low-memory killer gets rid of tasks when memory gets tight; it is designed to activate more quickly than the kernel's out-of-memory killer, which will not act until a memory shortage is seriously affecting system performance. Also in this category is the interactive CPU frequency governor, which immediately ramps the CPU up to its maximum speed in response to touch events; its purpose is to help the system provide the fastest response possible to user actions. The "debugging features" category includes a USB gadget driver that supports communication with the adb debugging tools; it is also used to support file transfer using the media transfer protocol (MTP). The FIQ debugger is a low-level kernel debugger with some unique features — communication through the device's headphone jack being one of them. The RAM console will save kernel messages for later recovery in case of a crash. There is the "key-reset" driver, a kind of "control-alt-delete for phones." The patches to the ARM architecture's "embedded trace macrocell" and "embedded trace buffer" drivers offer improved logging of messages from peripheral processors. Then there is the "goldfish" emulator, derived from QEMU, which allows Android to be run in an emulated mode on a desktop system. The list of networking features starts with the "paranoid networking framework," the mechanism that controls which applications have access to the network; it restricts that access to members of a specific group. There is a set of netfilter changes mostly aimed at providing better accounting for which applications are using data. There are some Bluetooth improvements and the Broadcom "bcmhd" WiFi driver. In the graphics category is the ION memory allocator, which handles DMA buffer management. The "sync" driver provides a sort of mutex allowing applications to wait for a vertical refresh cycle. There is also a miscellaneous category that includes the battery meta-driver, which provides wakelock support and thermal management. That category contains various touch screen drivers, the "switch" class for dealing with physical switches, and the timed GPIO facility as well. Finally, the list of deprecated features includes the PMEM memory allocator, the early suspend mechanism, the "apanic" driver, and the yaffs2 filesystem, which has been replaced by ext4. Having passed over the long list of Android patches, John moved on to discuss where each stands with regard to upstreaming. The good news is that some of these features are already upstream. Wakelocks are, arguably, the most important of those; Rafael Wysocki's opportunistic suspend work, combined with a user-space emulation library, has made it possible for Android to move over to a mainline-based solution. John's monotonic event timestamp patches are also in the mainline, controlled by a special ioctl() command to avoid breaking the ABI; Android is using this mechanism as of the 4.2 ("Jelly Bean") release. The RAM console functionality is available via the pstore mechanism. The switch class is now supported via the kernel's "extconn" driver, but Android is not yet using this functionality. A number of the Android patches are currently in the staging tree. These include the binder, ashmem, the logger, the low-memory killer, the alarm device, the gadget device, and the timed GPIO feature. The sync driver was also just pulled into the staging tree for merging in the 3.10 development cycle. With all of the staging code, John said, Android "just works" on a mainline kernel. That does not mean that the job is done, though; quite a few Android patches are still in need of more work to get upstream. One such patch is the FIQ debugger; work is being done to integrate it with the kdb debugger, but, among other problems, the developers are having a hard time getting review attention for their patches. The key-reset driver was partially merged for the 3.9 kernel, but there are a number of details to be dealt with still. The plan for the low-memory killer is to integrate it with the mempressure control group patch and use the low-memory notification interface that is part of that mechanism; the developers hope to merge that code sometime soon. Ashmem is to be reimplemented via one of the volatile ranges patch sets, but there is still no agreement on the right direction for this feature. Much of the goldfish code has been merged for the 3.9 release. The ION memory allocator has not yet been submitted for consideration at all. Much of this code duplicates what has been done with the CMA allocator and the DMA buffer sharing mechanism; integrating everything could be a challenge. There should be pieces that can be carved out and submitted, John said, even if the whole thing requires more work. The interactive CPU frequency driver has been rejected by the scheduler developers in its current form. Supporting this feature properly could require some significant reworking of the scheduler code. The netfilter changes have been submitted for inclusion, but there is some cleanup required before they can be merged. The paranoid networking code, instead, is not appropriate for upstream and will not be submitted. The right solution here would appear to be for Android to use the network namespaces feature, but that would require some big changes on the Android side, so it is not clear when it might happen. The alarm device code needs to be integrated with the kernel's timerfd subsystem. Much of that integration has been done, but it requires an Android interface change, which is slowing things down. The embedded trace driver changes have been submitted, but the developer who did that work has moved on, so the code is now unmaintained. It is also undocumented and nobody else fully understands it at this point. There is a desire to replace the Android gadget driver with the CCG ("configurable composite gadget") code that is currently in the staging tree, but CCG does not yet do everything that Android needs, and it appears to be unmaintained as well. There was talk in the session of Linaro possibly taking over the development of that driver in the future. Finally, it would be good to get the binder and logger patches out of the staging tree. That, however, is "complicated stuff" and may take a while. There is hope that the upcoming patches to support D-Bus-like communication mechanisms in the kernel will be useful to provide binder-like functionality as well. There are a few issues needing longer-term thought. The integration of the sync driver and the DMA buffer sharing mechanism is being thought through now; there are a lot of details to be worked out. The upstreaming of ION could bring its own challenges. Much of that code has superficial similarities to the GEM and TTM memory managers that already exist in the kernel. Figuring out how to merge the interactive CPU frequency driver is going to be hard, even before one gets into details like how it plays with the ongoing big.LITTLE initiative. Some fundamental scheduler changes will be needed, but it's not clear who is going to do this work. The fact that Google continues to evolve its CPU frequency driver is not helping in this regard. There will, in other words, be plenty to keep developers busy for some time. In total, John said, there are 361 Android patches for the kernel, with the gadget driver being the largest single chunk. Some of these patches are quite old; one of the patches actually predates Android itself. Google is not standing still; there is new code joining that which has been around for a while. Current areas of intensive development include ION, the sync driver, the CPU frequency driver, the battery driver, and the netfilter code. While some of the code is going into the mainline, the new code adds to the pile of out-of-tree patches shipped by the Android project. Why should we worry about this, John asked, when it really is just another one of many forks of the kernel? Forking is how development gets done; see, for example, the development of the realtime patches or how many filesystems are written. But, he said, forks of entire communities, where code does not get merged back, are more problematic. In this case, we are seeing a lot of ARM systems-on-chip being developed with Android in mind from the beginning, leading to an increase in the use of out-of-tree drivers and kernels. Getting the Android base into the mainline makes it easier for developers to work with, and makes it easier to integrate Android-related code developed by others. John would like Android developers to see the mainline kernel, rather than the Android world, as their community. Things are getting better; Zach Pfeffer pointed out that the work being done to bring Android functionality into the mainline kernel is, indeed, being used by the Android team. The relationship between that team and the kernel development community is getting better in general. It is a good time for people who are interested to join the effort and help get things done. [Your editor would like to thank Linaro for travel assistance to attend this event.] Patches and updates Kernel trees Architecture-specific Core kernel code Development tools Device drivers Documentation Filesystems and block I/O Memory management Networking Virtualization and containers Miscellaneous Page editor: Jonathan Corbet Distributions The March 13 release of openSUSE 12.3 comes just six months after its predecessor, which is a bit quicker than the target of eight months between releases that the project has set. But the shorter development cycle does not mean that openSUSE 12.3 is lacking for new features. From the kernel up through the desktops and applications, 12.3 offers much that is new. The project was nice enough to provide members of the press with early access to the 12.3 final release. The distribution comes in multiple flavors, of course; I tried the Live KDE version to get a feel for the new release. It has been many years since I ran openSUSE, and I never ran it in anger, so I tried to put it through its paces a bit over the five or six days since it was made available. Since a Live distribution is somewhat cumbersome to use as a regular system, I opted to install it as a dual-boot system with Fedora on my trusty laptop. While I was ultimately successful in getting things installed that way, it took a rather extensive detour through GRUB 2, GUID partition table (GPT) partitions, resize2fs, and so on to get there. It's not clear that openSUSE or its installer were the only culprits, as I have dark suspicions about the BIOS on the laptop, but it is clear that allowing the installer to write to the master boot record (MBR) in a dual-Linux setup leads to an unbootable system—at least it did for me, and more than once. It should be noted, though, that the Live media was quite useful in helping to recover from that state as it had all of the GRUB 2 tools and GPT-aware utilities needed to fix things up. One new thing that came in with 12.3 is a change to Live media. It is now nearly 1G in size, which means it won't fit on a CD—either DVD or USB sticks must be used instead. That extra space allowed for additional packages, including LibreOffice 3.6 and OpenJDK 7, though not GIMP 2.8 as promised in the RC2 news item. Installation was straightforward, with the only "tricky" piece being the partition and filesystem layout. 12.3 gives the option of using Btrfs for all non-boot filesystems, which seemed worth trying. I haven't done anything particularly interesting with Btrfs (yet), but it seems to be working just fine for / and /home. Other than some cosmetic differences (theme, background, and so on), openSUSE 12.3 didn't seem much different from Fedora 18 once I logged into the KDE desktop (or Plasma workspace if that's the new terminology). It comes with KDE 4.10, which is more recent than Fedora's 4.9, but that difference was not particularly obvious. It works well for the limited desktop use cases I need—terminal windows, a browser, email client, and so on. I was able to use the Dolphin file manager to mount and access the encrypted /home that I use on the Fedora side, for example, which was convenient, but I still haven't gotten the hang of KDE Activities. KDE is not the only desktop available for openSUSE 12.3; there is, of course, a GNOME version of the distribution based on GNOME 3.6. Community manager Jos Poortvliet put together a lengthy preview of openSUSE 12.3 for desktop users that covers both desktops. KDE was chosen as the default for openSUSE back in 2009, but its GNOME support is said to be top-notch as well. UEFI secure boot support is available in 12.3, and the systemd integration that started in earlier versions has been completed. The switch to MariaDB as the "default MySQL" has been completed. MySQL is still available, but MariaDB has been chosen as a more community-oriented, drop-in replacement for MySQL. The kernel is fairly recent, based on 3.7. It exhibited the same annoying blinking WiFi indicator behavior that I have seen on the laptop with other recent kernels, though it was easy set a driver parameter for iwlegacy and get rid of it. In fact, the same file I used on the Fedora side (with a minor name change) just dropped into /etc/modprobe.d on openSUSE. Perhaps that's not surprising, but it is indicative of how it felt to use 12.3; it was often hard to remember that I wasn't still running Fedora. Some adjustments were needed (e.g. retraining fingers to type "zypper" rather than "yum"), but the two distributions are quite similar. There are a few oddities. The default is for the primary user to be logged in automatically, which doesn't seem like the most secure of choices. Installing Emacs led to a complaint about a lack of Asian fonts for Java. The auto-lock-screen appears not to work, as any key will unlock the screen, which seems to be a known problem, though it doesn't start working after 60 seconds for me. But those are pretty minor. A more substantive complaint could be made about one of the more advanced features being touted for the release: using the Open Build Service (OBS) to get the latest and greatest packages. There is even a video in that news item describing how to use software.opensuse.org to update LibreOffice from the 3.6 version that comes with 12.3 to LibreOffice 4.0. Perhaps LibreOffice was a poorly chosen example, but the video paints a picture that is very different from what a user will actually run into. In fact, it stops before things get interesting. The "one click install" offered does bring up the YaST software installer, but there are many more clicks ahead. If it were just extra clicks, it would be a pretty minor issue, but the new package conflicts with the old LibreOffice, so the user needs to make a decision about what to do—without a reasonable default (like "go ahead and break LibreOffice 3.6"). Beyond that, the upgrade caused YaST to choose an enormous number (over 100) of additional packages to install, many of which (telnet, screen, GIMP, ...) seemed to have nothing to do with LibreOffice. Licenses for Flash and Fluendo GStreamer plugins had to be clicked through as well. That said, once the process was complete, LibreOffice 4.0 was up and running on the system, it was just a lot more complicated than the video (which does feature some amusing Geeko animation) depicted. But openSUSE is not specifically targeted at non-technical users, and anyone who has used Linux before has likely run into these kinds of issues once or twice. For technically savvy users, openSUSE provides a solid operating system with the ability to get bleeding-edge applications via OBS. For Fedora users, a switch will probably be uneventful, while other distribution users (non-systemd, .deb-based, or build-it-from-quarks-and-gluons, for example) may have some adjustments to make. It's not clear that there is a strong reason to do so, but if some "distro hopping" is in your plans, openSUSE should certainly be on the list. But for those who already use it, openSUSE 12.3 will be a welcome upgrade. Brief items Distribution News Debian GNU/Linux Full Story (comments: none) Newsletters and articles of interest? Page editor: Rebecca Sobol Development The GNU Compiler Collection (GCC) was, from its inception, written in C and compiled by a C compiler. Beginning in 2008, an effort was undertaken to change GCC so that it could be compiled by a C++ compiler and take advantage of a subset of C++ constructs. This effort was jump-started by a presentation by Ian Lance Taylor [PDF] at the June 2008 GCC summit. As with any major change, this one had its naysayers and its problems, as well as its proponents and successes. Taylor's slides list the reasons to commit to writing GCC in C++: The popularity of C++ and its superset relationship to C speak for themselves. In stating that the C subset of C++ is as efficient as C, Taylor meant that if developers are concerned about efficiency, limiting themselves to C constructs will generate code that is just as efficient. Having cleaner interfaces is one of the main advantages of C++, or any object-oriented language. Saying that C++ never requires "uglier" code is a value judgment. However, saying that it supports "cleaner code in several significant cases" has a deep history, best demonstrated by gengtype. According to the GCC Wiki: What had happened was that developers were emulating features such as garbage collection, a vector class, and a tree class in C. This was the "ugly" code to which Taylor referred. In his slides, Taylor also tried to address many of the initial objections: that C++ was slow, that it was complicated, that there would be a bootstrap problem, and that the Free Software Foundation (FSF) wouldn't like it. He addressed the speed issue by pointing out that the C subset of C++ is as efficient as C. As far as FSF went, Taylor wrote, "The FSF is not writing the code." The complexity of a language is in the eye of the beholder. Many GCC developers were primarily, or exclusively, C programmers, so of necessity there would be a time period in which they would be less productive, and/or might use C++ in ways that negated all its purported benefits. To combat that problem, Taylor hoped to develop coding standards that limited development to a subset of C++. The bootstrap problem could be resolved by ensuring that GCC version N-1 could always build GCC version N, and that they could link statically against libstdc++. GCC version N-1 must be linked against libstdc++ N-1 while it is building GCC N and libstdc++ N; GCC N, in turn, will need libstdc++ N. Static linking ensures that each version of the compiler runs with the appropriate version of the library. For many years prior to 2008, there had been general agreement to restrict GCC code to a common subset of C and C++, according to Taylor (via email). However, there was a great deal of resistance to replacing the C compiler with a C++ compiler. At the 2008 GCC summit, Taylor took a poll on how large that resistance was, and approximately 40% were opposed. The C++ boosters paid close attention to identifying and addressing the specific objections raised by C++ opponents (speed, memory usage, inexperience of developers, and so on), so that each year thereafter the size of the opposition shrank significantly. Most of these discussions took place at the GCC summits and via unlogged IRC chats. Therefore, the only available record is in the GCC mailing list archives. The first step, a proper baby step, was merely to try to compile the existing C code base with a C++ compiler. While Taylor was still at the conference, he created a gcc-in-cxx branch for experimenting with building GCC with a C++ compiler. Developers were quick to announce their intention to work on the project. The initial build attempts encountered many errors and warnings, which were then cleaned up. In June 2009, almost exactly a year from proposing this switch, Taylor reported that phase one was complete. He configured GCC with the switch enable-build-with-cxx to cause the core compiler to be built with C++. A bootstrap on a single target system was completed. Around this time, the separate cxx branch was merged into the main GCC trunk, and people continued their work, using the enable-build-with-cxx switch. (However, the separate branch was revived on at least one occasion for experimentation.) In May 2010, there was a GCC Release Manager Q&A on IRC. The conclusion from that meeting was to request permission from the GCC Steering Committee to use C++ language features in GCC itself, as opposed to just compiling with a C++ compiler. Permission was granted, with agreement also coming from the FSF. Mark Mitchell announced the decision in an email to the GCC mailing list on May 31, 2010. In that thread, Jakub Jelinek and Vladimir Makarov expressed a lack of enthusiasm for the change. However, as Makarov put it, he had no desire to start a flame war over a decision that had already been made. That said, he recently shared via email that his primary concern was that the GCC community would rush into converting the GCC code base to C++ "instead of working on more important things for GCC users (like improving performance, new functionality and so on). Fortunately, it did not happen." Richard Guenther was concerned about creating a tree class hierarchy: The efforts of the proponents to allay concerns, and the "please be careful" messages from the opponents give some indication of the other concerns. In addition to the issues raised by Taylor at the 2008 presentation, Jelinek mentioned memory usage. Others, often as asides to other comments, worried that novice C++ programmers would use the language inappropriately, and create unmaintainable code. There was much discussion about coding standards in the thread. Several argued for existing standards, but others pointed out that they needed to define a "safe" subset of C++ to use. There was, at first, little agreement about which features of C++ were safe for a novice C++ developer. Taylor proposed a set of coding standards. These were amended by Lawrence Crowl and others, and then were adopted. Every requirement has a thorough rationale and discussion attached. However, the guiding principle on maintainability is not the coding standard, but one that always existed for GCC: the maintainer of a component makes the final decision about any changes to that component. Currently, those who supported the changes feel their efforts provided the benefits they expected. No one has publicly expressed any dissatisfaction with the effort. Makarov was relieved that his fear that the conversion effort would be a drain on resources did not come to pass. In addition, he cites the benefits of improved modularity as being a way to make GCC easier to learn, and thus more likely to attract new developers. As far as speed goes, Makarov noted that a bootstrap on a multi-CPU platform is as fast as it was for C. However, on uniprocessor platforms, a C bootstrap was 30% faster. He did not speculate as to why that is. He also found positive impacts, like converting to C++ hash tables, which sped up compile time by 1-2%. This last work is an ongoing process, that Lawrence Crowl last reported on in October 2012. In keeping with Makarov's concerns, this work is done slowly, as people's time and interests permit. Of the initial desired conversions (gengtype, tree, and vector), vector support is provided using C++ constructs (i.e., a class) and gengtype has been rewritten for C++ compatibility. Trees are a different matter. Although they have been much discussed and volunteered for several times, no change has been made to the code. This adds credence to the 2010 contention of Guenther (who has changed his surname to Biener) that it would be difficult to do correctly. Reached recently, Biener stated that he felt it was too early to assess the impact of the conversion because, compared to the size of GCC, there have been few changes to C++ constructs. On the negative side, he noted (as others have) that, because of the changes, long-time contributors must relearn things that they were familiar with in the past. In 2008, 2009, and 2010, (i.e., at the beginning and after each milestone) Taylor provided formal plans for the next steps. There is no formal plan going forward from here. People will use C++ constructs in future patches as they deem necessary, but not just for the sake of doing so. Some will limit their changes to the times when they are patching the code anyway. Others approach the existing C code with an eye to converting code to C++ wherever it makes the code clearer or more efficient. Therefore, this is an ongoing effort on a meandering path for the foreseeable future. As the C++ project has progressed, some fears have been allayed, while some developers are still in a holding pattern. For them it is too soon to evaluate things definitively, and too late to change course. However, the majority seems to be pleased with the changes. Only time will tell what new benefits or problems will arise. Brief items Version 2.0 of the cross-platform open source softphone application Jitsi has been released. An announcement on the XMPP Foundation blog includes some details, such as: "one of the most prominent new features in the 2.0 release is Multiparty Video Conferencing. Such conferences can work in an ad-hoc mode where one of the clients relays video to everyone else, or in cases that require scalability, Jitsi can use the Jitsi Videobridge: an RTP relaying server controlled over XMPP." Other changes include support for the royalty-free VP8 and Opus codecs, and support for integrating with Microsoft Outlook. Additional details are listed at the Jitsi site. Version 198 of systemd has been released. The long list of changes in this release includes new ways to extend unit file configuration, dynamic runtime control of resource limits, a number of changes to nspawn, and "substantially larger unit test suite, but this continues to be work in progress." New maintainer Robin Green announced the availability of TopGit 0.9, the first new release of the patch queue management tool after a lengthy hiatus. The project has also moved to Github. Green notes: ." Full Story (comments: none) Version 24.3 of GNU Emacs has been released. Among the highlights are a new major mode for editing Python, an update to the Common Lisp emulation library, and the addition of generalized variables in core Emacs Lisp. Full Story (comments: none) Newsletters and articles At his blog, Richard Hughes outlines his designs for a plugin-capable software installer for GNOME. ." The gnome-software tool Hughes is prototyping is currently alpha-quality, but is available in the GNOME git repository. Andre Klapper announced that the door is now open to propose new platform-wide features to be added for GNOME 3.10, which is slated for a September 2013 release. New proposals should be added to the GNOME wiki, but Klapper notes that "Proposed features must have an assignee working on them. The proposal period is planned to end in about a month." Full Story (comments: none) Page editor: Nathan Willis Announcements Brief items Articles of interest Upcoming Events If your event does not appear here, please tell us about it. Page editor: Rebecca Sobol Linux is a registered trademark of Linus Torvalds
https://lwn.net/Articles/542257/bigpage
CC-MAIN-2017-30
refinedweb
12,999
58.62
To a certain extent, we can all be web publishers now: social media let’s us share words, pictures and videos, online office suites allow us to publish documents and spreadsheets, code repositories allow us to share code, sites like Shinyapps.io allow you to publish specific sorts of applications, and so on. So where do initiatives like a domain of one’s own come in, which provide members of a university (originally), staff and students alike, with a web domain and web hosting of their own? One answer is that they provide a place on the web for you to call your own. With a domain name registered (and nothing else – not server requirements, no applications to install) you can set up an email address that you and you alone own and use it to forward mail sent to that address to any other address. You can also use your domain as a forwarding address or alias for other locations on the web. My ouseful.info domain forwards traffic to a blog hosted on wordpress.com (I pay WordPress for the privilege of linking to my site there with my domain address); another domain I registered – f1datajunkie.com – acts as an alias to a site hosted on blogger.com. The problem with using my domains like this mean that I can only forward traffic to sites that other people operate – and what I can do on those sites is limited by those providers. WordPress is a powerful web publishing platform, but WordPress.com only offers a locked down experience with no allowances for customising the site using your own plugins. If I paid for my own hosting, and ran my own WordPress server, the site could be a lot richer. But then in turn I would have to administer the site for myself, running updates, being responsible – ultimately – for the security and resource provisioning of the site myself. Taking the step towards hosting your own site is a big one, for many people (I’m too lazy to host my own sites, for example…) But initiatives like Reclaim Hosting, and more recently OU Create (from Oklahoma University, not the UK OU), originally inspired by a desire to provide a personal playspace in which students could explore their own digital creativity and give them a home on the web in which they could run their own applications, eased the pain for many: the host could also be trusted, was helpful, and was affordable. The Oklahoma create space allows students to register a subdomain (e.g. myname.oucreate.com) or custom domain (e.g. ouseful.info) and associate it with what is presumably a university hosted serverspace into which users can presumably install their own applications. So it seems to me we can tease apart two things: - firstly, the ability to own a bit of the web’s “namespace” by registering your own domain (ouseful.info, for example); - secondly, the ability to own a bit of the web’s “functionality space”: running your own applications that other people can connect to and make use of; this might be running your own possibly blogging platform, possibly customised using your own, or third party, extensions, or it might be running one or more custom applications you have developed on your own. But what if you don’t want the responsibility of running, and maintaining, your own applications day in, day? Or you’re running a netbook or tablet, and the application you want isn’t available as an app, just as a piece of “traditionally installed software”? I’ve started to think that docker style containers may offer a way of doing this. I’ve previously posted a couple of examples of how to run RStudio or OpenRefine via docker containers using a cloud host. How much nicer it would be if I could run such containers on a (sub)domain of my own running via a university host… Which is to say – I don’t necessarily want a full hosting solution on a domain of my own, at least, not to start with, but I do want to be able to add my own bits of functionality to the web, for short periods of time at the least. That is, what I’d quite like is a convenient place to “publish” (in the sense of “run”) my own containerised apps; and then rip them down. And then, perhaps at a later date, take them away and run them on my own fully hosted domain. 3 thoughts on “Getting Your Own Space on the Web…” Hi Tony – great post (as ever). I don’t do as much as you, but like you have a WordPress account which I pay for but I know I don’t really exploit fully. I’m not confident enough about installing plugins and stuff so really like the idea of being able to easily add bits of functionality for a long or short a period as you need them. Aggregation of stuff is still important to me which is why I like the about.me service and I guess in terms of my digital literacy and personality type I’m a bit of a tart cos I’ll try just about anything if it takes my fancy😀 Hi Sheila – for me, the disposability of docker containers is one of the attractions; if something doesn’t work, you just trash it. Here was one recipe for trying WordPress out (not sure if it works on Windows yet?): I appreciate it still includes some possibly scary command line foo, but kitematic/docker toolbox ( ) is getting easier and there may be a way of simplifying it further, either now or in near future, to just selecting a docker-compose file and automatically running it
https://blog.ouseful.info/2015/08/22/getting-your-own-space-on-the-web/
CC-MAIN-2019-51
refinedweb
963
52.23
You can subscribe to this list here. Showing 11 results of 11 I tried using the ZSH but had problems w/ the PATHs... not to mention a whole lot of other problems :( I'm swamped w/ admin work right now, tho. --- Tilman Utz <Tilman.Utz@...> wrote: > Hello, > just another question regarding a development environment for mingw > (respectively > working with gcc). What do you use? emacs? Where did you get it? > > Thanks for any suggestions > Tilman > > Georg Fusz schrieb: > > > I am using the Z-shell from > >. > > > > It works fine. > > > > But is there a shell, where I can copy parts of the output of commands to > build > > new inputs > > with mouse dragging? > > > > The compiling and linking I do with the build-in utilities of the EMACS. > > > > With the EMACS it easy to jump from the output of the compiler run to the > place > > in the source > > buffer where the error was made. > > > > -- > > Georg Fusz > > Technische Universitaet Berlin, Germany > > > > Fon: > > Uni.: +49 30 314 26 884 > > privat: +49 30 815 30 32 > > Handy: +49 173 20 10 696 > > > > > > _______________________________________________ > > MinGW-users mailing list > > MinGW-users@... > > > > You may change your MinGW Account Options at: > > > > > _______________________________________________ > MinGW-users mailing list > MinGW-users@... > > You may change your MinGW Account Options at: > ===== John van Vlaanderen ############################################# # CXN, Inc. Contact: john@... # # # Proud Sponsor of Perl/Unix of NY # # # ############################################# __________________________________________________ Do You Yahoo!? Get email at your own domain with Yahoo! Mail. i am currently trying to build a C++ dll (using dllimport/export) and gcc continuously bug. i look at mingw's gcc and happily see that's easier to make dll now. i just wonder if $ gcc -c foo.c $ gcc -shared -Wl,--implib,libfoo.a -o foo.dll foo.o generate relocatable DLL or not ? is there anyway to verify ot ? (with nm/objdump or something like this..) thnaks.. > Hmm... Works for me without problems. It only actually reports a segfault when run in gdb; otherwise I just have to watch the return code. This seems to be a common problem (at least with running mingwin programs under Cygwin bash). > How old are your MinGW headers? From the Cygwin package dated 20010130. > Do you have __MSVCRT__ defined by default? (touch nullfile.c && gcc -c > nullfile.c -mno-cygwin -E -dM) Yes. -- | certain, a. insufficiently analysed Hi, I am looking for a simple MIDI-playing example, compileable with Ming. = Also, can Bruno Desthuilliers please email me? I know you are = subscribed to this list, and I lost your email address. Sorry for the = inconvenience. Thanks! Greg Chicares <chicares@...> wrote: > Pedro A ARANDA wrote: > > > > 1) When compiling resources, I had to add a > > #define IDC_STATIC -1 > > which doesn't seem to be defined anywhere. > > This looks like a user-defined macro that is not a standard part > of windows. It is not part of WINAPI, but of MFC (Microsoft Foundation Classes). I wouldn't be suprised if the resource editor would use MFC-based definitions even when MFC is not used. To have access to it, you need to #include <afxres.h>, but you might not have this file if you don't have MFC installed. MFC is not implemented by Mingw. IDC_STATIC is the only IDC_ symbol defined by "afxres.h", the others are prefixed with AFX_IDC_. That's why I have the impression that IDC_STATIC should have been defined in the WINAPI headers, but M$ added the symbol only later, and it added it to MFC. > > 2) The new M$ tools to edit resources seem to add an additional > > parameter to the FONT definition in DIALOG resources and windres > > chokes at that. Just an example of the offending line > > > > FONT 8, "MS Sans Serif", 0, 0,0x1 > > The only ms documentation I can easily put my hands on doesn't > mention any extra parameters: > > FONT pointsize, "typeface" > Can you point to public documentation of this new syntax? I don't know about this one, but it might be as well a MFC extension, recognized by the their resource compiler. Cosmin Jim Roy wrote: > > Hi all, > > How do I make my program deal with data files which > have embedded ^Z ? > > As I understand it, in the windows world, this is an > issue of whether you open the file in text mode or not. > > Is there a compiler switch that forces binary mode? > > In case it's not clear, my specific problem is this. > I tell read() to get say... 200 bytes. If there > is an EOF in there, it returns everything up to > the EOF, yet the file pointer is advanced 200 bytes. > I can't believe I have to kludge in a bunch > of file pointer manipulation to work around this. > You can have the following code in a separate source/object and add the object to the link step or just add the code to the main() source file. Note: this also affects stdin, stdout and stderr. #include <stdlib.h> _fmode = _O_BINARY; Earnie. _________________________________________________________ Do You Yahoo!? Get your free @yahoo.com address at Reuben Thomas wrote: > > I'm trying to use gcc (2.95.2-9 or 2.95.3.x) -mno-cygwin under Cygwin 1.1.8 > and having problems seemingly related to the declaration of struct stat. For > example, the following program segfaults: > > #include <stdio.h> > #include <sys/stat.h> > #include <dirent.h> > > int main(void) > { > DIR *dir = opendir("."); > return 0; > } > > and I can't see any reason why it should (compiled for Cygwin, it works fine). > > I compiled with: > > gcc -o opendir opendir.c -mno-cygwin -mwin32 > > As far as I can see the problem occurs because the struct stat declaration > that the compiler gets isn't the same as the one used by the relevant > library, so the stat is overfilled (with a _stati64), and the stack is > trashed. I confirmed this by using a structure like this: > > struct foo { double pad1; struct stat s; double pad2; } > > so it was the padding that got overwritten, and the stack wasn't trashed. > > Is this going to be fixed soon? I'm the Windows maintainer for the Glasgow > Haskell Compiler, and we can't build our standard libraries at the moment > because of this problem. Or is there some workaround or fix I can apply? Or > am I just doing something wrong? > Hmm... Works for me without problems. How old are your MinGW headers? Do you have __MSVCRT__ defined by default? (touch nullfile.c && gcc -c nullfile.c -mno-cygwin -E -dM) Earnie. _________________________________________________________ Do You Yahoo!? Get your free @yahoo.com address at ----- Original Message ----- From: "Javier Gonz=E1lez" <xaviergonz@...> To: "Mingw list" <mingw-users@...> Sent: Tuesday, March 27, 2001 10:28 PM Subject: [Mingw-users] other win32 port of utils? > Hello, maybe this is not very related to mingw32, but i didn't found > anywhere else to ask... > where can i find a win32 port of the utils: > sed > diff > patch > > thnx a lot :) > > _______________________________________________ > MinGW-users mailing list > MinGW-users@... > > You may change your MinGW Account Options at: > > --- jsvendsen@... wrote: > have found that the sed that is distributed with cygwin is more dependable than other "native" versions. Danny _____________________________________________________________________________ - My Yahoo! - Have news, stocks, weather, sports and more in one place. Static constant initialisation of data in C++ classes works when linking statically, but not with dllimported classes. This is a bug with older versions of gcc as well as gcc-2.95.3. The following code used to build dll: dllclass.h ====================================== #if BUILDING_DLL # define DLLIMPORT __declspec (dllexport) #else /* Not BUILDING_DLL */ # define DLLIMPORT __declspec (dllimport) #endif /* Not BUILDING_DLL */ class DLLIMPORT DllClass { public: DllClass(); unsigned int a_method () const; static int non_const_int; /* initialised in dllclass.cc */ static const unsigned int const_int=256; char buffer[const_int]; }; ========================================== dllclass.cc =========================================== #include "dllclass.h" #include <string.h> DllClass::DllClass(){ memset(buffer,0,const_int); } unsigned int DllClass::a_method () const { return const_int; } int DllClass::non_const_int; ============================================ Dll build correctly. non_const_int is exported as DATA. const_int is not exported. That's fine. This is client code: usedll.cc ========================================= #include <stdio.h> #include "dllclass.h" int main () { DllClass A; printf("a_method = %d\n", A.a_method()); } ========================================== This fails to compile with error: dllclass.h:13: initialized variable `const int DllClass::const_int' is marked dllimport In this case, (integral const), one workaround is the enum hack. - static const unsigned int const_int=256; + enum {const_int=256}; The problem occurs because class members get the dllimport/export status of their class. IMO static const data members of classes initialised in class definition should not "inherit" the dllimport attribute of their class. The following w32-specific patch to gcc/config/i386/winnt.c fixes the problem. I have tested with STLport, which uses static const initialisation of fmtflags (in ios_base) and locale categories, and no problems yet. However, I am very, very new to the insides of gcc and this patch probably breaks soemthing else. Can somebody who "knows what they are doing" check. --- gcc/config/i386/winnt.c.orig Wed Jan 19 19:30:10 2000 +++ gcc/config/i386/winnt.c Tue Mar 27 22:03:47 2001 @@ -250,6 +250,11 @@ i386_pe_dllimport_p (decl) context = associated_type (decl); if (context) { + /* Don't use context to mark initialised variables as dllimport */ + if (TREE_CODE (decl) == VAR_DECL + && (DECL_INITIAL (decl) + && ! TYPE_NEEDS_CONSTRUCTING (TREE_TYPE (decl)))) + return 0; imp = lookup_attribute ("dllimport", TYPE_ATTRIBUTES (context)); if (imp) Danny _____________________________________________________________________________ - My Yahoo! - Have news, stocks, weather, sports and more in one place. find it shockingly improbable that i should be the first to experience this.
http://sourceforge.net/p/mingw/mailman/mingw-users/?style=flat&viewmonth=200103&viewday=28
CC-MAIN-2015-40
refinedweb
1,560
76.62
- Advertisement Content Count20 Joined Last visited Community Reputation417 Neutral About Silamoth - RankMember Personal Information - InterestsDesign Programming Towers That Don't Like Each Other Has Officially Been Released!!!! Silamoth posted a topic in Your AnnouncementsHello all! My friend and I have just released our first game! The game is called Towers That Don't Like Each Other. In our game, you fight through levels in which you have to strategically buy soldiers in order to protect your tower and attack your enemy's tower. Your end goal is to defeat the Evil Lord Morgoroth. More information can be found here on itch.io. I hope you all enjoy it and at least give it a chance. Towers That Don't Like Each Other - A WIP Strategy Game Silamoth posted a topic in Your AnnouncementsIntroduction Hello! I'm a high schooler, and a friend and I are making a game! It's a strategy game called Towers That Don't Like Each Other. It's still a work-in-progress, but I figured I'd start posting about it. The game has been in development for about a year now. It started off with just me, but then my friend joined in to do some art. The premise of the game is simple: an evil guy has taken over the land, so you must defeat him. You battle through many levels in which you must spend your money wisely to send out soldiers to attack the enemy's soldiers. There are also some upgrades you can buy if you save up your money throughout the game. You must ration your money well, though, because it carries over throughout the game. If you make it to the end, there's an epic final battle against the evil Lord Morgoroth. The actual mechanics of the game are a little hard to put into words, but you can basically send out soldiers from your tower to fight enemies sent out from the enemy tower. The goal is to reach the enemy's tower and destroy it. The pictures below should help explain it a bit better. Purchasing The game isn't quite done yet. It's mostly done, but we want to do some more testing. We're shooting for an early fall release. Our plan is to release it on itch.io for the incredibly small price of $1. If anyone is interested in buying it, perhaps we'll open a pre-order, maybe even with a slight discount. That has yet to be sorted out, though. Videos We will be making some videos soon to show off what the game is like in better detail. If you're interested, keep an eye on this thread. I'll be sure to post the videos here as soon as they're made. More Info If you want anymore information, please check out my website and keep an eye on this thread. Interview Homework Assignment Silamoth posted a topic in GDNet LoungeSo in my high school, we have a class that everyone has to take. The class is about preparing for college and careers. It's basically just a bunch of cringey, low-budget videos about jobs and college. In this class, we were recently assigned to interview someone in the field we intend to go into. So I was wondering if any game programmers wanted to answer the questions for me. 1. What is the most rewarding part of your job? 2. How demanding is your job? 3. What is your favorite part of your job? 4. What in the past has helped contribute most towards your job today? 5. How do you relax on your days off? 6. If you could change your career, would you? If so, what to? 7. What does a typical work day look like for you? 8. What is your work environment? 9. How did you obtain your current position? 10. What career paths are available in your company? Thanks to anyone who takes the time to respond to this. Small Game Team Silamoth replied to Space Sweatshop's topic in Hobby Project ClassifiedsI'm 16, and I've been programming for a couple years now. I mostly do C# with Mongame, but I also know Java and C++. I've made a few small unpolished games, and I'm currently working on a larger, more polished game. I'd be interested in joining your group. I'm pretty decent at programming. You also mentioned you know some stuff about audio. I'm currently trying to work on audio stuff for my current project. I'd enjoy talking to you about audio. I'd also appreciate talking to you and maybe using you as a tester. How do desginer design their game to be fun? Silamoth replied to Dovakhiin's topic in Game Design and TheoryI have to agree that getting people to play test is essential to making it fun and functional. You might think a feature is good, but others might not agree. Additionally, people can point out to you when things don't work the way they should. If you don't have many friends who are willing to play test it, make some new friends. Friends aren't limited just to people you know IRL. There's a whole community of people here. I'm sure some people here would be willing to help test your game and give you advice. Where to start with C# Silamoth replied to ZaTrox's topic in For Beginners's ForumI personally recommend the tutorials on this website : rbwhitaker.wikidot.com It goes over the basics (and some more advanced stuff) of programming in C#. It also had tutorials for Xna/MonoGame, which are graphics libraries for C# that allow you to make games. Monogame developer? Silamoth replied to LetsDoThis's topic in Hobby Project ClassifiedsI do most of my stuff in C# with MonoGame. I'd be interested in joining your group. Just out of curiosity, though, what kind of low-level stuff do you guys do with MonoGame? MonoGame is a rather high-level framework. Do you like modify the framework classes or something? C++ Going Beyond Basics Silamoth replied to Sora Keyheart's topic in For Beginners's ForumUnity has C# scripting and JavaScript scripting. It does not support Java. I'm not sure if that was a typo, but I don't think so since the OP was talking about knowing Java. Just wanna keep facts straight. Random Generation Issues Silamoth replied to Silamoth's topic in General and Gameplay ProgrammingWell, after taking a long break from this project, reading what you guys said, and looking back at my code, I have absolutely no clue what in the world I was doing when I wrote that code. I mean, seriously, the code looked like it was written by a newbie. Thanks for the help. I guess I just needed someone to make me realize how stupid I was being. :) Random Generation Issues Silamoth posted a topic in General and Gameplay ProgrammingSo I'm not an incredibly experienced programmer, but I know a thing or two, so I've been working on a little game that I don't really know what will happen with. It'll likely just end up being me messing around. One of the things I'm trying to implement is random terrain generation. I have it sort of implemented, but it's really...weird. Just so you know, it's written in C# with Monogame, and I'm using Visual Studio 2013 Express at the moment. Here's the code: using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Content; namespace Fantasy_RPG { class Tile { List<Texture2D> textureList; Texture2D tileTexture; const int TileWidth = 64; const int TileHeight = 64; private Vector2 position; public Tile(ContentManager content, Vector2 position) { this.position = position; textureList = new List<Texture2D>(); LoadTextures(content); Generate(); } void LoadTextures(ContentManager content) { textureList.Add(content.Load<Texture2D>("My Sprites/Terrain/Grass1")); textureList.Add(content.Load<Texture2D>("My Sprites/Terrain/Grass2")); } void Generate() { Random random = new Random(); int x = random.Next(0, textureList.Count); Console.WriteLine(x); for (int i = 0; i < textureList.Count; i++) { if (x == i) { tileTexture = textureList[i]; Console.WriteLine(i); } } } public void Draw(SpriteBatch spriteBatch) { spriteBatch.Draw(tileTexture, position, Color.White); } } } using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Content; namespace Fantasy_RPG { class TileGenerator { private List<Tile> tiles; public TileGenerator(ContentManager content) { tiles = new List<Tile>(); Populate(content); } void Populate(ContentManager content) { for (int x = 0; x <= 1440; x += 64) { for (int y = 0; y <= 900; y += 64) { tiles.Add(new Tile(content, new Vector2(x, y))); } } } public void Draw(SpriteBatch spriteBatch) { foreach (Tile tile in tiles) { tile.Draw(spriteBatch); } } } } This is then drawn properly in my Main class, but I don't think you'll want more code to read through . So this sort of works, but it's more like chunks. The way I have it right now, there are two textures: a light green and a dark green texture. The background is usually dominated mostly by one, with chunks of the other mixed in. Oddly enough, if I comment out the Console.WriteLine(x); and Console.WriteLine(i); lines in the Tile class, it randomly makes the entire background one of the colors. If I comment out either of these lines, it is either entirely dominated by one color or just about completely dominated by one color more so than it normally is. I know enough about programming to know that random generation is really pseudo-random and based on time, so I've deduced that that must be why those lines affect it. However, my question now is, how can I fix this to make it work to be fully random, regardless of time impacted by console output lines I was using for debugging? Thanks in advance! Monogame vs Otter Silamoth replied to Ovicior's topic in General and Gameplay ProgrammingI don't have any experience with Otter, and I'm certainly not one of the super-experienced guys on here. However, I have used Monogame, after messing with other frameworks, and I absolutely love Monogame. I can tell you that if you know how to program and are willing to do a bit of learning, using Monogame can be a great experience. I also want to talk about framework vs. engine. Think about what you would like to do. Do you want to worry about the design of a game and things like the story? If so, an engine like Otter might be a better choice. However, if you'd like to program the gameplay and worry about things like making a sword swing or making an enemy knowledgable enough to know when to attack, then a framework like Monogame might be a better choice. That's not to say there won't be overlap and that you can't worry about things like story of you use Monogame or low-level things like individual sword swings in Otter, but there is a difference in what you'll do. Engines are higher-level, as you probably know, so you'll worry less about small stuff and more about making a game. In the end, decide what you want to do and make your choice based in that. I hope this helps you at least somewhat. What should I learn before I create my own game engine? Silamoth replied to Maruiki's topic in For Beginners's ForumI don't necessarily have a of experience to speak from, but I can tell you that you should definitely evaluate what you are trying to do. A lot of game developers often say "Make games, not engines." In game programming, and honestly, in programming in general, some people get caught up in trying to write a codebase that is perfect and is easily to add new things into. Some people get caught up trying to make the perfect engine before even making the simplest of games. If you want to learn how this low-level stuff works, then fine, learn about game engines and how they work. However, if you want to make an actual game, then use a pre-made engine like Unity or use a framework like Monogame or SFML to program your game. - I did some even further research and found out that D3DXCOLOR is no longer supported. Why, I am not sure. I was able to use a float instead and it now works. Where to Start Silamoth replied to gprogrammer122's topic in For Beginners's ForumYeah bits and pieces from Stack Overflow can be very helpful. - Yes, here. I found an outdated header for DX9. Do you know why it isn't working? - Advertisement
https://www.gamedev.net/profile/219390-silamoth/
CC-MAIN-2019-22
refinedweb
2,155
66.13
Migrating from version 2 to version 3¶ The main change between version 2 and version 3 is the basic plotting library on which guiqwt is based on: - guiqwt version 2: depends on PyQwt, the Python bindings to Qwt C++ library – only supports PyQt4. - guiqwt version 3: depends on PythonQwt, a new library written from scratch to continue supporting Qwt API through a pure Python reimplementation of its main classes (QwtPlot, QwtPlotItem, QwtPlotCanvas, ...) – supports PyQt4, PyQt5 and PySide (PySide support is theoretical: not tested). Another major change is the switch from old-style to new-style signals and slots. The guiqwt.signals module is now empty because it used to collect strings for old-style signals: however, it still contains documentation on available signals. Examples¶ Switching from PyQwt to PythonQwt in your code: from PyQt4.Qwt5 import QwtPlot # PyQwt (supports only PyQt4) from qwt import QwtPlot # PythonQwt (supports PyQt4, PyQt5 and eventually PySide) Switching from guiqwt 2 to guiqwt 3: plot = get_plot_instance() # plot is a QwtPlot instance ## guiqwt 2: from guiqwt.signals import SIG_ITEM_MOVED plot.connect(plot, SIG_ITEM_MOVED, item_was_moved) ## guiqwt 3: plot.SIG_ITEM_MOVED.connect(item_was_moved)
https://pythonhosted.org/guiqwt/migrating_from_v2_to_v3.html
CC-MAIN-2019-04
refinedweb
184
51.99
The procedures in this section enable you to complete the following tasks. Configure Sybase ASE database access with Solstice DiskSuite/Solaris Volume Manager or VxVM. Create the Sybase ASE database environment. If you use the Solstice DiskSuite/Solaris Volume Manager, perform the following steps to configure Sybase ASE database access with the Solstice DiskSuite/Solaris Volume Manager. Configure the disk devices for the Solstice DiskSuite/Solaris Volume Manager software to use. See the Sun Cluster Software Installation Guide for Solaris OS for information on how to configure Solstice DiskSuite/Solaris Volume Manager. diskset. Specifies the name of the raw disk device within the metaset diskset. Verify that the changes are effective. If you use VxVM software, perform the following steps to configure Sybase ASE database access with the VxVM software. Configure the disk devices for the VxVM software to use. See the Sun Cluster Software Installation Guide for Solaris OS for information on how to configure VERITAS Volume Manager... Verify that the changes are effective. Reregister the disk device group with the cluster to keep the VxVM namespace consistent throughout the cluster. Before you perform this procedure,.
http://docs.oracle.com/cd/E19263-01/817-4650/6mk5m9gl4/index.html
CC-MAIN-2014-15
refinedweb
187
58.28
Hello! I want to add shadows and lighting to my game, but my problem is I don't know how to get depth component from a perspective other than main one. I thought ok, that's easy, an FBO and render,... Type: Posts; User: DirtyBlasion Hello! I want to add shadows and lighting to my game, but my problem is I don't know how to get depth component from a perspective other than main one. I thought ok, that's easy, an FBO and render,... Hi, there! I will put more code because it explains better than I would #include "Texture.h" #define STB_IMAGE_IMPLEMENTATION #include "..\stb_image.h" #include <iostream> ... Hi, I'm not the one that questioned, but you are "OpenGL Pro" so, you must know something. Never used that parameter, I used to replace it with nullptr, and do the same as mhagain said, but what I... So I want to recreate minecraft, I have created everything, it does create chunk shape, it draws it, but how I can put corresponding texture. What I'm thinking at, but I don't know how to apply is... I cant understand how I can transform a PNG in glTexImage2D image data, last parameter So I read a lot of things about textures, but it's still blocks me out... So please can somebody explain me something, on how it works? Impresive, I got my system actually worked, but I forgot to add things in drawplane. So I never used glm, because I considered my math is enough, anyways, I want to know how does your system works,... Hi there! These days I'm strugling with a fps camera style. here's my camera code void Camera::FirstPerson(SDL_Window* window) { SDL_GetMouseState(&mousex, &mousey); So I isntalled glew, all good, but my altgorithm didn't worked propely, and I put this in my script GLenum err = glewInit(); if(err != GLEW_OK) { cout << "Error(glew): "... So initialy I was starting with glut, but I read somethings and I think sfml and glew are a great combo. So I started, I did the basic things, but how I can draw with a function? I make void Draw();... Nobody? Please, help me! So I use freeglut. I have this class class PlayerClass { public: int x, y, z, xzdir = 0, ydir = 0; PlayerClass(int _x, int _y, int _z) { x = _x; ... #ifndef PLAYERCLASS_H_INCLUDED #define PLAYERCLASS_H_INCLUDED #include <iostream> #include <windows.h> #include <stdlib.h> #include <GL/glew.h> #include <GL/freeglut.h> #include <math.h> So I'm working with code blocks, on c++. I want to get started. I want to start a game without any engine and thing. A Minecraft like. I see some people use glut, others use glew, or glfw3. Whats...
https://www.opengl.org/discussion_boards/search.php?s=75168ecac2abc38c0c9b0f8205deea56&searchid=3234778
CC-MAIN-2018-30
refinedweb
457
84.37
Introduction to Leiningen for Clojure Last modified: February 18, 2019 1. Introduction Leiningen is a modern build system for our Clojure projects. It’s also written and configured entirely in Clojure. It works similarly to Maven, giving us a declarative configuration that describes our project, without needing to configure exact steps to be executed. Let’s jump in and see how to get started with Leiningen for building our Clojure projects. 2. Installing Leiningen Leiningen is available as a standalone download, as well as from a large number of package managers for different systems. Standalone downloads are available for Windows as well as for Linux and Mac. In all cases, download the file, make it executable if necessary, and then it’s ready to use. The first time the script is run it will download the rest of the Leiningen application, and then this will be cached from this point forward: $ ./lein Downloading Leiningen to /Users/user/.lein/self-installs/leiningen-2.8.3-standalone.jar now... ..... Leiningen is a tool for working with Clojure projects. Several tasks are available: ..... Run `lein help $TASK` for details. ..... 3. Creating a new Project Once Leiningen is installed, we can use it to create a new project by invoking lein new. This creates a project using a particular template from a set of options: - app – Used to create an application - default – Used to create a general project structure, typically for libraries - plugin – Used to create a Leiningen Plugin - template – Used to create new Leiningen templates for future projects For example, to create a new application called “my-project” we would execute: $ ./lein new app my-project Generating a project called my-project based on the 'app' template. This gives us a project containing: - A build definition – project.clj - A source directory – src – including an initial source file – src/my_project/core.clj - A test directory – test – including an initial test file – test/my_project/core_test.clj - Some additional documentation files – README.md, LICENSE, CHANGELOG.md and doc/intro.md Looking inside our build definition, we’ll see that it tells us what to build, but not how to build it: (defproject my-project "0.1.0-SNAPSHOT" :description "FIXME: write description" :url "" :license {:name "EPL-2.0 OR GPL-2.0-or-later WITH Classpath-exception-2.0" :url ""} :dependencies [[org.clojure/clojure "1.9.0"]] :main ^:skip-aot my-project.core :target-path "target/%s" :profiles {:uberjar {:aot :all}}) This tells us: - The details of the project consisting of the project name, version, description, homepage and license details. - The main namespace to use when executing the application - The list of dependencies - The target path to build the output into - A profile for building an uberjar Note that the main source namespace is my-project.core, and is found in the file my_project/core.clj. It’s discouraged in Clojure to use single-segment namespaces – the equivalent of top-level classes in a Java project. Additionally, the filenames are generated with underscores instead of hyphens because the JVM has some problems with hyphens in filenames. The generated code is pretty simple: (ns my-project.core (:gen-class)) (defn -main "I don't do a whole lot ... yet." [& args] (println "Hello, World!")) Also, notice that Clojure is just a dependency here. This makes it trivial to write projects using whatever version of the Clojure libraries are desired, and especially to have multiple different versions running on the same system. If we change this dependency, then we’ll get the alternative version instead. 4. Building and Running Our project isn’t worth much if we can’t build it, run it and package it up for distribution, so let’s look at that next. 4.1. Launching a REPL Once we have a project, we can launch a REPL inside of it using lein repl. This will give us a REPL that has everything in the project already available on the classpath – including all project files as well as all dependencies. It also starts us in the defined main namespace for our project: $ lein repl nREPL server started on port 62856 on host 127.0.0.1 - nrepl://127.0.0.1:62856 [=> (-main) Hello, World! nil This executes the function -main in the current namespace, which we saw above. 4.2. Running the Application If we are working on an application project – created using lein new app – then we can simply run the application from the command line. This is done using lein run: $ lein run Hello, World! This will execute the function called -main in the namespace defined as :main in our project.clj file. 4.3. Building a Library If we are working on a library project – created using lein new default – then we can build the library into a JAR file for inclusion in other projects. We have two ways that we can achieve this – using lein jar or lein install. The difference is simply in where the output JAR file is placed. If we use lein jar then it will place it in the local target directory: $ lein jar Created /Users/user/source/me/my-library/target/my-library-0.1.0-SNAPSHOT.jar If we use lein install, then it will build the JAR file, generate a pom.xml file and then place the two into the local Maven repository (typically under .m2/repository in the users home directory) $ lein install Created /Users/user/source/me/my-library/target/my-library-0.1.0-SNAPSHOT.jar Wrote /Users/user/source/me/my-library/pom.xml Installed jar and pom into local repo. 4.4. Building an Uberjar If we are working on an application project, Leiningen gives us the ability to build what is called an uberjar. This is a JAR file containing the project itself and all dependencies and set up to allow it to be run as-is. $ lein uberjar Compiling my-project.core Created /Users/user/source/me/my-project/target/uberjar/my-project-0.1.0-SNAPSHOT.jar Created /Users/user/source/me/my-project/target/uberjar/my-project-0.1.0-SNAPSHOT-standalone.jar The file my-project-0.1.0-SNAPSHOT.jar is a JAR file containing exactly the local project, and the file my-project-0.1.0-SNAPSHOT-standalone.jar contains everything needed to run the application. $ java -jar target/uberjar/my-project-0.1.0-SNAPSHOT-standalone.jar Hello, World! 5. Dependencies Whilst we can write everything needed for our project ourselves, it’s generally significantly better to re-use the work that others have already done on our behalf. We can do this by having our project depend on these other libraries. 5.1. Adding Dependencies to our Project To add dependencies to our project, we need to add them correctly to our project.clj file. Dependencies are represented as a vector consisting of the name and version of the dependency in question. We’ve already seen that Clojure itself is added as a dependency, written in the form [org.clojure/clojure “1.9.0”]. If we want to add other dependencies, we can do so by adding them to the vector next to the :dependencies keyword. For example, if we want to depend on clj-json we would update the file: :dependencies [[org.clojure/clojure "1.9.0"] [clj-json "0.5.3"]] Once done, if we start our REPL – or any other way to build or run our project – then Leiningen will ensure that the dependencies are downloaded and available on the classpath: $ lein repl Retrieving clj-json/clj-json/0.5.3/clj-json-0.5.3.pom from clojars Retrieving clj-json/clj-json/0.5.3/clj-json-0.5.3.jar from clojars nREPL server started on port 62146 on host 127.0.0.1 - nrepl://127.0.0.1:62146=> (require '(clj-json [core :as json])) nil my-project.core=> (json/generate-string {"foo" "bar"}) "{\"foo\":\"bar\"}" my-project.core=> We can also use them from inside our project. For example, we could update the generated src/my_project/core.clj file as follows: (ns my-project.core (:gen-class)) (require '(clj-json [core :as json])) (defn -main "I don't do a whole lot ... yet." [& args] (println (json/generate-string {"foo" "bar"}))) And then running it will do exactly as expected: $ lein run {"foo":"bar"} 5.2. Finding Dependencies Often, it can be difficult to find the dependencies that we want to use in our project. Leiningen comes with a search functionality built in to make this easier. This is done using lein search. For example, we can find our JSON libraries: $ lein search json Searching central ... [com.jwebmp/json "0.63.0.60"] [com.ufoscout.coreutils/json "3.7.4"] [com.github.iarellano/json "20190129"] ..... Searching clojars ... [cheshire "5.8.1"] JSON and JSON SMILE encoding, fast. [json-html "0.4.4"] Provide JSON and get a DOM node with a human representation of that JSON [ring/ring-json "0.5.0-beta1"] Ring middleware for handling JSON [clj-json "0.5.3"] Fast JSON encoding and decoding for Clojure via the Jackson library. ..... This searches all of the repositories that our project is working with – in this case, Maven Central and Clojars. It then returns the exact string to put into our project.clj file and, if available, the description of the library. 6. Testing our Project Clojure has built-in support for unit testing our application, and Leiningen can harness this for our projects. Our generated project contains test code in the test directory, alongside the source code in the src directory. It also includes a single, failing test by default – found in test/my_project/core-test.clj: (ns my-project.core-test (:require [clojure.test :refer :all] [my-project.core :refer :all])) (deftest a-test (testing "FIXME, I fail." (is (= 0 1)))) This imports the my-project.core namespace from our project, and the clojure.test namespace from the core Clojure language. We then define a test with the deftest and testing calls. We can immediately see the names of the test, and the fact that it’s deliberately written to fail – it asserts that 0 == 1. Let’s run this using the lein test command, and immediately see the tests running and failing: $. If we instead fix the test, changing it to assert that 1 == 1 instead, then we’ll get a passing message instead: $ lein test lein test my-project.core-test Ran 1 tests containing 1 assertions. 0 failures, 0 errors. This is a much more succinct output, only showing what we need to know. This means that when there are failures, they immediately stand out. If we want to, we can also run a specific subset of the tests. The command line allows for a namespace to be provided, and only tests in that namespace are executed: $ lein test my-project.core-test lein test my-project.core-test Ran 1 tests containing 1 assertions. 0 failures, 0 errors. $ lein test my-project.unknown lein test my-project.unknown Ran 0 tests containing 0 assertions. 0 failures, 0 errors. 7. Summary This article has shown how to get started with the Leiningen build tool, and how to use it to manage our Clojure based projects – both executable applications and shared libraries. Why not try it for out on the next project and see how well it can work.
https://www.baeldung.com/leiningen-clojure
CC-MAIN-2019-22
refinedweb
1,902
58.38
Starting the Synth Project We’re going to build this from scratch, so in order to not spend much time with UI issues, we are going to make use of AudioKit’s built-in UI elements that are normally used in playgrounds and our example apps. From within Xcode, create a new project with the single view application template. Give it a product name of “SenderSynth” (no spaces) and make it a Universal Swift application as shown below: Since Audiobus is most easily installed uing Cocoapods, we could use Cocoapods to install AudioKit, and eventually this tutorial will be updated as such, but for now, add AudioKit’s iOS project from the develop branch as a subproject. Set Up the Synth (easy!) Inside the ViewController.swift, first import AudioKit: import AudioKit Create the oscillator by adding it as an instance variable, class ViewController: UIViewController { let oscillator = AKOscillatorBank() and then use oscillator as AudioKit’s output and start things up: override func viewDidLoad() { super.viewDidLoad() AudioKit.output = oscillator AudioKit.start() } User Interface This tutorial will not use storyboards because they require too much mouse activity to describe, so instead we’ll build the UI programmatically. Next, build the views: override func viewDidLoad() { super.viewDidLoad() AudioKit.output = oscillator AudioKit.start() setupUI() } func setupUI() { let stackView = UIStackView() stackView.axis = .vertical stackView.distribution = .fillEqually stackView.alignment = .fill stackView.translatesAutoresizingMaskIntoConstraints = false let adsrView = AKADSRView() stackView.addArrangedSubview(adsrView) let keyboardView = AKKeyboardView() stackView.addArrangedSubview(keyboardView) view.addSubview(stackView) stackView.widthAnchor.constraint(equalToConstant: view.frame.width).isActive = true stackView.heightAnchor.constraint(equalToConstant: view.frame.height).isActive = true stackView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true stackView.centerYAnchor.constraint(equalTo: self.view.centerYAnchor).isActive = true } While this may seem like a lot of code, its a lot more reliable than describing how to do this with storyboards. The last step is to hook up controls. For the keyboard, make the view controller conform to the AKKeyboardDelegate protocol: class ViewController: UIViewController, AKKeyboardDelegate { and add these functions: func noteOn(note: MIDINoteNumber) { oscillator.play(noteNumber: note, velocity: 80) } func noteOff(note: MIDINoteNumber) { oscillator.stop(noteNumber: note) } and make the view controller the delegate for the keyboard inside viewDidLoad, right after the instantiation: let keyboardView = AKKeyboardView() keyboardView.delegate = self If you run your app now, it will respond to the keys, but the ADSR envelope won’t do anything. Replace the ADSR creation step with this one defining a code block: let adsrView = AKADSRView() { att, dec, sus, rel in self.oscillator.attackDuration = att self.oscillator.decayDuration = dec self.oscillator.sustainLevel = sus self.oscillator.releaseDuration = rel } Now you’re really done with all the AudioKit stuff. From here, it’s all inter-app audio. Installing Audiobus You will need Cocoapods to do this step. Close the project you created and open up a terminal and go to the projects folder and type: pod init Add a pod ‘Audiobus’ line to the Podfile that was just created in this folder: # Uncomment the next line to define a global platform for your project # platform :ios, '9.0' target 'SenderSynth' do # Comment the next line if you're not using Swift and don't want to use dynamic frameworks use_frameworks! # Pods for SenderSynth pod 'Audiobus' end Back on the commandline, > pod install This should work as follows: Analyzing dependencies Downloading dependencies Installing Audiobus (2.3.1) Generating Pods project Integrating client project It may also produce some warning messages which can be ignored for now. There are alternative installation instructions on the Audiobus integration page if you do not want to use Cocoapods. From now on, we will be working with the SenderSynth.xcworkspace file instead of the project file, so open that in Xcode now. Add the Audiobus Files Since Audiobus is not a Swift framework, we need to import the Audiobus header into a bridging header. There are a few ways to create a bridging header, but the way I recommend is to go to your app’s target Build Settings tab and search for “Bridging”. All of the settings will be filtered and you’ll be left with one remaining “Objective-C Bridging Header” setting in which you can paste “$(SRCROOT)/SenderSynth/SenderSynth-BridgingHeader.h” so that it looks like the following screenshot. Then create a new file, of type “Header File”, name it “SenderSynth-BridgingHeader.h” and add the import line so that it looks like: #ifndef SenderSynth_BridgingHeader_h #define SenderSynth_BridgingHeader_h #import "Audiobus.h" #endif /* SenderSynth_BridgingHeader_h */ Next grab the Audiobus.swift file from the AudioKit repository and place it in your project, creating a copy. Back in your ViewController.swift file: AudioKit.output = oscillator AudioKit.start() Audiobus.start() Project Settings You need to enable background audio and inter-app audio. Follow these steps to do so: Open your app target screen within Xcode by selecting your project entry at the top of Xcode’s Project Navigator, and selecting your app from under the “TARGETS” heading. Select the “Capabilities” tab. Underneath the “Background Modes” section, make sure you have “Audio, AirPlay, and Picture in Picture” ticked. To the right of the “Inter-App Audio” title, turn the switch to the “ON” position – this will cause Xcode to update your App ID with Apple’s “Certificates, Identifiers & Profiles” portal, and create or update an Entitlements file. Next, set up a launch URL: Open your app target screen within Xcode by selecting your project entry at the top of Xcode’s Project Navigator, and selecting your app from under the “TARGETS” heading. Select the “Info” tab. Open the “URL types” group at the bottom. Click the “Add” button at the bottom left. Then enter this identifier for the URL: io.audiokit.sendersynth Enter the new Audiobus URL scheme for your app, generally the name of the app, a dash, and then a version number: “SenderSynth-1.0.audiobus”. Of course when you do all this for a new app, you’ll need to have your new app’s name in these fields. Here is one step that is not documented on the Audiobus web site: - Give your app a bundle name. In the Info tab, you might see grayed out default text in the Identity section’s display name field. Go ahead and type or re-type the app’s name. Here I just added a space to call the app “Sender Synth”. More Project Settings (for Sender apps) Create your sender port by following these steps: “aurg”, which means a “Remote Generator” unit. “subtype” (of type String): set this to “sndx”, which just means “Sender Example”. “name” (of type String): set this to “AudioKit: Sender” “version” (of type Number): set this to an integer. “1” is a good place to start. In the end your Info.plist should now have the following: Audiobus and Registration Perhaps it goes without saying, but you need to have the Audiobus application installed on your device. Next, you’ll need create a user at developer.audiob.us. Next, back in Xcode, build the SenderSynth project and right click on the app in the Products directory, and “Show in Finder”. In the Finder, right click on the app and “Show Package Contents”. Using a web browser, go to the Audiobus Temporary Registration and drag the Info.plist file from this directory into the web page. Complete the temporary registration by choosing the SDK version you’re using, adding an icon to the sender port, and adding a title as shown: You will be given an API Key that will be good for 14 days. Copy the text of the key and create a new document of type “Other / Empty” and call it “Audiobus.txt”. Paste the API Key in that file. You should also click the “email this to me” link on the Audiobus registration page so that you can open up the email on your device and tap the link to add an entry to your local Audiobus app for the Sender Synth. When you’re ready to submit to the App Store and you have and App Store ID, make sure you get a new, permanent registration with Audiobus. Build the app to your device This is pretty straightforward, but you do need to make sure to give your app app icons. Conclusion (for Sender Apps) There, that wasn’t so hard was it? The next example is a Filter Effects app. I recommend that you work through that as well, even if you’re not going to build an effects/filter app, just to solidify some of the concepts.
http://audiokit.io/audiobus/sender-synth/
CC-MAIN-2017-22
refinedweb
1,412
55.54
Translation(s): none sbuild is used on the official buildd network to build binary packages for all supported architectures. It can also be used by individuals to test that their package builds in a minimal installation of Debian Unstable. In particular, this helps ensure that you haven't missed any build dependencies. The main alternative to sbuild is pbuilder combined with cowbuilder. This main part of this page is intended as a short guide to sbuild. It documents how to set up sbuild and build packages with it. The later parts of the page document optional enhancements to the simple setup described in the first section. If you use propellor to configure your development machine, its Propellor.Property.Sbuild module can perform most of this setup for you. Contents - Setup - Enhancements - Using lintian - Using piuparts - Using autopkgtest - Bind mounts - Customizations of sbuild chroots - External Commands - Using "ccache" with sbuild - Using eatmydata with sbuild - sbuild overlays in tmpfs - Enabling experimental - Build for experimental - Enabling incoming.debian.org - Disabling network access for dpkg-buildpackage - source only upload - Using aliases - Adding extra packages Setup Create the chroot To get started so you may build packages for Debian unstable, run the following. 1 sudo apt-get install sbuild 2 sudo mkdir /root/.gnupg # To work around #792100; not needed post-Jessie 3 sudo sbuild-update --keygen # Not needed since sbuild 0.67.0 (see #801798) 4 sudo sbuild-adduser $LOGNAME 5 ... *logout* and *re-login* or use `newgrp sbuild` in your current shell 6 sudo sbuild-createchroot --include=eatmydata,ccache,gnupg unstable /srv/chroot/unstable-amd64-sbuild 7 echo "union-type=aufs" | sudo tee -a /etc/schroot/chroot.d/unstable-amd64-sbuild-* # Only needed in jessie 8 Now for a brief explanation on what these commands do. The first line installs sbuild onto the system. The third line generates apt keys used internally by sbuild. (If you get an error about lack of entropy, do something else on the system, like browsing the web or running find /usr or so. Or skip down to creating the chroot, and come back to this step.) This only needs to be done once. The fourth line will add your username so that it may use the sbuild command. Additional users may be added by running sudo sbuild-adduser USER1 USER2 .... sbuild-adduser will prompt you to copy the template sbuild configuration in /usr/share/doc/sbuild/examples/example.sbuildrc to each user's ~/.sbuildrc, to be used as their user sbuild configuration. You can customize sbuild settings here, but you usually won't need to customize anything. This should be done once per user. The fifth line is to update the active user group set to include sbuild. The sixth line uses sbuild-createchroot to create a chroot used by sbuild meant for building packages targeting Debian unstable main. The chroot is saved in /srv/chroot/unstable-amd64-sbuild. It installs the packages ccache and eatmydata in the chroot in case you want to use some of the enhancements detailed below. The apt repository used is the mirror service which will choose a suitable local mirror automatically. This can be changed to use a URL for a different mirror of the Debian archive. You can run this command once per distribution you want, and pass --arch=i386 to create a chroot for a different architecture (the default is your host architecture). The command given above creates a type=directory chroot. If you are short of disc space, you can instead use the following command to create a chroot stored in a tarball at /srv/chroot/unstable-amd64-sbuild.tar.gz. This is not recommended unless you really can't spare the disc space, because several of the enhancements below depend on using a type=directory chroot. sudo sbuild-createchroot --make-sbuild-tarball=/srv/chroot/unstable-amd64-sbuild.tar.gz unstable `mktemp -d` Configuration If you're setting up sbuild for personal use, instead of as part of a build server, you might want to use the following options in your ~/.sbuildrc. These can also be set on the command line when running sbuild. The $build_arch_all variable will enable building of architecture independent packages by default. Since official build servers are used to build an existing package for a different architecture (e.g., the uploader builds for i386, uploads arch-i386 and arch-all binary packages, and a build server builds arch-amd64 packages), this is off by default. You can also enable this per build by passing -A to sbuild. The $build_source variable will enable building of source packages by default. Again, on official build servers, this isn't wanted, but for personal use it's generally useful. You can enable this per build with -s. The $distribution variable will set the distribution to build for as 'unstable'. You can set the distribution per build by passing it to the -d option. Be careful not to use -d just to select a specific chroot (use -c for that, see below), as it will override the distribution set in debian/changelog and may lead you to upload a package to a distribution it was not intended for. Updating The chroot should be up-to-date before building packages. Use the sbuild-update to perform updates. First, note the name of the sbuild chroot to be updated. All sbuild chroots built with sbuild-createchroot will have a suffix of '-sbuild' thus to find the names of all sbuild chroots, run the following. If you followed the setup instructions above, there should be one chroot named source:unstable-$arch-sbuild where $arch is the architecture installed on your machine. After noting the name of your sbuild chroot, run the following. The arguments '-udcar' will tell sbuild-update to run an apt-get update, dist-upgrade, clean, autoclean, and autoremove in the chroot. You can also pass --apt-update --apt-distupgrade to the individual sbuild invocation to update the temporary copy of the build chroot, but this won't cause any changes to happen in the persistent copy of the chroot (in the .tar.gz file). So if you are building more than once, you should run sbuild-update instead of relying on this. Building packages To build a package from the source directory of a debianized package, simply run the following. Alternatively, you may pass in the '.dsc' file of a package generated by dpkg-buildpackage, git-buildpackage, and so forth so that it may be built with sbuild. For example, to build sbuild from its '.dsc' file, do the following. To build packages available from the apt repositories used in the sbuild chroot, just pass in a package name (older versions of sbuild required $package_$version). For example to build the latest sbuild: Everything needed to build the latest sbuild version will be downloaded from the repositories and will be saved in your current directory after building of the packages is finished. If you want parallel build to be used, add a line like the following to ~/.sbuildrc: $ENV{'DEB_BUILD_OPTIONS'} = 'parallel=5'; Cleaning up schroot session Sometimes you can end up with dangling chroot sessions potentially taking up valuable system resources (find them with `schroot -l --all`). This command is useful: sudo schroot --end-session --all-sessions Enhancements Using lintian The use of lintian with sbuild can greatly aid with increasing the quality of Debian packages. To use lintian with sbuild, first install lintian. Next, edit your ~/.sbuildrc configuration file. Open ~/.sbuildrc with your favorite text editor and edit the lines with the following variables. The $run_lintian variable will enable running of lintian after a successful build with sbuild. The $lintian_opts variable is an array of options to pass to lintian. Here the options are '-i' which will output information about lintian warnings and errors, and '-I' which will output lintian "info" messages. Using piuparts The use of piuparts with sbuild is another feature meant to enhance the quality of Debian packages built with sbuild. To use piuparts, first install piuparts. Next, edit your ~/.sbuildrc configuration file. Open ~/.sbuildrc with your favorite text editor and edit the lines with the following variables. The $run_piuparts variable will enable running piuparts after a successful build with sbuild. The $piuparts_opts variable is an array of options to pass to piuparts. Here the options instruct piuparts to use sbuild chroot '/srv/chroot/unstable-amd64-sbuild' as the chroot used in its testing of packages. Using autopkgtest Add this to .sbuildrc: $external_commands = { 'post-build-commands' => [ [ 'autopkgtest', '%d', '%c', '--', 'schroot', 'unstable-%a-sbuild;', # if autopkgtest's exit code is 8 then the package had no tests # but this isn't a failure, so catch it 'aptexit=$?;', 'if', 'test', '$aptexit', '=', '8;', 'then', 'exit', '0;', 'else', 'exit', '$aptexit;', 'fi' ], ], }; Consider configuring schroot with tmpfs or eatmydata, or else running adt-run will slow the build a lot. Bind mounts Directories on the local filesystem can be bind mounted and made available in the sbuild chroots. To do this, add an entry in /etc/schroot/sbuild/fstab. The following example shows how to bind mount the apt archive cache inside an sbuild chroot. This is useful when not using a local mirror of the Debian repository. Note that if you set up this bind mount, you probably want to avoid passing the -c flag to sbuild-update or you'll keep clearing out the bind mount. Also note if you set up piuparts as detailed above, it will empty your apt cache each time it runs, which greatly reduces the usefulness of bind-mounting the cache. To deal with this you can set up a separate schroot configuration for piuparts that doesn't perform the bind mount. In brief (sed commands untested): cd /etc/schroot cp chroot.d/unstable-amd64-sbuild-* chroot.d/unstable-amd64-piuparts sed -i 's/profile=sbuild/profile=piuparts/' chroot.d/unstable-amd64-piuparts cp -R sbuild piuparts sed -i '|^/var/cache/apt/archives|d' piuparts/fstab and use --schroot unstable-amd64-piuparts in your ~/.sbuildrc. Customizations of sbuild chroots Sometimes it is desirable to further customize your sbuild chroot environment. Typical customizations done are installing more packages inside the chroot, modifying /etc/apt/sources.list, and installing custom scripts to be run inside the chroot. To modify a chroot, start a session for the chroot with the prefix 'source:'. For example, to modify the unstable-$arch-sbuild chroot, start a session for the chroot as follows. This will start a session inside the unstable-$arch-sbuild chroot. Any modifications done inside the chroot will be saved upon exiting. Inside this chroot, you may run apt-get commands to install or remove packages as desired. For example, to install ccache, do the following in the chroot session. Note that you are already root inside a chroot session. Also, sudo would typically not be installed in the chroot anyway. Making other modifications such as editing /etc/apt/sources.list or adding scripts inside the chroot is best done from outside the chroot session. In order to do this, leave the current chroot session open and start another terminal session. In the other terminal session, find the path used for the existing chroot session as follows. This should output exactly one line and should specify the path of the chroot session. It should look something like this. Path /var/lib/schroot/mount/unstable-amd64-sbuild-5bad48fe-9823-4454-815f-b869d1d7b22c Doing an ls on this directory should resemble a standard listing of the '/' directory. With the above path, the sources.list file will be in the following path. /var/lib/schroot/mount/unstable-amd64-sbuild-5bad48fe-9823-4454-815f-b869d1d7b22c/etc/apt/sources.list Open the sources.list file at this path with root privileges using your favorite editor, for example: Proceed to edit the sources.list file as you see fit, then save. To add scripts inside the chroot, simply place the scripts in the following directory. /var/lib/schroot/mount/unstable-amd64-sbuild-5bad48fe-9823-4454-815f-b869d1d7b22c/usr/local/bin Be sure to make the scripts executable. Other modifications may be done to the chroot, either by running commands available within the chroot session, or by running commands with root privileges via the secondary terminal session. Once you are done making modifications to the chroot, simply exit the session. Inside the chroot session, do the following. After exiting, your modifications will be saved and made available for every new chroot session created afterwards. External Commands sbuild supports running external commands at various stages of the build process. This is useful for cases such as running a script inside the chroot after it has been setup. As an example, to run a script in /usr/local/bin/myscript, edit the $external_commands in the sbuild configuration file ~/.sbuildrc as follows. sbuild can also translate certain percent escaped keywords for external commands during certain portions of a build. For example, in post build commands, %SBUILD_CHANGES is changed to the path of the '.changes' file for a successfully built package. Here is an example of adding a post build command to run /usr/local/bin/postbuildscript with %SBUILD_CHANGES as an argument. See the 'EXTERNAL COMMANDS' section of the sbuild man page for more information on external commands. Using "ccache" with sbuild ccache is a compiler wrapper that will cache compilation results (produced object files) from gcc and g++; if you repeatedly compile the same source code (or parts of it), ccache will greatly shorten compilation times by avoiding recompilation of files that it has cached earlier. This is especially useful during package development, when you might have to rebuild a package with a long compilation phase several times. It is also effective with packages that are frequently updated, because often only a few files actually change during updates to a software. In order to prepare your sbuild environment for ccache, first perform the following setup in the host environment (i.e., outside the chroot), as user root: This assumes that you trust all members of the sbuild group. It is perfectly fine to share the cache among chroots, even for different architectures. ccache honours the compiler name, size and timestamp as well as the command line when calculating hash values. At least one of these will differ between builds of the same file for different architectures. Next place the following script into /var/cache/ccache-sbuild/sbuild-setup: and make it executable: chmod a+rx /var/cache/ccache-sbuild/sbuild-setup Then for each chroot ($dist-$arch-sbuild) where you want to enable ccache Install ccache inside the chroot by running schroot -c source:$dist-$arch-sbuild apt-get install ccache and edit the corresponding configuration file in /etc/schroot/chroot.d/ by appending the line command-prefix=/var/cache/ccache-sbuild/sbuild-setup (Multiple command-prefix can be joined with commas, in case you already have one configured; see eatmydata below.) Using eatmydata with sbuild eatmydata is used when storing data on the system is not that important. This is typically the case during build runs using sbuild. To use eatmydata in sbuild, install the eatmydata package inside the sbuild chroot environment. To enable first run, as root: Then edit /etc/schroot/chroot.d/$dist-$arch-sbuild-$suffix to add the line: command-prefix=eatmydata If you want to combine this with the ccache instructions from above then use: command-prefix=/var/cache/ccache-sbuild/sbuild-setup,eatmydata Note that piuparts invokes eatmydata by default and nested eatmydata invocations don't work. To deal with this pass --no-eatmydata to piuparts in your ~/.sbuildrc, or set up a separate schroot profile for piuparts as described above. sbuild overlays in tmpfs If you are using a type=directory chroot as described in "Setup" above, and you have sufficient memory, you can run builds in RAM for a huge speed increase. The build is performed in a tmpfs that is overlaid upon the base chroot. You need union-type=overlay in your /etc/schroot/chroot.d/sbuild-amd64-sbuild-<hash> file but that should be there by default if you followed the setup instructions above. Create the executable: /etc/schroot/setup.d/04tmpfs with 1 cat >/etc/schroot/setup.d/04tmpfs <<"END" 2 #!/bin/sh 3 4 set -e 5 6 . "$SETUP_DATA_DIR/common-data" 7 . "$SETUP_DATA_DIR/common-functions" 8 . "$SETUP_DATA_DIR/common-config" 9 10 11 if [ $STAGE = "setup-start" ]; then 12 mount -t tmpfs overlay /var/lib/schroot/union/overlay 13 elif [ $STAGE = "setup-recover" ]; then 14 mount -t tmpfs overlay /var/lib/schroot/union/overlay 15 elif [ $STAGE = "setup-stop" ]; then 16 umount -f /var/lib/schroot/union/overlay 17 fi 18 END and make it executable: chmod a+rx /etc/schroot/setup.d/04tmpfs Alternatively you could configure fstab to mount /var/lib/schroot/union/overlay as tmpfs none /var/lib/schroot/union/overlay tmpfs uid=root,gid=root,mode=0750 0 0 Enabling experimental The Debian experimental repository can be added dynamically on top of an existing unstable chroot during each sbuild run that requires experimental: sbuild --extra-repository='deb experimental main' --build-dep-resolver=aspcud mypkg.dsc Build for experimental If you want to build for unstable but upload to experimental. Use schroot -l --all-source-chroots to get the name of the chroot (unstable-amd64-sbuild in this case). sbuild -d experimental -c unstable-amd64-sbuild mypkg.dsc Alternatively, if you know that you always want to build your packages for experimental in a sid chroot, just add experimental as an alias of your sid schroot to your sid schroot configuration: aliases=experimental Enabling incoming.debian.org Another useful repository to add as --extra-repository option is deb buildd-unstable main in case you want to build or do a new upload before the next dinstall sbuild --extra-repository='deb buildd-unstable main' mypkg.dsc Disabling network access for dpkg-buildpackage This doesn't seem to work with recent sbuild (2016/05) Source packages must be buildable without accessing any remote machines. On the other hand, the build process needs network access for the installation of the build dependencies. Conveniently, the build dependencies are installed by the "root" user while dpkg-buildpackage is run under fakeroot by the user running sbuild. So the following will deny any network access during the build process through blocking traffic originating from any process owned by the sbuild group while the root user will still have network access: sudo iptables -I OUTPUT -m owner --gid-owner sbuild ! -d 127.0.0.0/8 -j DROP sudo -u sbuild sbuild mypkg.dsc A better fix would be if schroot allowed to unshare the network namespace for the dpkg-buildpackage invocation. See bugs 802850 and 802849 source only upload Sbuild is *not* suitable for source-only uploads. Sbuild is meant to build architecture specific binary packages (with the --arch-all option it can also build Architecture:all packages). But source-only uploads are neither architecture specific nor do they contain binary packages. To create a dsc for a source-only upload you would use: dpkg-buildpackage -nc -d -S Since dpkg 1.18.0 (starting with Debian Stretch) the -d option is implicit when specifying -S -nc so you just need: dpkg-buildpackage -nc -S The above requires a clean source directory as it will not run the clean target (because it might require some of the build dependencies). If you built your package with sbuild before, then your source directory will be clean anyways. Using aliases In Debian, an unstable chroot is used for building in a number of situations like building an unpacked source package with UNRELEASED in debian/changelog or building packages for experimental. Furthermore, distributions have alternative names like sid/unstable or experimental/rc-buggy. Sbuild selects the chroot to use either from debian/changelog (so it would be nice if UNRELEASED would trigger a build in an unstable chroot) or through the -d option which also sets the Distribution value in the resulting .changes file (so it would be handy if saying -d sid were enough and one wouldn't have to use the -c option to type unstable-amd64-sbuild manually). All of this can be solved by using schroot aliases. My sid schroot config says: aliases=UNRELEASED,sid,rc-buggy,experimental This means, that this schroot will be used for packages having UNRELEASED in their debian/changelog, for packages I build with -d sid (because writing out unstable is too long) as well as for packages I build for experimental. Adding extra packages It is often necessary to add extra binary packages as build dependencies. For example, you might want to make a package available as a build dependency that is waiting in the NEW queue and so isn't available from the mirrors. To do this, use the --extra-package=./foo.deb option to sbuild. You might find that the output from the resolver is not helpful in determining which extra package you need to make available. In this case, it can be useful to pass --build-dep-resolver=aptitude which tends to provide more useful output (though you should remove it once you've figured out the problem).
https://wiki.debian.org/sbuild?action=diff
CC-MAIN-2017-04
refinedweb
3,518
54.83
Parsing the #U2F Signature response in #Javascript This is my third blog post in my series of U2F, and if you haven’t already seen it – check out the github repo for the source code here; It’s been refactored since the last post, so that the parser no longer pollutes the global namespace with it’s own variables, and keeps things cleaner. So, it’s now wrapped up like this class U2FParse { parseRegistration (registrationData) { … } parseSign (signData) { … } … } So that you instatiate a new U2FParse class (which I’ve called “parser”), then parse either the registration response or the sign response. Let’s look at how to get a signature response, assuming you already have the keyhandle from the registration; function Sign() { let registeredKey = { keyHandle: U2FRegistration.keyHandle, version: ‘U2F_V2’ } u2f.sign(‘’, ‘SigningChallenge’, [registeredKey], (response) => { …. } ); } By running this code, the browser will prompt you to press the button on your U2F device, and the callback will be triggered, with the response object populated. Now, we call the method; U2FSign = parser.parseSign(response.signatureData); Which does the following; var bSignData = this._Base64ToArrayBuffer(signData); return { userPresence : bSignData[0], userCounter : bSignData[4] + bSignData[3] * 256 + bSignData[2] * 256 * 256 + bSignData[1] * 256 * 256 * 256 }; The UserPresence is a number where 1 is present, and anything else is just plain wierd, but treat that as an error. UserCounter is a 4 byte integer, that counts up how many times the user has logged in (signed a challenge). My plan is to move this to server side code that can be accessed via Ajax, since I haven’t seen that done before, and I guess it may be useful to someone.
https://blog.dotnetframework.org/2020/02/28/parsing-the-u2f-signature-response-in-javascript/
CC-MAIN-2022-40
refinedweb
274
56.39
Welcome to Freemarker Tutorial Series. In previous post we created our first Hello World Freemarker Template example. We learned few APIs of freemarker and also how template file is loaded in Java and values are replaced. Following is the list of tutorials from Freemarker tutorial series. FreeMarker Tutorial Series Today we will create a Servlet based application that uses Freemarker FTL as view instead of default JSP. This would give you a good insight in Servlet+Freemarker integration. The application is very simple: 1. There is a table that displays user info like firstname, lastname. 2. New user can be added via Add User form. Below is the wireframe of our final freemarker based servlet app. So lets get started. Things We Need Before we starts with our Servlet FreeMarker example, we will need few tools. - JDK 1.5 or above (download) - Tomcat 5.x or above or any other container (Glassfish, JBoss, Websphere, Weblogic etc) (download) - Eclipse 3.2.x or above (download) - Freemarker JAR v2.2.8 or above(download) Let us start with our Servlet based Freemarker application. Step 1: Getting Started Open Eclipse and goto File -> New -> Project and select Dynamic Web Project in the New Project wizard screen. After selecting Dynamic Web Project, press Next. Write the name of the project. For example Freemarker_Hello_World. Freemarker support to this project. Step 2: Add FreeMarker Support to Servlet First copy the Freemarker JAR file in WebContent > WEB-INF > lib folder. Create this folder if it does not exists. Once the JAR is in place, modify deployment descriptor (web.xml) file. Replace existing code with following: Don’t get scared!! :) we will dissect the code and understand whats happening here. File: /WebContent/WEB-INF/web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns: <display-name>FreeMarker_Hello_World</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> </welcome-file-list> <servlet> <servlet-name>freemarker</servlet-name> <servlet-class>freemarker.ext.servlet.FreemarkerServlet</servlet-class> <!-- FreemarkerServlet settings: --> <init-param> <param-name>TemplatePath</param-name> <param-value>/</param-value> </init-param> <init-param> <param-name>NoCache</param-name> <param-value>true</param-value> </init-param> <init-param> <param-name>ContentType</param-name> <param-value>text/html; charset=UTF-8</param-value> <!-- Forces UTF-8 output encoding! --> </init-param> <!-- FreeMarker settings: --> <init-param> <param>hello_servlet</servlet-name> <servlet-class>net.viralpatel.freemarker.HelloServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>hello_servlet</servlet-name> <url-pattern>/hello</url-pattern> </servlet-mapping> <!-- Prevent the visiting of MVC Views from outside the servlet container. RequestDispatcher.forward/include should and will still work. Removing this may open security holes! --> <security-constraint> <web-resource-collection> <web-resource-name>FreeMarker MVC Views</web-resource-name> <url-pattern>*.ftl</url-pattern> </web-resource-collection> <auth-constraint> <!-- Nobody is allowed to visit these --> </auth-constraint> </security-constraint> </web-app> To start with first we make an entry for freemarker.ext.servlet.FreemarkerServlet servlet in web.xml. Note how we mapped this servlet with url-pattern *.ftl. Thus all the request that ends with .ftl will get processed by FreemarkerServlet servlet. In addition to this, we also provided few parameters to FreemarkerServlet. These parameters are more or less self explanatory. Have a look at comment. For our servlet app, we defined a new servlet net.viralpatel.freemarker.HelloServlet which we mapped to url /hello. This serves as an entry point to our app. We start with /hello page. The FTL templates will be saved in .ftl files in our WebApp folder. To avoid any unwanted access to these files we defined security-constraint in web.xml. Once we have setup web.xml, we add Java source code. Step 3: Hello World FreeMarker Create a class User.java under /src/net/viralpatel/freemarker folder. This class serves as bean class which we uses to set User data. Copy following code in User.java. File: /src/net/viralpatel/freemarker/User.java package net.viralpatel.freemarker; public class User { private String firstname; private String lastname; public User() { } public User(String firstname, String lastname) { this.firstname = firstname; this.lastname = lastname; } //Getter and Setter methods } Once User bean is created, we add HelloServlet. Create HelloServlet.java under /src/viralpatel/freemarker and copy following code. File: /src/net/viralpatel/freemarker/HelloServlet.java package net.viralpatel.freemarker; import java.io.IOException; import java.util.ArrayList; import java.util.List;; private static List<User> userList = new ArrayList<User>(); //Just prepare static data to display on screen static { userList.add(new User("Bill", "Gates")); userList.add(new User("Steve", "Jobs")); userList.add(new User("Larry", "Page")); userList.add(new User("Sergey", "Brin")); userList.add(new User("Larry", "Ellison")); } } We haven’t defined any doGet or doPost methods in servlet. We will add them shortly. Note how we defined a static instance of List<User>. We use it to store user list. Ideally instead of doing this, you should store user information in database. But for sake of simplicity of this example we store users in this static list. Add following doGet() method in HelloServlet. In this method we just set User list in request via request.setAttribute("users", userList); and forwards the request to /index.ftl. We do HTTP Forward here. The request gets forwarded to index.ftl. As this URL ends with .ftl, the servlet container triggers FreemarkerServet. This servlets load the index.ftl template file and renders the output. @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //Put the user list in request and //let freemarker paint it. request.setAttribute("users", userList); request.getRequestDispatcher("/index.ftl").forward(request, response); } In our example, we also have functionality of adding a user. We have a form with two fields firstname and lastname. User can add new users through this form. We define a doPost() method which gets called when add user form is submitted. In this method we get firstname, lastname values through request and add it in our user list. Also note how we called doGet() method inside doPost(). This is because we want to render same output, the user list on adding new user. Add doPost() method to HelloServlet. @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String firstname = request.getParameter("firstname"); String lastname = request.getParameter("lastname"); if(null != firstname && null != lastname && !firstname.isEmpty() && !lastname.isEmpty()) { synchronized (userList) { userList.add(new User(firstname, lastname)); } } doGet(request, response); } We are almost done. All we need is our freemarker template file. Create a file index.ftl under /WebContent/ folder. Copy following content into it. File: /WebContent/index.ftl <html> <head><title>ViralPatel.net - FreeMarker Hello World</title> <body> <form name="user" action="hello" method="post"> Firstname: <input type="text" name="firstname" /> <br/> Lastname: <input type="text" name="lastname" /> <br/> <input type="submit" value="Save" /> </form> <table class="datatable"> <tr> <th>Firstname</th> <th>Lastname</th> </tr> <#list users as user> <tr> <td>${user.firstname}</td> <td>${user.lastname}</td> </tr> </#list> </table> </body> </html> For sake of simplicity, I have removed CSS styles from the above FTL file. You can download the full source code at the end of this tutorial. Just compare your project structure with project structure image above. See if there are any differences.<< Use the Add User form to add new user into below list. Download Source Code FreeMarker_Servlet_helloworld.zip (513 KB) Is it possible to use your example with embedded jetty server. If yes than how will we can use css and javascript with the freemaker template files. Can you give me some pointer. Nigau, yes you can embed the jetty server , u can use the similar way you use the normal servlet container. For Example —————————————————- Please note if you Eclipse set the Jetty in your classpath and create all the required resources(javascript) in the webapp folder. Since the freemarker template is loaded by the servlet we dont need to specify any markups in the web.xml Place all the *.ftl in the webapp folder… Regards, Ronald i am getting error “No setter found for property” templateLoaderPath. in spring servlet .i know this type of error occurs if no setter injection is declared in class..but how can i inject setter in org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer Thanks for your tutorial. I was wondering how to add an Image in the FTl and where to store the image ?. I am bit confused with the relative /absolute path which is referenced by FTL and later by Java. Can you provide a short example based on the above project structure ?. thanks Hi Densil, For your query FTL is just a template and a mere html file see the template carefully just like this so you can use your normal html tag to load the image,, its a relative path not the absolute path. since u r placing in a web container you would use the image in the context folder .. like —/rootContext +———/WEB-INF +———/lib +———freemarker.jar +———.jar +———/images [all the images] +———/templates [ all the templates] thats all, make sure your classpath entries are perfect. Enjoy scripting Regards, Ronald i am getting error HTTP Status 404 – /FreeMarker_Hello_World/ You have to go to directly because the index.html is missing. it should be will it be better if we set like this? Is there any package/bundle to use FTL on Adobe CQ Thanks, please when i run this code i get an error “HTTP Status 404 – /Freemarker_Hello_World/” i get “SEVERE: Servlet /Freemarker_Hello_World threw load() exception java.lang.ClassNotFoundException: javax.servlet.http.HttpServlet” ???????????????????? Thanks for sharing the article, saved a lot of time of mine :) I am facing another issue with freemarke though. My application uses xhtml files as pdf template, my template path is web-inf/pdfTemp and I have testTemplate.xhtml there as a template file. Now whenever I try to generate a pdf, it creates something like ‘testTemplate.xhtml12300783522’ inside web-inf/pdfTemp of the server installation directory. Every time I have to manualy clean those junk files. Any idea why this files are getting generated and how to get rid of them? hi, the alignment works for chrome but except other browsers like IE, firefox, etc etc. As i’m new to this freemarker concept please let me know how to make it proper alignment for all browsers.. Hi, I am using ftl with spark web framework. My project structure is —/root +———/src[ALL THE JAVA FILES WITH SPARK] +———/images [all the images] +———/templates [ all the .FTL templates] I wanna put images in the .ftl file, for which i am using image tag of html. but the images are not shown when i run the program. I think there’s some problem with the project structure or the image path that i gave. Could you please help me with this? thanks too much for this article tomcat gives report that the access has been forbidden! what i have to do? okay solved the problem when i run the code – i get an error as below weblogic.application.ModuleException: VALIDATION PROBLEMS WERE FOUND problem: cvc-complex-type.3.2.1: Attribute not allowed (no wildcards allowed): [email protected]:// in element [email protected]://java.sun.com/xml/ns/javaee” First of All insert getters/setters into your User class Hi Guys, Those who getting error while running “HTTP Status 404 – /Freemarker_Hello_World/” is bcoz in web.xml we mapped the servlet with url pattern try run it with “” Thanks.. Correct ftl template must be hi sir, i am using free marker template to send emails using Java mail Api. So i am able to send emails by loading free marker template and sending data dynamically using Map object. But i am unable to images in free marker template. Can you please tell me solution for this i had kept my template in src folder Thanks for your tutorial, it saved me a bunch of time! I was learning freemarker, and testing my code online, but when I was about to deploy it with real servlets, real data… I searched, found your tutorial, and man… thank you! Very good, very well written and just enough to get started in something real :) Happy holidays!
http://viralpatel.net/blogs/freemarker-servlet-tutorial-example/
CC-MAIN-2016-26
refinedweb
2,018
60.72
Opened 6 years ago Closed 6 years ago #3358 closed defect (wontfix) TracTags 0.6 appears to break IPermissionPolicy example Description This is an important example showing how to build a fine-grained permission policy using tags: The sample now appears to be broken, due to non-existence of TagEngine object in TracTags 0.6. It would be great if someone who understands TracTags 0.6 could fix this example, or point me to an IPermissionPolicy sample that uses the new TracTags 0.6 API. Thanks, James Attachments (1) Change History (4) comment:1 Changed 6 years ago by athomas - Resolution set to invalid - Status changed from new to closed Changed 6 years ago by jamesyonan patch to api.py comment:2 Changed 6 years ago by jamesyonan - Resolution invalid deleted - Status changed from closed to reopened - Trac Release changed from 0.10 to 0.11 I was able to fix the issue, but I had to add a small patch (attached) to api.py to allow get_resource_tags to be called with req==None, since the IPermissionPolicy plugin might want to query the tags for a page outside the context of a request for that page. After adding this patch, it is then possible to easily get the tags for a resource in an IPermissionPolicy plugin as such: tags = TagSystem(self.env).get_tags(None, resource) I added the patch since it was not clear to me how an IPermissionPolicy plugin could pass a reasonable 'req' object given the context in which it is called. In fact, it would seem that if the IPermissionPolicy plugin passed the current request object, it would set up an infinite recursion because the IPermissionPolicy plugin would get recursively called again asking if TAGS_VIEW is permitted on the requested page. Please merge if this seems like a reasonable approach. comment:3 Changed 6 years ago by athomas - Resolution set to wontfix - Status changed from reopened to closed req usage is pervasive in Trac, selectively avoiding it isn't really feasible. Fortunately, Trac provides a couple of mock objects that are perfect for this situation: from trac.tests import Mock, MockPerm req = Mock(perm=MockPerm()) ... Urm , you'd be better off creating this ticket on that Trac rather than here.
http://trac-hacks.org/ticket/3358
CC-MAIN-2014-42
refinedweb
373
59.03
Learn how to configure Auth0 with Shiny Server Pro to secure your interactive R apps! As we've shown in a previous post, you can add authentication to a Shiny Server instance, allowing your server to be online without being available to everyone in the internet. If you've been working with this and your organization has grown, you'll be more likely to find scenarios where you'd prefer or need to restrict access to a report to specific users or groups. Shiny Server Pro is a paid edition which allows for this, and has a built-in authentication scheme with some options included, but these options, for one of many reasons may not be appropiate for you, if so, this is the blog post you've been waiting for! We'll explain how to use the shiny-auth0-plus proxy to pass along credentials and permissions. Note: If you are working in a small company and are scared away by Shiny Pro's pricing, take into account they have special pricing for small companies. But why? First of all, why would you need to get authorization for your shiny apps? Well, suppose you have a report with customer PII (personally identifiable information) which employees should only access in a "need to know basis", a way to control this would be requiring a certain permission or list of users to access the report. Also, to consider a slightly more complex scenario, suppose you want sales representatives to be able to access customer data, but only of accounts they manage, you can also do this with Shiny. For example, consider this Demo available in the Shiny reports gallery, you can login as an administrator ( kim) and see all companies: Or, you can login with sam, that only has access to data from DL, and you'll see this: The code for this example is here, and in this case the report has been coded in such a way that the users membership to a company or complete admins has been hardcoded into a membership_db table. We'll recreate a similar example but using Auth0 as a proxied authentication. Apart from these, the Pro version allows for usage monitoring with a sweet admin panel, spanning multiple processes per each report to handle a bigger number of users without hanging, and allows to use different R versions per Shiny app. Step 1: Installation and configuration - First of all Download Shiny Server Pro - If you don't see anything in the download box, you may have to disable your ad-blocker software, since it's a third party form. The setup is almost the same as the one described in our previous blog post, in step 1, but using the Shiny Server Pro download. - Follow the basic setup instructions for it - Make sure it works before trying to add any authentication. Once you know Shiny Server is up and running in its Pro version, we can start to plan out how to make it work with Auth0.-plus proxy server, which will run without TLS in our internal network (considered safe). This step is the same as the guide for the open source Shiny server. Our sample Nginx configuration file looks as follows:-plus authentication proxy. # Requests are passed in plain HTTP, so TLS termination # is applied at this point. location / { proxy_set_header Host $host; # This points to our shiny-auth0-plus authentication proxy, # change localhost:3000 to suit the configuration of # your shiny-auth0-plus-plus may want to consider that Let's Encrypt provides free TLS certificates with automatic updates after expiration.-plus Since authentication will be handled by Auth0, a free Auth0 account is required to work with shiny-auth0-plus. Don't panic, it's as simple as signing-up and setting a few knobs here and there. Let's take a look. First, head over to Auth0's signup page. Follow the steps to fill in your details. For simple use cases, a free account is more than enough. With a free account you get up to 7000 regular users. If you need more than that, check our pricing page. After you have completed the signup process, access the Auth0 Dashboard and create a new application for our shiny-auth0-plus app. This application will let you setup how your users will log-in through the proxy. You have several options you must consider: will you use a standard username/password database? Or will you allow social logins (through Facebook or Google, for example)? It is up to you to decide what fits best your use case.-plus. Another important setting is the Allowed Callback URLs setting visible below. This is the URL the user will be redirected to after a successful authentication attempt. It is formed by the domain of your public server plus the callback path. For instance:. Step 4: Setting up shiny-auth0-plus for Shiny Server Authentication In this step we'll configure a proxy that sits between nginx and the Shiny Server, which will authenticate with Auth0. First, clone the latest version of shiny-auth0-plus to the system that will run the authentication proxy. git clone Make sure you have an up-to-date Node.js installation. If in doubt, consult with your system administrator. Now install all required dependencies for shiny-auth0-plus: cd shiny-auth0-plus npm install If everything went well, all dependencies for running shiny-auth0-plus are now locally installed. Now, we will setup shiny-auth0-plus. Create a new file named .env inside the shiny-auth0-plus directory with the following content, adjusted with the variables you wrote down. AUTH0_CLIENT_SECRET=myCoolSecret AUTH0_CLIENT_ID=myCoolClientId AUTH0_DOMAIN=myCoolDomain AUTH0_CALLBACK_URL= AUTH0_GROUPS_CLAIM= COOKIE_SECRET=somethingRandomAndLongHerePlease SHINY_HOST=localhost SHINY_PORT=3838 SHINY_ADMIN_PORT=4151. AUTH0_GROUPS_CLAIM is an URL we'll use to define custom claims to add to the token, just use your shiny domain slash claims and you'll be fine. Remember to use the same when configuring your Auth0 tenant for the groups. COOKIE_SECRET should be a fairly long random string that should be kept secret. This secret is used to validate the cookie stored client side. Put a long, random string here. For example, you can generate this string with the pwgen package: pwgen 50 1 SHINY_HOST, SHINY_PORT and SHINY_ADMIN_PORT are the actual host and ports for your running Shiny Server installation from step 1. If everything is running on the same server, the defaults should be OK (localhost and ports 3838 and 4151). Lastly, PORT is the port where the shiny-auth0-plus authentication proxy will run. This port is the port that should be set in the proxy_pass and proxy_redirect directives from step 2. If shiny-auth0-plus will run on a different host from Nginx, don't forget to update the localhost part of these directives in nginx.conf as well. If in doubt, consult with your system administrator. If you are just testing locally, you can use localhost instead of the IP of any machine. After setting up all of this, start the proxy with this command: npm start And check if you can access the server, if you get error 502, check in the logs ( /var/log/nginx/error.log) If you see an error like this: [...]*1 connect() to [::1]:3000 failed (13: permission denied) while connecting to upstream[...] It can be solved by configuring SELinux to allow the connection, using this command as root: setsebool -P httpd_can_network_connect 1 Step 5: Authorization in Shiny If you got everything right up to this step, you should get an Auth0 login screen when accessing the server (The one we mentioned as). If something fails in this stage make sure to recheck all steps before continuing. Having logged in, go into and click on the user you accessed with, if you scroll down to Identity Provider Attributes you'll see the user_id, write this value down in some text file since we'll use it afterwards. Assuming everything works, you can now make some adjustments to the /etc/shiny-server/shiny-server.conf file, so the user/groups will arrive to the shiny app. If there are any Authentication strategies defined (auth_proxy, auth_pass), please delete that line, and also modify the admin panel so it looks like this, where auth0|5ad7c0bd67dd561ad0ab2b2 should be your user_id: # Send user id and group to shiny auth_proxy X-AUTH0-USER-ID X-AUTH0-GROUPS; # Define a default admin interface to be run on port 4151. {.pro} admin 4151 { required_user auth0|5ad7c0bd67dd561ad0ab2b2d; } With any change in this configuration file, make sure to restart the shiny-server to take the change. When this has been configured, the admin panel should be accesible at, only to the user specified up there, and will have the reports you made available with shiny server. If instead of using user_ids you wish to allow access using the email of the user (which may not be available for all connection types, like SMS) you can use X-AUTH0-EMAIL instead of X-AUTH0-USER-ID. Step 6: Authorization by group We'll implement authorization by groups to allow for specifying groups for each user, and adjust the reports using this data. Let's assume a simple example, where a user can have groups "Admin", "Manager", or none of those. For this, we can use (Among a lot of other approaches) the authorization extension, first of all, install it: To keep it simple, install it using Webtask storage for now: Open the Authorization extension: And go to the configuration section, there choose to include the groups in the token and persistence, and then click on "Publish Rule", this will generate a Rule which will load the groups that you define in the extension. You can then create groups and assign them to users in this interface: Almost done! The users/groups are created and being passed along in the authentication steps, but the groups still don't reach Shiny at this point, to include the group in the token Auth0 generates, we can add a rule which adds it as a custom claim: function(user, context, callback){ var namespace = ''; // This one has to match with `AUTH0_GROUPS_CLAIM` in shiny-auth0-plus context.idToken[namespace + '/groups'] = user.groups; callback(null, user, context); } Make sure this rule runs after the rule autogenerated by the Authorization Extension! After all of this, you can head over to clone this report: - This example report can show you different results if it's an admin or not, and shows you the reported values at the left, you can use the code as a basis to do something more complex and allow for specific roles to access specific pieces of the data, or directly deny access to it. If you've followed all the steps, you'll now be able to control Authorization in your Shiny server!
https://auth0.com/blog/amp/authentication-and-authorization-with-shiny-server-pro-and-auth0/
CC-MAIN-2019-18
refinedweb
1,807
58.42
With datastore identity you are leaving the assignment of id's to DataNucleus and your class will not have a field for this identity - it will be added to the datastore representation by DataNucleus. It is, to all extents and purposes a surrogate key that will have its own column in the datastore. To specify that a class is to use datastore identity with J. See also :- When using datastore identity, the class has no associated field so you can't just access a field of the class to see its identity - if you need a field to be able to access the identity then you should be usingapplication identity. There are, however, ways to get the identity for the datastore identity case, if you have the object. Object id = pm.getObjectId(obj); Object id = JDOHelper.getObjectId(obj); You should be aware however that the "identity" is in a complicated form, and is not available as a simple integer value for example. Again, if you want an identity of that form then you should use application identity When implementing datastore identity all JDO implementations have to provide a public class that represents this identity. If you call pm.getObjectId(...) for a class using datastore identity you will be passed an object which, in the case of DataNucleus will be of type org.datanucleus.identity.OIDImpl. If you were to call "toString()" on this object you would get something like 1[OID]mydomain.MyClass This is made up of :- 1 = identity number of this object class-name);
http://www.datanucleus.org/products/accessplatform/jdo/datastore_identity.html
CC-MAIN-2015-48
refinedweb
256
52.6
resolv-retry infinite # Most clients don't vpn entre 2 synology need to bind to a specific local port number. Nobind # The persist options will try to avoid accessing certain resources on restart that may no longer be accessible because of the privilege downgrade. Vpn entre 2 synology the VPN would not vpn entre 2 synology be able to see what data you are sending over TOR unless they decrypted it, because remember, all information relayed over TOR is encrypted. The downsides of course, after Install activate Your ip will be Changed. Vpn vpn entre 2 synology Add on If you dont wants to above iphone best proxy Method, how to open Blocked sites in Chrome Firefox via. Then we have one more method where you have to Install one add on in your Browser.j utilise un script d auto-configuration vpn entre 2 synology proxy sur ma machine. Vpn entre 2 synology in USA and United Kingdom! import and export functions are available both through the GUI or through direct command line options. Secured import and export functions To allow IT Managers to deploy vpn entre 2 synology VPN Configurations securely, ). in the vpn entre 2 synology Basic Settings section, click the pencil icon near the top right. In the Max Users field, click More.mod Games. 2016. Mod Games. 2016 - Game Petualangan, mod Games. Other Games December 24th, 2016 - Action vpn entre 2 synology Games, 2016 - Action Games, december 24th, december 4th, 2016. December 1st, december 9th, 2017 - Action Games December 28th, august 20th, action Games, 2016 - Action Games, mod Games. Mod Games. Role Playing Pages 1 of 10 : ». Strategi Games December 28th, 2016 - Mod Games, 2016. 2016 hide proxy kickass Mod Games, action Games, december 4th, mod Games. December 28th, The desert festival and fairs, colorful folk culture of royal Rajasthan can be seen, the snake charmers, folk performers, puppeteers, art and crafts are the major attraction of the festival. Desert Camel Safari The best way to explore the Thar region of India is using the Camel.. 1. the following prerequisites are required: iOS 8 required To set up UsenetServer VPN, click on your operating system below. Mac vpn entre 2 synology OS X (10.10)) Software The following prerequisites are required: 64-bit processor iOS Mobile App. solitaire Zynga Inc. Facebook doesn't run GPS in the background unless you give vpn entre 2 synology us permission by turning on optional features that require this. Games Solitaire by Zynga: The Only Game You Need Therapy: Solitaire is a mental escape that is a refreshing stress-reliever.to see how to fix this problem, vpn entre 2 synology we advise you to check out our article on how to fix Wi-Fi exclamation mark on Windows 10.top features Remote Desktop Sharing. This feature enables a user to share his machine on the corporate network from a remote location like home. Multiple Remote Desktop Sharing sessions may be configured in the 'Remote Sharing' tab. gRE tunnels greatly simply vpn entre 2 synology the configuration and administration of VPN tunnels and are covered in our Configuring Point-to-Point GRE VPN Tunnels article. IPSec VPN tunnels can also be configured using GRE (Generic Routing Encapsulation)) Tunnels with IPsec encryption. Lastly,you may want to turn those features off while using a hotspot or vpn entre 2 synology you could end up with a big bill. You use auto backup software or vpn samsung s4 upload photos to iCloud,the iPhone 8 and iPhone 8 Plus vpn entre 2 synology have custom front and rear glass, fitted onto a steel substructure and surrounded with an aerospace-grade 7000 Series aluminum band. Made with a 50 percent deeper strengthening layer, Shellfire vpn windows 10: SoundAbout Pro Mod Apk Latest Version Download With Full Version License Key Unlocked Apk Download For Android Free. which is technically weaker but still uncrackable. Currently the best cipher available, some companies offer AES-128 as well, so, aES-256 is literally uncrackable. You can vpn entre 2 synology go with either one without any fear of your Internet traffic being compromised.the pseudowire is not enabled. In this case, the C-bit in the Label Mapping message that the PE router sends is set to 0. If a PE router is capable of and prefers sending and receiving the optional control word, vpn entre 2 synology when two PE routers exchange Label Mapping messages, the control word is optional. For other Layer 2 payload types, one of the following scenarios could happen when the control word is optional: Both C-bits are set to the same valuethat is, or if it is capable of doing that but prefers not to do so, if a PE router cannot send and receive the optional control word, the C-bit in the Label Mapping message it sends is set to 1.its available for free in the. Mac) 3.7 (74.62)) 52 votes XMEye is a free video monitoring tool. XMEye is a practical video monitoring tool for IPC and DVR. XMEye for PC ( Windows 7,) using cloud vpn entre 2 synology technology, 10, 8,in a corporate setting, vpn entre 2 synology vPNs can be either remote-access (connecting a computer to a network)) or site -to- site (connecting two networks)). Remote-access VPNs allow employees to access their company's intranet from home or while travelling outside the office, herere some of the impressive features that make Ivacy the best VPN for BBC iPlayer: Unlimited bandwidth offered IPv6 and DNS expressvpn with chromecast leak protection Internet kill switch Split tunneling offered Up to 5 multi-logins 4.talk with us about Internet security solutions to protect your IP from online threats. Sony vpn entre 2 synology Broadcast and Business Solution in 4K. M is recommending enterprise clients look at some of the great new Sony or Canon 4K Technology. users can connect the VPN service to a variety of devices and choose the most appropriate protocol to suit their web browsing needs. The companys dedicated apps vpn entre 2 synology for separate devices make it simple to access the service from wired, wiFi or mobile connections.the term proxy site vpn entre 2 synology most commonly refers to an open proxy, or web proxy, using a proxy site, which is a web site that allows a user to surf the internet anonymously.it's a free VPN proxy for first 7 days only. Anti-DDoS servers -Unlimited VPN bandwidth -Friendly 24/7 support -6 VPN connections under 1 account at the same time -Military-grade encryption protocols (OpenVPN,) other cool features you may like: -P2P supported on optimized servers -Servers for extra security: DoubleVPN, get the best VPN speed. Set up VPN and you are ready to go! Ready to surf? Ikev2 / IPsec) -3000 VPN servers in more than 60 countries. Just download the app,Editor Ratings: User Ratings: Total: du suchst einen vpn entre 2 synology VPN-Service den Du kostenlos finch vpn application download nutzen kannst?
http://soupfactory.co.uk/remote-tech-support/vpn-entre-2-synology.html
CC-MAIN-2018-47
refinedweb
1,174
60.45
Searching in Array in C++ In this tutorial, we are going to learn about Searching in Array in C++. We’ll be using an algorithm called Linear Search for this purpose. Linear search is a basic and simple search algorithm. We’ll also implement a C++ Program, that performs the searching task using Linear Seach. The topics that are covered in this tutorial are as follows: - What is a Linear Search Algorithm? - Algorithm and steps to implement the Linear Search. - Coding Linear Search in C++ for an array. Linear Search Definition: A linear search, also known as a sequential search, is a method of finding an element within an array. It checks each element of the array sequentially until a match is found for a particular element or the whole array has been searched. Time and Space Complexity analysis of this method: - Worst Case Time Complexity – O(n) - Best Case Time Complexity – O(1) - Average Time Complexity – O(n) - Worst Case Space Complexity – O(1) Iterative Algorithm: - Take the size of the array, the element that needs to be searched, and elements of the array as input from the user. - Before searching store the index as -1 in variable names “ans”. - Loop through the elements of the array. - If a match is found, then we break the loop and update the value of the “ans” variable with the index of the element. - If no match is found, then display output accordingly. Code: #include<iostream> using namespace std; int main() { int n,k,ans=-1; cout<<"Enter size of array"<<endl; cin>>n; int arr[n]; cout<<"Enter elements of array"<<endl; for(int i=0;i<n;i++) { cin>>arr[i]; } cout<<"Enter element to be searched"<<endl; cin>>k; for(int i=0;i<n;i++) { if(arr[i]==k) { ans=i; break; } } if(ans!=-1) cout<<"The element "<<k<<" is present at index "<<ans; else cout<<"The element "<<k<<" is not there in the array"; return 0; } Output: Enter size of array 5 Enter elements of array 10 20 30 40 50 Enter element to be searched 30 The element 30 is present at index 2
https://www.codespeedy.com/searching-in-array-in-cpp/
CC-MAIN-2020-50
refinedweb
358
59.74
XmStringNCopy (3) - Linux Man Pages XmStringNCopy: A compound string function that creates a copy of a compound string NAMEXmStringNCopy --- A compound string function that creates a copy of a compound string SYNOPSIS #include <Xm/Xm.h> XmString XmStringNCopy( XmString s1, int num_bytes); DESCRIPTION. - s1 - Specifies the compound string. - num_bytes - Specifies the number of bytes of s1 to copy. If this value is less than the length of s1, as many bytes as possible, but possibly fewer than this value, will be appended to s1 such that the resulting string is still a valid compound string. RETURN Returns a new compound string. RELATED XmStringCreate(3) and XmStringFree(3).
https://www.systutorials.com/docs/linux/man/3-XmStringNCopy/
CC-MAIN-2021-25
refinedweb
107
65.01
This is sort of a feature request, and also explaining a problem to see if there is a better way to do this, I am creating a plugin that runs JS Beautify on source code and noticed that after the edit, it erases your current selection and moves the cursor. So I set upon a way to preserve the selection and came up with a solution. #: old_selection = view.sel() Do edits... view.sel(old_selection) class FirmSelection(): def __init__(self, view): self.view = view def __enter__(self): self.old_selection = ] for region in self.view.sel(): self.old_selection.append(region) def __exit__(self, type, value, traceback): self.view.sel().clear() for region in self.old_selection: self.view.sel().add(region) Then you can just: with FirmSelection(view): Do edit... I'm wondering the same right now. Can we please create new instances of RegionSet?
https://forum.sublimetext.com/t/keeping-selection-after-edits/2552/2
CC-MAIN-2016-44
refinedweb
142
52.05
I'm trying to use a java code in xamarin with C #, I was doing well until I got to that part:); Can anyone help me to adapt this part? Answers I would say this looks like a question better suited for the Xamarin Android forum, as it appears to be about just Android, no Forms involved. That said, getter methods are usually properties in Xamarin Android. GetContentResolver is a method on a context it says, so from the Activity or something with a context, try looking for a ContentResolver property. If I am in my MainActivity, typing this.ContentResolvergets me an instance of a ContentResolver. So I understood what you said, so in mainactivity I stated: ContentResolver getContentResolver; So in the line of code I put it and it was, but the problem is that when I put the (), to return the list it does not accept and it turns red. ContentResolver musicResolver = getContentResolver(); It seems that it is a problem in my version of xamarin, since I have researched a lot and it seems that this problem does not exist in others, there they can get getContentResolver (), without problems, in my nor does this component appear. I think we had a miscue somewhere. In native Android, getContentResolver is a method, part of the Context class. In Xamarin Android, it is a property of ContentResolver that can be accessed on any Context instance. Here is an example post on it. I also think because I tried this command, I did not give it a mistake, either. I use all these: using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Android.Provider; using Android.App; using Android.Database; using Android.Net; using Android.App; using Android.Provider; using Android.Util; using Android.Views; using Java.IO; using Java.Util; @Jair_xamarin is there a reason you're still not posting in the Android forum where you'll get the best help for this topic ()? The C# equivalent to the Java you posted should look something like this in an Android Activity class. var musicResolver = this.ContentResolver; var musicUri = Android.Provider.MediaStore.Audio.Media.ExternalContentUri; var musicCursor = musicResolver.Query(musicUri, null, null, null, null); I recommend you read the Stack Overflow link that @AdamMeaney shared. Sorry, where can I move this topic to android category? The line you passed worked, the others I had already adapted: Android.Net.Uri MusicUri = MediaStore.Audio.Media.ExternalContentUri; ICursor musicCursor = musicResolver.Query(MusicUri, null, null, null, null); But will the first line work even without the ()? Here is the code I am adapting: I don't think you can move it, which is why it's best to post in the right place initially. Maybe a moderator can move it, I don't know. Run it and see. You do not need the (). This is an idiomatic change made by Xamarin to make it more C#. Thank you now everything is without error, I have compiled and gives installation error, I will seek a solution I have two doubts in a snippet of this code: Collections.sort(songList, new Comparator<Song>(){ public int compare(Song a, Song b){ return a.getTitle().compareTo(b.getTitle()); } }); I tried to adapt it this way: Collections.Sort(songlist, new Comparer<Song>(){} But he did not accept, I also tried with Icomparator, but due to not having the <> he did not accept. My other question is about the syntax of the code as I noted the following: () {} 0; Is this really right?
https://forums.xamarin.com/discussion/85255/getcontentresolver-equivalent
CC-MAIN-2020-05
refinedweb
603
60.92
Make your SAP Data Hub Distributed Runtime work on the SUSE CaaS Platform In my previous blog, I leveraged the SAP Data Hub, developer edition as my SAP Data Hub Distributed Runtime: This worked well to some extent, but is of course not a supported architecture. Therefore, I will explain how to install the SAP Data Hub Distributed Runtime on the SUSE CaaS Platform which is supported as per SAP Note 2464722 – Prerequisites for installing SAP Data Hub: To start with, I install three SUSE CaaSP nodes as per the respective Deployment Guide. Administration Node - 2 cores - 12 GB RAM - 40 GB disk Please ensure to select Install Tiller during the Initial CaaS Platform Configuration as this will be needed for the SAP Data Hub Distributed Runtime: Master Node - 2 cores - 8 GB RAM - 40 GB disk Worker Node - 4 cores - 20 GB RAM - 80 + 16 GB disks This is the node onto which I will install the SAP Data Hub Distributed Runtime later. To make this work, I need to mount an additional volume as /var/local: Cluster As a result, I got my cluster ready and can monitor its Cluster Status from Velum: As well as my respective Cluster Nodes from my Kubernetes dashboard: With this I configure my Docker Registry to Use self-signed certificates and verify its availability: 424e441f1fef4c629d512f5fa33889f0:~ # curl -iv * Hostname was NOT found in DNS cache * Trying 86.164.155.84... * Connected to registry.dynalias.com (86.164.155.84) port 5000 (#0) * successfully set certificate verify locations: * CAfile: none CApath: /etc/ssl/certs/ * SSLv3, TLS Unknown, Unknown (22): * SSLv3, TLS handshake, Client hello (1): * SSLv2, Unknown (22): * SSLv3, TLS handshake, Server hello (2): * SSLv2, Unknown (22): * SSLv3, TLS handshake, CERT (11): * SSLv2, Unknown (22): * SSLv3, TLS handshake, Server key exchange (12): * SSLv2, Unknown (22): * SSLv3, TLS handshake, Server finished (14): * SSLv2, Unknown (22): * SSLv3, TLS handshake, Client key exchange (16): * SSLv2, Unknown (20): * SSLv3, TLS change cipher, Client hello (1): * SSLv2, Unknown (22): * SSLv3, TLS handshake, Finished (20): * SSLv2, Unknown (20): * SSLv3, TLS change cipher, Client hello (1): * SSLv2, Unknown (22): * SSLv3, TLS handshake, Finished (20): * SSL connection using TLSv1.2 / ECDHE-RSA-AES128-GCM-SHA256 * Server certificate: * subject: C=UK; ST=Warwickshire; O=BOA; CN=registry.dynalias.com * start date: 2018-01-14 12:17:16 GMT * expire date: 2019-01-14 12:17:16 GMT * common name: registry.dynalias.com (matched) * issuer: C=UK; ST=Warwickshire; O=BOA; CN=registry.dynalias.com * SSL certificate verify ok. * SSLv2, Unknown (23): > GET /v2 HTTP/1.1 > User-Agent: curl/7.37.0 > Host: registry.dynalias.com:5000 > Accept: */* > * SSLv2, Unknown (23): < HTTP/1.1 301 Moved Permanently HTTP/1.1 301 Moved Permanently < Docker-Distribution-Api-Version: registry/2.0 Docker-Distribution-Api-Version: registry/2.0 < Location: /v2/ Location: /v2/ < Date: Wed, 17 Jan 2018 16:58:52 GMT Date: Wed, 17 Jan 2018 16:58:52 GMT < Content-Length: 39 Content-Length: 39 < Content-Type: text/html; charset=utf-8 Content-Type: text/html; charset=utf-8 < <a href="/v2/">Moved Permanently</a>. * Connection #0 to host registry.dynalias.com left intact Next, I provide the Kubernetes Persistent Volumes required by the SAP Data Hub Distributed Runtime. Please ensure that their Capacity and Access modes are exactly as shown below, otherwise the Kubernetes Persistent Volume Claims could not be satisfied: Finally, I install Helm to match Tiller:296k 0 0:00:02 0:00:02 --:--:-- 6299k 424e441f1fef4c629d512f5fa33889f0:~ # gunzip helm-v2.6.2-linux-amd64.tar.gz gzip: helm-v2.6.2-linux-amd64.tar already exists; do you wish to overwrite (y or n)? ^C 424e441f1fef4c629d512f5fa33889f0:~ # rm helm-v2.6.2-linux-amd64.tar478k 0 0:00:02 0:00:02 --:--:-- 6476k 424e441f1fef4c629d512f5fa33889f0:~ # gunzip helm-v2.6.2-linux-amd64.tar.gz 424e441f1fef4c629d512f5fa33889f0:~ # tar -xvf helm-v2.6.2-linux-amd64.tar linux-amd64/ linux-amd64/helm linux-amd64/LICENSE linux-amd64/README.md 424e441f1fef4c629d512f5fa33889f0:~ # cp linux-amd64/helm bin/ With this the installations runs smoothly and I am rewarded with a fully operational and supported SAP Data Hub Distributed Runtime: If you needed more compute capacity, you could of course add more nodes. Thanks for your effort. It s very useful. Great blog Frank. Any insights as to the script/process you used to create the Kubernetes Persistent Volumes in the Vora namespace? Hello Robert, I put my Kubernetes Persistent Volumes onto a NFS server like this: For each Kubernetes Persistent Volume you would have to update the name, capacity and accessModes respectively. Best regards Frank Hi Frank.....Any reason for not letting the installer set up persistent volumes on NFS during the installation procedure in this scenario? Hello Robert, When you chose the on premise installation option for the SAP Data Hub Distributed Runtime then only the vora/vflow-stdlib-pvc persistent volume is put on nfs. The other volumes are put on a local host path which I do not want, but that depends on your requirements. Best regards Frank Thanks for the clarification. thought my issue might have to do with nfs. Have you experienced anything like the following? I get lost connection to pod every time! "Using vora consul image... Deploying vora-consul with: helm install --namespace vora -f values.yaml -f /root/SAPVora-2.1.60-DistributedRuntime/stateful-replica-conf.yaml --set docker.registry=localhost:5000 --set rbac.enabled=true --set imagePullSecret= --set docker.imagePullSecret= --set version.package=2.1.60 --set docker.image=localhost:5000/vora/consul --set docker.imageTag=0.9.0-sap10 --set version.component=0.9.0-sap10 --set dontUseExternalStorage=true --set useHostPath=true --set components.disk.useHostPath=true --set components.dlog.useHostPath=true . --wait --timeout 900 E0213 05:09:03.055798 63085 portforward.go:178] lost connection to pod Error: transport is closing Deployment failed, please check logs above and Kubernetes dashboard for more information!" Hi Robert, How did you go past the above error? I am also facing the same in Caasp cluster. Regards, Vasanth HI Frank,. Hi Frank , we have Installed SUSE Caas platform with 2 nodes . how to cluster both nodes . when i am logging in to kubernetus dashboard i can only see local server, unable to see worker node. can we run autoyast command in 2 node direclty or do we need to follow some other process. as we have performed normal installation on 2nd node. Regards karthik Hey everyone! Just a quick note from Rob your friendly CaaS Platform Strategist (and creator of this): Please never ever ever install a cluster that only has 1 master and 1 worker. You will not have etcd quorum if you do this and if you reboot the worker or master it's highly likely your cluster will be trashed beyond recovery. So when using SUSE CaaS Platform please always have at least 2 worker nodes and 1 master node. This will allow 3 instances of etcd to run and allow you to survive a single node failure without breaking quorum. As another side note - it's worth mentioning if you use local-only storage your pods won't be able to start up on another node. Always use shared storage for application data. In this case I can see an external NFS server is being used which is great! (although I'm unsure what /var/local is being used for. If it's temp/scratch data then that's great but for anything requiring persistence we recommend using NFS or Ceph based backends). But great blog post Frank! - It's great to see the platform being used for actual workloads and interesting for me to see what our partners and customers are getting up to in the real world 🙂 (if anyone is considering purchasing SUSE CaaS Platform or wants a demo/trial and needs assistance feel free to email me at rob.decanha-knight@suse.com and I'll be happy to point in the right direction 🙂 ) Rob Hi Rob, we use only Suse 12 versions for our sap installations.. do we have any proper documentation to create cluster with 2 or 3 nodes (Kuberenets )
https://blogs.sap.com/2018/01/17/make-your-sap-data-hub-distributed-runtime-work-on-the-suse-caasp/
CC-MAIN-2022-27
refinedweb
1,347
56.55
Ramon Berke637 Points I am stuck in a task can somebody tell me my mistake? The task says "Oops, I forgot that I need to break out of the loop when the current item is the string "STOP". Help me add that code!" I wrote this but the bummer says "Didn't find the right items being printed.". Can somebody tell me my mistake? def loopy(items): # Code goes here for item in items: print(item) if item == "STOP": break 1 Answer Cheo R20,552 Points You're on the right track. Just move your print statement below the if block and think about why. Moderator Edit: Moved response from Comment Section to Answers. Ramon Berke637 Points Ramon Berke637 Points Can you send the code too because it easier to understand.
https://teamtreehouse.com/community/i-am-stuck-in-a-task-can-somebody-tell-me-my-mistake
CC-MAIN-2017-30
refinedweb
131
91.11
Python Classes And Objects - Classes in Python. Focusing first on the data, each thing or object is an instance of some class. The primitive data structures available in Python, like numbers, strings, and lists are designed to represent simple things like the cost of something, Python Classes And Objects - Classes in Python. Focusing first on the data, each thing or object is an instance of some class. The primitive data structures available in Python, like numbers, strings, and lists are designed to represent simple things like the cost of something, After Stack Overflow predicted that by 2019, Python will outstrip other languages in terms of active developers, the demand for Certified Python Developers is only growing. Python follows object-oriented programming paradigm. It deals with declaring python classes, creating objects from them and interacting with the users. In an object-oriented language, the program is split into self-contained objects or you can say into several mini-programs. Each object is representing a different part of the application which can communicate among themselves. In this python class blog, you will understand each aspect of classes and objects in the following sequence: What is a Python Class?Methods and Attributes in a classWhat are Objects?* OOPs Concepts: InheritancePolymorphismAbstraction* Let’s get started.:-) A class in python is the blueprint from which specific objects are created. It lets you structure your software in a particular way. Here comes a question how? Classes allow us to logically group our data and function in a way that it is easy to reuse and a way to build upon if need to be. Consider the below image. In the first image (A), it represents a blueprint of a house that can be considered as Class. With the same blueprint, we can create several houses and these can be considered as Objects. Using a class, you can add consistency to your programs so that they can be used in cleaner and efficient ways. The attributes are data members (class variables and instance variables) and methods which are accessed via dot notation. Class variable is a variable that is shared by all the different objects/instances of a class.Instance variables are variables which are unique to each instance. It is defined inside a method and belongs only to the current instance of a class.*Methods *are also called as functions which are defined in a class and describes the behaviour of an object. Now, let us move ahead and see how it works in PyCharm. To get started, first have a look at the syntax of a python class. Syntax: class Class_name: statement-1 . . statement-N Here, the “class” statement creates a new class definition. The name of the class immediately follows the keyword “class” in python which is followed by a colon. To create a class in python, consider the below example: class employee: pass #no attributes and methods emp_1=employee() emp_2=employee() #instance variable can be created manually emp_1.first='aayushi' emp_1.last='Johari' emp_1.email='[email protected]' emp_1.pay=10000 emp_2.first='test' emp_2.last='abc' emp_2.email='[email protected]' emp_2.pay=10000 print(emp_1.email) print(emp_2.email) *Output *– Now, what if we don’t want to manually set these variables. You will see a lot of code and also it is prone to error. So to make it automatic, we can use “init” method. For that, let’s understand what exactly are methods and attributes in a python class. Now creating a class is incomplete without some functionality. So functionalities can be defined by setting various attributes which acts as a container for data and functions related to those attributes. Functions in python are also called as Methods. Talking about the init* method*, it is a special function which gets called whenever a new object of that class is instantiated. You can think of it as initialize method or you can consider this as constructors if you’re coming from any another object-oriented programming background such as C++, Java etc. Now when we set a method inside a class, they receive instance automatically. Let’s go ahead with python class and accept the first name, last name and salary using this method. class employee: def __init__(self, first, last, sal): self.fname=first self.lname=last self.sal=sal self.email=first + '.' + last + '@company.com' emp_1=employee('aayushi','johari',350000) emp_2=employee('test','test',100000) print(emp_1.email) print(emp_2.email) Now within our “init” method, we have set these instance variables (self, first, last, sal). Self is the instance which means whenever we write self.fname=first, it is same as emp_1.first=’aayushi’. Then we have created instances of employee class where we can pass the values specified in the init method. This method takes the instances as arguments. Instead of doing it manually, it will be done automatically now. Next, we want the ability to perform some kind of action. For that, we will add a method to this class. Suppose I want the functionality to display the full name of the employee. So let’s us implement this practically. class employee: def __init__(self, first, last, sal): self.fname=first self.lname=last self.sal=sal self.email=first + '.' + last + '@company.com' def fullname(self): return '{}{}'.format(self.fname,self.lname) emp_1=employee('aayushi','johari',350000) emp_2=employee('test','test',100000) print(emp_1.email) print(emp_2.email) print(emp_1.fullname()) print(emp_2.fullname()) Output – As you can see above, I have created a method called “full name” within a class. So each method inside a python class automatically takes the instance as the first argument. Now within this method, I have written the logic to print full name and return this instead of emp_1 first name and last name. Next, I have used “self” so that it will work with all the instances. Therefore to print this every time, we use a method. Moving ahead with Python classes, there are variables which are shared among all the instances of a class. These are called as class variables. Instance variables can be unique for each instance like names, email, sal etc. Complicated? Let’s understand this with an example. Refer the code below to find out the annual rise in the salary. class employee: perc_raise =1.05 def __init__(self, first, last, sal): self.fname=first self.lname=last self.sal=sal self.email=first + '.' + last + '@company.com' def fullname(self): return '{}{}'.format(self.fname,self.lname) def apply_raise(self): self.sal=int(self.sal*1.05) emp_1=employee('aayushi','johari',350000) emp_2=employee('test','test',100000) print(emp_1.sal) emp_1.apply_raise() print(emp_1.sal) Output – 350000 367500 As you can see above, I have printed the salary first and then applied the 1.5% increase. In order to access these class variables, we either need to access them through the class or an instance of the class. Now, let’s understand the various attributes in a python class. Attributes in Python defines a property of an object, element or a file. There are two types of attributes: Built-in Class Attributes: There are various built-in attributes present inside Python classes. For example dict, doc, _name _, etc. Let me take the same example where I want to view all the key-value pairs of employee1. For that, you can simply write the below statement which contains the class namespace: print(emp_1.__dict__) After executing it, you will get output such as: {‘fname’: ‘aayushi’, ‘lname’: ‘johari’, ‘sal’: 350000, ’email’: ‘[email protected]’}Attributes defined by Users: Attributes are created inside the class definition. We can dynamically create new attributes for existing instances of a class. Attributes can be bound to class names as well. Next, we have public, protected **and private** attributes. Let’s understand them in detail: Next, let’s understand the most important component in a python class i.e Objects. As we have discussed above, an object can be used to access different attributes. It is used to create an instance of the class. An instance is an object of a class created at run-time. To give you a quick overview, an object basically is everything you see around. For eg: A dog is an object of the animal class, I am an object of the human class. Similarly, there can be different objects to the same phone class. This is quite similar to a function call which we have already discussed. Let’s understand this with an example: class MyClass: def func(self): print('Hello') # create a new MyClass ob = MyClass() ob.func() Moving ahead with python class, let’s understand the various OOPs concepts. OOPs refers to the Object-Oriented Programming in Python. Well, Python is not completely object-oriented as it contains some procedural functions. Now, you must be wondering what is the difference between a procedural and object-oriented programming. To clear your doubt, in a procedural programming, the entire code is written into one long procedure even though it might contain functions and subroutines. It is not manageable as both data and logic get mixed together. But when we talk about object-oriented programming, the program is split into self-contained objects or several mini-programs. Each object is representing a different part of the application which has its own data and logic to communicate among themselves. For example, a website has different objects such as images, videos etc. Object-Oriented programming includes the concept of Python class, object, Inheritance, Polymorphism, Abstraction etc. Let’s understand these topics in detail. Inheritance allows us to inherit attributes and methods from the base/parent class. This is useful as we can create sub-classes and get all of the functionality from our parent class. Then we can overwrite and add new functionalities without affecting the parent class. Let’s understand the concept of parent class and child class with an example. As we can see in the image, a child inherits the properties from the father. Similarly, in python, there are two classes: Parent class ( Super or Base class) Child class (Subclass or Derived class ) A class which inherits the properties is known as Child *Class whereas a class whose properties are inherited is known as *Parent class. Inheritance refers to the ability to create Sub-classes that contain specializations of their parents. It is further divided into four types namely single, multilevel, hierarchical and multiple inheritances. Refer the below image to get a better understanding. Let’s go ahead with python class and understand how inheritance is useful. Say, I want to create classes for the types of employees. I’ll create ‘developers’ and ‘managers’ as sub-classes since both developers and managers will have a name, email and salary and all these functionalities will be there in the employee class. So, instead of copying the code for the subclasses, we can simply reuse the code by inheriting from the employee.): pass emp_1=developer('aayushi', 'johari', 1000000) print(emp_1.email) Output - [email protected] As you can see in the above output, all the details of the employee class are available in the developer class. Now what if I want to change the raise_amount for a developer to 10%? let’s see how it can be done practically. emp_1=developer('aayushi', 'johari', 1000000) print(emp_1.raise_amount) Output - 1.1 As you can see that it has updated the percentage rise in salary from 4% to 10%. Now if I want to add one more attribute, say a programming language in our init method, but it doesn’t exist in our parent class. Is there any solution for that? Yes! we can copy the entire employee logic and do that but it will again increase the code size. So to avoid that, let’s consider the below code: def __init__(self, first, last, sal, prog_lang): super().__init__(first, last, sal) self.prog_lang=prog_lang emp_1=developer('aayushi', 'johari', 1000000, 'python') print(emp_1.prog_lang) Therefore, with just a little bit of code, I have made changes. I have used super.init(first, last, pay) which inherits the properties from the base class. To conclude, inheritance is used to reuse the code and reduce the complexity of a program. Polymorphism in Computer Science. Let us understand with an example: class Animal: def __init__(self,name): self.name=name def talk(self): pass class Dog(Animal): def talk(self): print('Woof') class Cat(Animal): def talk(self): print('MEOW!') c= Cat('kitty') c.talk() d=Dog(Animal) d.talk() Output – Meow! Woof Next, let us move to another object-oriented programming concept i.e Abstraction. Abstraction is used to simplify complex reality by modelling classes appropriate to the problem. Here, we have an abstract class which cannot be instantiated. This means you cannot create objects or instances for these classes. It can only be used for inheriting certain functionalities which you call as a base class. So you can inherit functionalities but at the same time, you cannot create an instance of this particular class. Let’s understand the concept of abstract class with an example below: from abc import ABC, abstractmethod class Employee(ABC): @abstractmethod def calculate_salary(self,sal): pass class Developer(Employee): def calculate_salary(self,sal): finalsalary= sal*1.10 return finalsalary emp_1 = Developer() print(emp_1.calculate_salary(10000)) Output – 11000.0 As you can see in the above output, we have increased the base salary to 10% i.e. the salary is now 11000. Now, if you actually go on and make an object of class “Employee”, it throws you an error as python doesn’t allow you to create an object of abstract class. But using inheritance, you can actually inherit the properties and perform the respective tasks. So guys, this was all about python classes and objects in a nutshell. We have covered all the basics of Python class, objects and various object-oriented concepts in python, so you can start practicing now. I hope you guys enjoyed reading this blog on “Python Class” and are clear about each and every aspect that I have discussed above. After python class, I will be coming up with more blogs on Python for scikit learn library and array. Stay tuned!
https://morioh.com/p/5fb7b1141021
CC-MAIN-2020-16
refinedweb
2,367
57.77
Rails has had the has_one :through association for a while now, and you probably use it on occasion. But, has it ever given you the heebie-jeebies a little bit? Maybe something happens now and then that doesn’t seem quite right? Well, the reason for this is that HasOneThroughAssociation, the class that ActiveRecord uses (shockingly) to implement has_one :through associations, is a subclass of HasManyThroughAssociation. Whhaaaaaaaaaat? Yes, oddly enough, a has_one :through association is a collection that is special-cased to always return just one element. Seems kind of dirty, doesn’t it? I have two, related, problems with this inheritance relationship. First, it violates Liskov substitutability. One cannot in any way argue that a has_one :through association IS A has_many :through association; substituting one for the other would not be likely to maintain a program’s correctness. Second, the inheritance relationship exists to share implementation, not interface. Among others, the Gang of Four have described, persuasively, why this is a terrible idea. More practically, I’ve now run into two serious bugs caused by this relationship. The first one caused newly created has_one :through associations to return an empty array rather than nil. I fixed that here, with the help of wunderkind David Stevenson. The second I ran into in the last few days while working on this patch, which I’ve written about here. It turns out that trying to get #method_missing to behave sensibly for all non-collection associations is difficult when one of those associations inherits a pile of collection-specific functionality. So, in order to make my #method_missing patch work I had to rewrite HasOneThroughAssociation with a more appropriate superclass (I used HasOneAssociation). You can find that patch here. Hopefully this change will make its way into the Rails codebase and will make lives easier for generations to come. > One cannot in any way argue that a has_one :through > association IS A has_many :through association; > substituting one for the other would not be likely to > maintain a program’s correctness. I beg to differ. You make the argument yourself: > a `has_one :through` association is a collection > that is special-cased to always return just one > element Polymorphism, baby! It’s like squares and rectangles. A square is a rectangle, but a rectangle cannot be a square. A square is a rectangle with special restrictions; both are quadrilaterals where all four of its angles are right angles, but a square extends this to say that all four sides have equal length. A `has_one :through` is a `has_many :through` relationship, but it can only return one element. A `has_one :though` is a `has_many :through`, but a `has_many :though` cannot be a `has_one :through` December 28, 2008 at 4:39 pm You’ve fallen into a classic inheritance fallacy. A square is a rectangle in mathematics, but not in object oriented design. The purpose of inheritance is to allow objects to share interfaces, or behavior if you prefer. Consider this example: def resize(rectangle) rectangle.height = 10 rectangle.width = 3 puts rectangle.area end What happens if you pass a square into that method? I’m not entirely certain, but you won’t end up with a shape that has an area of 30. The square is not substitutable for the rectangle, so it is not an appropriate subclass of rectangle. Analogously, consider any method that treats an association as a collection by calling #size or #each. Passing a has_one :through association to that method would make no sense. A HOT is not substitutable for a HMT, and therefore inheritance is not the appropriate approach. December 28, 2008 at 6:40 pm No, that is poor class design. The square should throw an exception when you attempt to resize it into something that is not a square. That’s part of the restrictions of the square, so the square class should ensure it. Otherwise, it is not a square. Same thing for the `has_one :through` method. It has special checks in place so that you cannot assign a collection to it. If you could, then it would not be a `has_one :through` That is good OO design. December 29, 2008 at 12:34 am Why throw an exception when a user tries to resize a square to violate its constraints, rather than simply *not define* the behavior that allows the user to violate the constraints? By that logic you should define Square#radius to throw an exception as well. Please explain how that is good OO design. Even if Square#width= were to throw an exception, passing an instance of square to the code snippet above wouldn’t lead to a correct program. Thus, it violates Liskov Substitution, and an inheritance relationship is not appropriate. I’m willing to be proven wrong on this point, but it seems to me a fairly clear application of well understood OO rules. I would love to hear a well-supported argument that shows otherwise. December 29, 2008 at 1:31 am Define correct program. If you mean allowing an invalid operation on an object to go through, unchecked, without some indication that it is invalid, then sure, you have a correct program. However, I argue that the code snippet violates the rules of what defines a Square; if your Square class doesn’t have check constraints on the dimensions to ensure that they are equal, then your class has not correctly modeled a Square, and, therefor, your program is incorrect. It makes sense to call `Square#resize` on a square. It does not make sense to call `Square#radius`. So, yes, trying to call `Square#radius` should throw an exception (specifically in the case of Ruby, a NoMethodError) , as should any other Shape where calling `radius` on it would make no sense. If you allow such calls to go through without raising some sort of error, then you have not correctly modeled the Shape in question. Again, you have an incorrect program. December 29, 2008 at 3:44 am Clearly we’ll have to agree to disagree. December 29, 2008 at 4:26 am Clearly ;) Interesting debate, though. December 29, 2008 at 2:07 pm
http://pivotallabs.com/has-one-ish-through/?tag=agile
CC-MAIN-2014-23
refinedweb
1,025
64
iLightFactoryList Struct Reference [Lighting] A list of light factories. More... #include <iengine/light.h> Inheritance diagram for iLightFactoryList: Detailed Description A list of light factories. Main ways to get pointers to this interface: Main users of this interface: Definition at line 631 of file light.h. Member Function Documentation Add a light factory. Find a light factory and return its index. Find a light factory by name. Return a light factory by index. Return the number of light factories in this list. Remove the nth light factory. Remove a light factory. Remove all light factory. The documentation for this struct was generated from the following file: Generated for Crystal Space 2.1 by doxygen 1.6.1
http://www.crystalspace3d.org/docs/online/api/structiLightFactoryList.html
CC-MAIN-2014-10
refinedweb
117
54.39
>>>>> "adl" == Alexandre Duret-Lutz <address@hidden> writes: adl> I'd really appreciate comments on the following patch. adl> The intent is to diagnose target clashes. adl> [...]/lib/am/program.am: ... `ctags' previously defined here. adl> The locations could be improved but that's not the point here; adl> for now I'm just using whatever location is available. At least adl> Automake doesn't produce a bogus Makefile silently. adl> 1. update specflag7.test and specflag8.test to reflect they adl> now test for this feature adl> 2. update ctags/etags example in the manual (probably change adl> it to egrep/fgrep...) adl> 3. add tests cases for the new manual example (since adl> specflag7.test and specflag8.test no longer test this) I think improving the error location would also be good (especially in light of Bruce's recent remarks on the main list). If it is too hard (perhaps it is) then we need a PR for it. (BTW I've noticed you've been really good about submitting PRs and stuff. Cool.) I think the idea is fine. I'm a bit concerned by the FIXMEs about redefining a target when there is a multi-target "foo bar baz:". I didn't read the patch very closely. At this point I'm sure your judgement on implementation issues is more sound than mine. What about setting things up now to reject targets that are in our reserved namespace? Do we want to actually reject them? I suspect so, though the counterargument is that overriding can still let the user work around automake when necessary... What about a section in the manual explaining how to build a program whose name clashes with a standard target? adl> automake: `LDADD' is a target; expected a variable adl> Now I'm wondering if this error still makes any sense today. I adl> guess it was because targets and variables used to share the same adl> namespace in older versions of Automake? While what you say is definitely part of it, I think it might also have been due to someone making a "spelling error" -- writing "foo:..." instead of "foo = ...". You'd have to dig in the logs to find out for sure. I'm not sure whether it is really worth diagnosing this sort of problem. In the old days I used to add warnings and errors like this pretty randomly, based on bug reports I got. But there's a plausible argument that I was trying too hard to prevent people from making mistakes. Tom
http://lists.gnu.org/archive/html/automake-patches/2002-09/msg00019.html
CC-MAIN-2015-22
refinedweb
425
74.39
camo Camo is all about making insecure assets look secure. This is an SSL image proxy to prevent mixed content warnings on secure pages served from GitHub. We want to allow people to keep embedding images in comments/issues/READMEs. There's more info on the GitHub blog. Using a shared key, proxy URLs are encrypted with hmac so we can bust caches/ban/rate limit if needed. Camo currently runs on node version 0.10.29 at GitHub on heroku. Features - Max size for proxied images - Follow redirects to a certain depth - Restricts proxied images content-types to a whitelist - Forward images regardless of HTTP status code At GitHub we render markdown and replace all of the src attributes on the img tags with the appropriate URL to hit the proxies. There's example code for creating URLs in the tests. URL Formats Camo supports two distinct URL formats:<digest>?url=<image-url><digest>/<image-url> The <digest> is a 40 character hex encoded HMAC digest generated with a shared secret key and the unescaped <image-url> value. The <image-url> is the absolute URL locating an image. In the first format, the <image-url> should be URL escaped aggressively to ensure the original value isn't mangled in transit. In the second format, each byte of the <image-url> should be hex encoded such that the resulting value includes only characters [0-9a-f]. Configuration Camo is configured through environment variables. PORT: The port number Camo should listen on. (default: 8081) CAMO_HEADER_VIA: The string for Camo to include in the Viaand User-Agentheaders it sends in requests to origin servers. (default: Camo Asset Proxy <version>) CAMO_KEY: The shared key used to generate the HMAC digest. CAMO_LENGTH_LIMIT: The maximum Content-LengthCamo will proxy. (default: 5242880) CAMO_LOGGING_ENABLED: The logging level used for reporting debug or error information. Options are debugand disabled. (default: disabled) CAMO_MAX_REDIRECTS: The maximum number of redirects Camo will follow while fetching an image. (default: 4) CAMO_SOCKET_TIMEOUT: The maximum number of seconds Camo will wait before giving up on fetching an image. (default: 10) CAMO_TIMING_ALLOW_ORIGIN: The string for Camo to include in the Timing-Allow-Originheader it sends in responses to clients. The header is omitted if this environment variable is not set. (default: not set) CAMO_HOSTNAME: The Camo-Hostheader value that Camo will send. (default: unknown) CAMO_KEEP_ALIVE: Whether or not to enable keep-alive session. (default: false) Deployment docker run -p 8081:8081 -e 'CAMO_KEY'='<my application key>' wfjsw/camo How to get encrypted URI (in Ruby) Remember to replace your application key! def request_uri(image_url) hexdigest = OpenSSL::HMAC.hexdigest( OpenSSL::Digest.new('sha1'), '<my application key>', image_url) encoded_image_url = hexenc(image_url) "#{config['host']}/#{hexdigest}/#{encoded_image_url}" end
https://hub.docker.com/r/wfjsw/camo/
CC-MAIN-2018-26
refinedweb
449
57.67
.NET deployment So I'm thinking of writing a shrinkwrap desktop app in .NET -- my first .NET app, actually. I don't expect to do online delivery (I may make it available as an option, but the target market is government and nonprofit social service agencies, which tend toward the lower end of the tech-savviness spectrum). Assuming that none (or close to none) of the users will have the .NET runtime, how difficult is it to deliver a .NET app on CD? Can a single setup program install the .NET runtime, copy the files over, and create shortcuts? Is there somewhere in the VS.NET online help where I should go to RTFM? (= Sam Gray Friday, January 10, 2003 Not hard. A single app can do it all. However - not easy to do using just the tools in the VS.NET package. The issue is that the setups it builds themselves have a runtime dependency on the Framework. So there's a chicken and egg problem. With a more professional tool, such as InstallShield Express (or Developer), you can bootstrap everything, including the Installer and the Framework, from a single setup. Mike Gunderloy Friday, January 10, 2003 I have a somewhat related question: if a .Net program uses "old" ActiveX controls, what do you need to install on the target machine (in addition to the .Net Framework and the executable) ? More specifically, my C# app uses the WebBrowser control. In addition to the executable, there are two files created by the compiler: Interop.SHDocVw.dll and AxInterop.SHDocVw.dll - so, do I need to copy them both ? (I did, and it all works just fine). Mike Friday, January 17, 2003 Yes, as well as the Interop assemblies you will need the actual ActiveX/COM components also. Duncan Smart Sunday, January 19, 2003 Yes, of course the control DLL should be there, no questions about it (in my case, the web browser control already was there). As for the interop dlls, why are there two of them ? Mike Monday, January 20, 2003 The AxInterop one contains the "ActiveX" hostable control (i.e. the control you drag and drop onto a form) whereas the plain old Interop one contains the "OLE automation" server stuff (i.e. you can instantiate and automate an IE window). You will need both. Top Tip: with those methods with lots of optional parameters... which aren't actually optional in C#, use "System.Reflection.Missing.Value" e.g.: browser.Navigate("http://...", Missing.Value, Missing.Value, Missing.Value, Missing.Value) In addition, if you want to navigate into the DOM of the hosted document import "Microsoft HTML Object Library (MSHTML.TLB)" which get you interfaces such as mshtml.HTMLDocument, mshtml.HTMLParaElement etc... e.g. using mshtml; ... HTMLDocument doc = (HTMLDocument)browser.Document; string html = doc.body.innerHTML; Duncan Smart Monday, January 20, 2003 Yes, I know about the DOM, but thanks anyway. As for the missing value, is it faster/better than using ref(nullObject), where nullObject is defined as Object nullObject = 0; Speaking of the web browser control, it really sucks that you cannot handle its events in C# (I am talking about things like OnBeforeNavigate, NavigateComplete, etc.). Supposedly this will be fixed in the next release of the framework. Mike Wednesday, January 22, 2003 Recent Topics Fog Creek Home
https://discuss.fogcreek.com/dotnetquestions/default.asp?cmd=show&ixPost=994&ixReplies=6
CC-MAIN-2018-26
refinedweb
552
58.99
Winter 2015 02/24/2015 9:00 am: Testing Irmak's voice.....Nope, still not working. 9:15 am: Introduction to Fletcher. Hold on to your seat, Dorothy, 'cause Kansas is going bye-bye. 9:30 am: More on databases: The concept of NoSQL databases and MongoDB 10:15 am: MongoDB Challenges 12:00 pm: The dreaded lunchtime. Stay warm. 1:30 pm: Back for glorious work on Mongo challenges and Fletcher data gathering 3:00 pm: Plot.ly workshop with Brooke Parsons from Plot.ly 5:00 pm: The End Intro to Mongo Mongo query documentation Pymongo tutorial NoSQL and MongoDB slides (198.3 KB) Make sure that mongodb is setup and the database server ( mongod) is running. We are going to work with reviews of Heavy Metal movies. Hellz Yeah. Unzip and unpickle the following file: heavy_metal_parsed.pkl.zip (1.1 MB) import pickle with open("heavy_metal_parsed.pkl", 'r') as datafile: heavy_metal_reviews = pickle.load(datafile) It's a list of dictionaries. One dictionary per review: perfect for a mongo document. The key raw has the full text as a list of lines. For example, to see the first review, you can do: first_review = heavy_metal_reviews[0] for line in first_review['raw']: print line which will give you: 200 MOTELS (1971) DIRECTORS: Tony Palmer, Frank Zappa CAST: Frank Zappa, Ringo Starr, Mark Volman, Howard Kaylan, Keith Moon METAL CRED Frank Zappa Nun Desecration THE MEAT Beyond his metal sainthood for battling the censor-witches of the PMRC and getting named checked by Deep Purple in “Smoke on the Water”, musical visionary Frank Zappa led many rock fans to heavy metal. And, from there, he led many metal fans to the outer expanses of rock’s possibilities. Zappa also opened countless banging heads to the far reaches of jazz, classical, doo-wop, and any other art form that could involve (brilliant) noise and (brilliantly dumb) dirty jokes. 200 Motels is Zappa’s first crack at major motion picture madness, and it embodies the much forgotten cultural moment when acid rock tumbled forever into the black pits of rising heavy metal. Surrealistic sketches and psychedelic set pieces about the insanity of a being on tour are interspersed among performances in which the Mothers jam with London Philharmonic. Ringo Starr plays Zappa during the talking parts. Zappa himself, plays guitar throughout, demonstrating how very much of a six-string maestro he was, every lick on par with his future collaborators Steve Vail and Yngwie Malmsteen. SOLID METAL NUGGETS - A psychedelic cartoon interlude admiringly tweaks Black Sabbath and Grand Funk Railroad. - Keith Moon, madman drummer of the Who, pops up—and off—as “The Hot Nun.” Let's see what other fields each document has: print first_review.keys() shows ['raw', 'head', 'metal_cred', 'title', 'direct', 'solid_metal_nuggets', 'cast', 'the_meat', 'year', 'sections'] Basically, each section in the review is parsed into it's own key. Ok, put these documents into a mongodb collection. For these challenges, do not use the heavy_metal_reviews list directly. Use mongo queries (you can use the mongo client directly or use pymongo from within python). Make a histogram of the years in the data. How many metal movies came out over the years? Find the cast member that appeared in most Heavy Metal movies. Is there one that is shared by more than one of these movies? Or are they all completely different actors for every movie? Find the most used words in Heavy Metal film titles. Is there a word that appears in a lot of them? Is it "The"? If it is something like "the", How can you get around that? Find one "meaningful" word that appears the most (this means non-structural word, unlike "the" or "a" or "in") METAL CRED section lists themes included in these movies that makes them more metal. What were the top 5 metal cred keywords in the 70s? In 80s? In 90s, In 2000s? Let's use the length of the METAL CRED section as a proxy score for how metal a movie is. Let's call this the METAL SCORE. To each mongo document, add the metal_score as a new field. Find the director that is MOST METAL per movie (director with the highest average metal score). Remember that some movies have multiple directors. The majority of directors and actors will have worked on a single movie. See if there are any directors that worked with an actor more than once. If so, find the director-actor duo that have worked together the most times. Create an index on the 'director' field to make the queries involving it faster. What is an index? Creating an index in mongo Creating an index in pymongo Single field index on mongo Mongo documentation on indexes For each decade, make a histogram of metal scores. Also, calculate the average metal score for each decade. Which decade was the most pure metal decade? In the latest version of mongo, you can do a text query. To do this, you need to create one (only one) text-based index. Let's index the_meat field so we can make text search queries on it (in pymongo): db.reviews.create_index([("the_meat", pymongo.TEXT,)]) Now you can do text search. For example, let's search for the phrase "hitting power chords" within "the_meat" fields of all our documents. db.reviews.find({"$text": {"$search": "hitting power chords"}}).count() 206 It has found 206 reviews. I can print the titles of the first 10 reviews that were returned in this text search: ten_matches = r.find({"$text": {"$search": "hitting power chords"}}).limit(10) for match in ten_matches: print match["title"] DOMINATOR REPO: THE GENETIC OPERA GREMLINS 2: THE NEW BATCH VICE SQUAD THE JERKY BOYS: THE MOVIE THE SONG REMAINS THE SAME THE EXORCIST THE CROW CANNIBAL HOLOCAUST HOSTEL Enjoy your text searches : ) These can be very useful in some apps.
http://senoni.com/nasdag/metis/metisw7d2.html
CC-MAIN-2019-30
refinedweb
976
73.98
While there are seemingly countless tutorials, articles, and assorted commentaries on using TexturePacker with Flash (and usually Starling), it seems there are very few articles out there about TexturePacker’s creator’s (Andreas Löw) other equally fantastic tool PhysicsEditor. Since I’m currently working on a game that makes extensive use of this software, I thought I’d take a bit of time off to write a little about it. If you don’t know what it is, in a nutshell, PhysicsEditor allows you to import .png files, trace their shapes, then export matching physics bodies for the framework of your choice (assuming your choice is AndEngine, Box2D, CitrusEngine, Corona, Chipmunk, Gideros, Lime + Corona, Nape, QuickBox2D, or RapaNui – and, really, what else is there?) in code form. I’ll give a quick run through on exporting some bodies for the Nape AS3 engine, so if you want to be able to compile the end result, you’ll need the latest Nape release, PhsyicsEditor, of course (there’s a free trial available), and Starling. First you’ll need some images to play around with. Just for complexity, for this demo, I chose a gear and a wacky ground I just drew up at random. You’re welcome to play around with these, but for the sake of full disclosure, I found the gear in a Google image search, so I wouldn’t go using it for anything other than testing. One of the great things about PhysicsEditor is that you can simply load in the actual textures you plan on using in your game or app so unless you wind up resizing your assets later, you’ll get a perfect WYSIWYG result. So, fire up PE and load in your images using the ‘Add Sprites’ button on the top tool bar. Once imported, to the left you’ll see a list of the currently added images. If you used your own images and didn’t give them meaningful names (e.g. you named them ’01.png’ or some such thing), now would be a good time to do so. Double click the name of the image and change it to something more meaningful like ‘ground’, or ‘gear’ or whatever (you’ll see why you’ll want to do so in a bit). Now on your images (one at a time), click the ‘shape tracer’ button (the little magic wand icon just above the big image in the center). This will open a new window called ‘Tracer’ and automatically trace a shape around your image. Of course you’re welcome to play around with the settings here, but I find the defaults to work just fine. More than likely the shape won’t be perfect, but we’ll fix that in just a second. After clicking ‘OK’ in the Tracer window, you’ll be taken back to the Main window, but now see a reddish shape around your image. For a closer look, you can use the slider beneath the image window to zoom in and out. As mentioned, your traced shape probably won’t be perfect, but at this point, you can click on vertex points to move them around. And by right clicking, you can delete any unnecessary vertex points or add new ones anywhere on the path. The goal is to trace a path as perfectly as possible around your image while keeping the vertex count as low as possible. After about 30 seconds of mucking about, my gear image wound up looking like this. My ground image took even less fixing up. Next you’ll want to choose an exporter. From the drop down menu to the left select ‘Nape (AS3)’. You’ll see some more settings you can play around with, but the only thing I changed in this demo was the anchor point which I placed right in the center for both ground and gear. You can do this quickly and easily by changing the relative x and y coordinates to both be .5. Like the Flash display list, this is the registration point of your physics body and will affect how they’re positioned when we get to that point. At this time, you’re ready to go. However, if you were to publish right now, you would wind up with several errors in your code. This is because the Nape Physics API has been updated since the last release PhysicsEditor (I’m sure it’s hard keeping up to date when supporting all those freaking engines). Thankfully, Andreas Löw has made it incredibly easy to keep the exporters up to date ourselves. Go to the installation directory of PhysicsEditor and find the ‘exporters’ directory. Browse into that then go down and move into the ‘nape-as3′ directory. Inside there, you’ll see a ‘nape.as’ file. Open that in a text or code editor and every place you see ‘cbType =’, change it to ‘cbTypes.add()’. So, for example: will become: and: will become: etc. If you’re not familiar with Nape, CBTypes are short for Call Back Types. You can create your own call back types and apply them to physics bodies so that interactions will have different results. For example, a collision between two gears may play a different sound than a collision between a gear and the ground. In previous versions of Nape each body could only have a single call back type applied. Now, however, call back types are added to a list and you can have several on a single body. For this basic demo we won’t bother with any cbTypes, but, again, without making these changes to the export, your final project will be filled with errors. NOTE: by the time you read this, this discrepancy may be fixed and none of this may be necessary. I’m currently using the 1.0.9 version of PhysicsEditor. So, once the exporter file has been fixed (you only have to do this one time), you’re ready to publish your actionscript file. Click on the ‘Publish’ or ‘Publish As’ button on the top tool bar and save the file to your project root (or anywhere you’ll remember if you haven’t created a project yet) with the default name ‘PhysicsData.as’. ANOTHER NOTE: if you choose a different file name or publish to a package other than the root of your project, you’ll have to edit the .as file to reflect these changes. No big deal. Now, you’re ready to start writing some code. If you haven’t already done so, create a new Actionscript project somewhere. I set mine to export a 800×600 .swf file with a framerate of 60. I also embedded the ground and gear images (same ones I used in PhysicsEditor). Of course you could create an image Atlas (with something like TexturePacker, for example), but for only two textures, I really didn’t want to go through the trouble. The first thing you’ll want to do is initialize Starling. In my example, I have a very basic mStarlingBase instance which inherits from the Starling Sprite class and does really nothing but act as container to which I can add some Starling images. After Starling is good to go, we’ll initialize the Nape Physics engine. Unlike other physics engines, Nape is extremely easy to set up. Really all you need to do is create an instance of the Space class and pass it a Vec2 instance which defines gravity and you’re good to go. For this example though, I also create a PivotJoint instance which will be used to add mouse interactivity so you drag and throw the gears around. So my initPhysics method looks like this: (1000 may seem like a high gravity, but Nape just seems to look and perform better with very high gravity set. Adjust to your own taste). Once the physics space is ready, we can start adding physics bodies. First we’ll initialize the ground. The first thing we’ll do is create a Starling image from the embedded ground image bitmap data and add it to the Starling base. After that, we create a Nape physics body using a static method of the PhysicsData class exported from PhysicsEditor – var ground:Body = PhysicsData.createBody(“ground”); And now you can see why it was important to give your images meaningful names back in PE – writing PhysicsData.createBody(“01″) just wouldn’t be the same. Notice that this static method can also take a graphic argument. We’re not going to bother with that though. More on that in just a bit. Since our ground will never move, we set its ‘type’ property to static. We then position it in the center of the screen (recall back in PE we set the registration point to be in the center – this is where it makes a difference). Finally we add the body to the physics simulation just by setting its space property to our mSpace instance. The entire initGround() method looks like this: Next, we’ll add some gears into the mix. Since I want to add 3, I’ll do it in a simple for loop. This is done essentially the same as we added the ground with one slight difference. Since these gears will be moving around, we’ll want to associate our gear image with the gear physics body. In many Nape tutorials, you’ll see people telling you to use the ‘graphic’ property of the body instance. That property is being deprecated though and it is now recommended that you add your graphics to the ‘userData’ property of the body; which is just a generic object that any data can be added to. Also note that when we create our gear images, we adjust the pivot point to match the centered anchor point of the gear body. So, the initGears() method looks like: Now that our physics bodies are in place, we add some MouseEvent listeners to handle our mouse interaction and, finally, an EnterFrame listener to update our physics simulation. To update the Nape Physics engine, it’s really only necessary to call the step() method of the Space instance. In our case though, we also want to update our PivotJoint for mouse interactions, and, more importantly we want to update the images associated with the gear bodies. So our enter frame handler looks like this: Notice that to update our graphics we loop through the live bodies in our Space instance and for each of them call a method called updateGraphics. This method expects a Body instance as an argument and looks like: And that is really the entire gist of it. Assuming all goes well, you should wind up with something like this. As you can see, even with such complex physics shapes as gears and that crazy ground, you still get an app that runs at a framerate of 60 FPS. But, of course, the main point was just how easy it is to create complex physics shapes using Andreas Löw’s fantastic PhysicsEditor tool. The entire code is listed below: The document class, Main.as: And the PhysicsData.as class exported from PhysicsEditor: Great work on this tutorial. Thanks a lot for including all files including the PhysicsData file, other tutorials haven’t and have been a headache as with different versions of Nape and the PhysicsEditor actionscript generator can be difficult to reconcile which versions play nicely together. In response to your note: “NOTE: by the time you read this, this discrepancy may be fixed and none of this may be necessary. I’m currently using the 1.0.9 version of PhysicsEditor.” It seems that the latest version of PhysicsEditor(I’m using 1.0.10) actually plays a little worse with the latest version of Nape. After making the changes you suggested, I was still left with errors. I was able to reconcile what the problems were by comparing with your version of PhysicsData. I found two issues: 1. In the ‘cbtype’ function, the line: if(name==”null”) return null; needs to be changed to: if(name==”null”) return CbType.ANY_BODY; 2. In the ‘init’ function, the line: anchor = (true) ? body.localCOM.copy() : Vec2.get(0,600); needs to be changed to: anchor = Vec2.get(400,300); (This I assume this would need to be updated if the stage size were to change) Hey Craig, Thank you for the comments. You’re right – I made some changes to the null conditional before writing up this blog post that I forgot to mention (didn’t have problems with the anchor though) – so thank you for pointing that info out to anyone who may be reading this. It turns out it gets even worse though. If you upgrade to Nape 2.0, the graphic property has been fully deprecated, so any references to that inside the nape.as template file must be removed as well. -d. Nape 2.0.3 with Starling 1.3 and PhysicsEditor 1.0.10… I’ve started looking into Starling (1.3), Nape (2.0.3), and PhysicsEditor (1.0.10) today and found that the tutorials/examples on the web don’t work with the current versions. Nothing new there, I’m sure in a few weeks (or months at the latest) my c… Any chances of updating your tutorial to be compatible with Nape 2.0.3 and Starling 1.3? I’ve downloaded PE1.1.10 and can’t seem to reconcile the code to work… I’ll try to make some time for an update this weekend. For a world with 1 square body (with square starling image) moving -500 pixels along the x axis, here the debug draw moves faster than the image. wonder why the debug draws and the starling images are not in sync (positions) when the velocity large – but are in perfect sync when they are at rest or in slow velocity. Would this not be a problem if we have 100 very fast moving objects like bullets. ret.graphic = graphic; ret.graphicUpdate = function(b:Body):void { var gp:Vec2 = b.localToWorld(offset); when i run ,worry here. (starling 1.3,nape:2.09,phsicyEditor 1.09) Hey wuchao, As was mentioned (partially) in a previous comment, the latest version of Nape no longer contains the graphic or graphicUpdate properties on Body objects. You will have to either remove those from the PhysicsEditor Nape template or remove those references from the generated class file. LOVE this – thanks for the tute User this PE Nape as3 template with Starling 1.3 and Nape 2.0.9 Regards Rod package { import nape.phys.Body; import nape.phys.BodyType; import nape.shape.Shape; import nape.shape.Polygon; import nape.shape.Circle; import nape.geom.Vec2; import nape.dynamics.InteractionFilter; import nape.phys.Material; import nape.phys.FluidProperties; import nape.callbacks.CbType; import nape.geom.AABB; import flash.display.DisplayObject; import flash.geom.Rectangle; import flash.utils.Dictionary; public class PhysicsData { public static function createBody(name:String,graphic:DisplayObject=null):Body { var xret:BodyPair = lookup(name); if(graphic==null) return xret.body.copy(); var ret:Body = xret.body.copy(); graphic.x = graphic.y = 0; graphic.rotation = 0; var bounds:Rectangle = graphic.getBounds(graphic); var offset:Vec2 = Vec2.get(bounds.x-xret.anchor.x, bounds.y-xret.anchor.y); ret.userData.graphic = graphic; ret.userData.graphicUpdate = function(b:Body):void { var gp:Vec2 = b.localPointToWorld(offset); b.userData.graphic.x = gp.x; b.userData.graphic.y = gp.y; b.userData.graphic.rotation = (b.rotation*180/Math.PI)%360; } return ret; } public static function registerMaterial(name:String,material:Material):void { if(materials==null) materials = new Dictionary(); materials[name] = material; } public static function registerFilter(name:String,filter:InteractionFilter):void { if(filters==null) filters = new Dictionary(); filters[name] = filter; } public static function registerFluidProperties(name:String,properties:FluidProperties):void { if(fprops==null) fprops = new Dictionary(); fprops[name] = properties; } public static function registerCbType(name:String,cbType:CbType):void { if(types==null) types = new Dictionary(); types[name] = cbType; } //———————————————————————- private static var bodies :Dictionary; private static var materials:Dictionary; private static var filters :Dictionary; private static var fprops :Dictionary; private static var types :Dictionary; private static function material(name:String):Material { if(name==”default”) return new Material(); else { if(materials==null || materials[name] === undefined) throw “Error: Material with name ‘”+name+”‘ has not been registered”; return materials[name] as Material; } } private static function filter(name:String):InteractionFilter { if(name==”default”) return new InteractionFilter(); else { if(filters==null || filters[name] === undefined) throw “Error: InteractionFilter with name ‘”+name+”‘ has not been registered”; return filters[name] as InteractionFilter; } } private static function fprop(name:String):FluidProperties { if(name==”default”) return new FluidProperties(); else { if(fprops==null || fprops[name] === undefined) throw “Error: FluidProperties with name ‘”+name+”‘ has not been registered”; return fprops[name] as FluidProperties; } } private static function cbtype(name:String):CbType { if(name==”null”) return CbType.ANY_BODY; else { if(types==null || types[name] === undefined) throw “Error: CbType with name ‘”+name+”‘ has not been registered”; return types[name] as CbType; } } private static function lookup(name:String):BodyPair { if(bodies==null) init(); if(bodies[name] === undefined) throw “Error: Body with name ‘”+name+”‘ does not exist”; return bodies[name] as BodyPair; } //———————————————————————- private static function init():void { bodies = new Dictionary(); var body:Body; var mat:Material; var filt:InteractionFilter; var prop:FluidProperties; var cbType:CbType; var s:Shape; var anchor:Vec2; {% for body in bodies %} body = new Body(); body.cbTypes.add(cbtype(“{{body.cbType}}”)); {% for fixture in body.fixtures %} mat = material(“{{fixture.material}}”); filt = filter(“{{fixture.filter}}”); prop = fprop(“{{fixture.fprop}}”); cbType = cbtype(“{{fixture.cbType}}”); {% if fixture.isCircle %} s = new Circle( {{fixture.radius}}, Vec2.weak({{fixture.center.x}},{{fixture.center.y}}), mat, filt ); s.body = body; s.fluidEnabled = {{fixture.fluidEnabled}}; s.fluidProperties = prop; s.cbTypes.add(cbType); {% else %} {% for polygon in fixture.polygons %} s = new Polygon( [ {% for point in polygon %} {% if not forloop.first %}, {% endif %} Vec2.weak({{point.x}},{{point.y}}) {% endfor %} ], mat, filt ); s.body = body; s.fluidEnabled = {{fixture.fluidEnabled}}; s.fluidProperties = prop; s.cbTypes.add(cbType); {% endfor %} {% endif %} {% endfor %} anchor = ({{body.auto_anchor}}) ? body.localCOM.copy() : Vec2.get({{body.anchorPointAbs.x}},{{body.anchorPointAbs.y}}); body.translateShapes(Vec2.weak(-anchor.x,-anchor.y)); body.position.setxy(0,0); bodies[“{{body.name}}”] = new BodyPair(body,anchor); {% endfor %} } } } import nape.phys.Body; import nape.geom.Vec2; class BodyPair { public var body:Body; public var anchor:Vec2; public function BodyPair(body:Body,anchor:Vec2):void { this.body = body; this.anchor = anchor; } } In the above template you should… CHANGE: import flash.display.DisplayObject; TO: import starling.display.DisplayObject; Hope this helps someone. Lex RSS feed for comments on this post. / TrackBack URI
http://blog.onebyonedesign.com/actionscript/starling-nape-physics-and-physicseditor/
CC-MAIN-2015-18
refinedweb
3,105
65.01
----- Original Message ----- From: Harlin Seritt To: tkinter-discuss at python.org Sent: Thursday, December 07, 2006 4:14 AM Subject: Re: [Tkinter-discuss] Tkinter-discuss Digest, Vol 34, Issue 5 Hiya G G In case you're a freak about namespace polution (and that's really a good thing), you can generally rest assured that you'll be almost always fine when you do a full namespace import of Tkinter module. Harlin Seritt ======= Yeah, I forgot to mention that using something like from Tkinter import * can get you into trouble if you happen to do something like name a variable "Radiobutton". To see a list of things you shouldn't name variables and functions you can start the Python interpreter, enter 'from Tkinter import *' and then dir() and it will list everything...although you also have to then enter commands like dir(__builtins__), etc. to get the complete list. Is there a way to get the complete list of used keywords with one command? In my programs my variables always start with an upper case letter and my functions always start with a lower case letter (that's just backwards to normal human beings) which has seemed to keep me out of trouble for about 300,000 lines of code. I usually do things like from time import sleep, gmtime, time instead of using from time import *. I guess it's only Tkinter where I import *. Bob
http://mail.python.org/pipermail/tkinter-discuss/2006-December/001004.html
CC-MAIN-2013-20
refinedweb
237
65.76
Gems / Libraries • Asked by Christopher Stewart I've built a todo list that consists of lists and tasks. I am looking to use sortable to allow someone to move items around and between lists. Can anyone recommend any resources on how to do this? I would like to be able to create as many lists as I need and have them available to be dragged and dropped to. Not sure how to go about that. Hey Chris, That's a good question. Honestly the Railscasts episode is probably the most recent that I've seen on that. I should do an episode on it, but I don't think too much has changed. The general idea is that you will keep track of the sort order in the db and then when the user drops an item, you tell the server to update all the positions of items accordingly. Thanks Chris. I stumbled upon that tutorial and was able to get it working for one list. I am struggling trying to get it to work with multiple dynamic lists though. In my app I can create new lists when I need so I was looking to set this up to be able to drag and drop events between whatever lists that are there. Any ideas on howw to do something like that? <% @tasklists.each do |tasklist| %> <ul class="sortable-list connectList agile-list" id="sortable" data- <%= tasklist.taskitems.each do |taskitems| %> <li class="info-element" id="list_<%= taskitems.id %>"> <%= taskitems.content %> <div class="agile-detail"> <%= link_to "Delete", tasklist_taskitem_path(tasklist, taskitems.id), :class=>"pull-right btn btn-xs btn- danger", method: :delete, data: { confirm: "Are you sure?" } %> <i class="fa fa-clock-o"></i> <%= taskitems.created_at.strftime('%m/%d/%Y %I:%M %p') %> </div> </li> <% end %> </ul> Coffee script: jQuery -> $("#sortable").sortable update: -> $.post($(this).data('update-url'), $(this).sortable('serialize')) Ah I see, kinda like Trello board columns. I believe you would want to make sure you submitted the tasklist for the one that the item landed on. You would probably need to check that and see what $(this) references, whether it was for the column it was picked up, or the column of where it dropped. Then server-side you can take those items and make sure that they're all updated with the correct tasklist_id which would do the moving of the item between tasklists on the db side. This might make for a good screencast. Yup like Trello. I have seen some Trello clone tutorials but none that include the sortable fucntionality. That would be a great screencast! Would I need to name the UL a unique value? Like sortable_<%= tasklist.id %>, or would checking "this" get what list I am dropping to? I'm very close I think. At least I have the correct params coming through now. Parameters: {"list"=>["2"], "item"=>["5", "4", "10"]} I just need to get the update working. It is updating positions, but multiple lists at the same time and not setting the correct list ID. def sort @items = params[:item] @items.each_with_index do |id, index| taskitem = Taskitem.where(tasklist_id: params[:list], id: id).update_all(:position => (index +1)) end render :nothing => true end Any thoughts on how I can change this? This is looking pretty good. I think the tough spot now is that you need to set the update to set the tasklist_id as well. I think this should work: def sort @list_id = params[:list].first @items = params[:item] @items.each_with_index do |id, index| taskitem = Taskitem.find(id).update(tasklist_id: @list_id, position: (index +1)) end render :nothing => true end Yup that did it! Thanks a lot. It's all working now.). Login or create an account to join the conversation.
https://gorails.com/forum/are-there-any-up-to-date-tutorials-for-jquery-sortable
CC-MAIN-2017-51
refinedweb
620
76.32
Rat in a Maze Problem 1 — Day 30(Python) Today, I worked on an interesting problem and thought it would be a good idea to write about it. It is a variation of the rat in a maze problem. Let us look into the question. The problem statement is from the GeeksforGeeks website. Rat in a Maze Problem — I Consider a rat placed at (0, 0) in a square matrix m[ ][ ] of order n and has to reach the destination at (n-1, n-1). The task is to find a sorted array of strings denoting all the possible directions which the rat can take to reach the destination at (n-1, n-1). The directions in which the rat can move are ‘U’(up), ‘D’(down), ‘L’ (left), ‘R’ (right). Examples: Input : N = 4 1 0 0 0 1 1 0 1 0 1 0 0 0 1 1 1 Output : DRDDRR Input :N = 4 1 0 0 0 1 1 0 1 1 1 0 0 0 1 1 1 Output : DDRDRR DRDDRR Explanation: The problem statement requires us to find all path that helps rat reach its destination, which is one of the good indicators that we might have to use Depth-First-Search(DFS). DFS algorithms are usually implemented recursively. The maze is represented in the form of a 2D matrix. The cell is accessed using row and column. The cell with the value 1 would mean there is a path present while 0 signifies a blocked path. The problem statement states that the rat starts at (0,0). Hence we will start from (0,0). - Check if the start position is marked as 1. If yes, continue with the algorithm by calling the function which has the DFS algorithm. Else, return an empty list. - We next need to check if the current position is our destination. If yes, append the path to the output list and return the output list. - We need to identify our neighbors. How would we do that? If we look at the below image, we can see how we can move by incrementing/decrementing the row/column value. Since we are allowed to move in 4 directions only, we can increment/decrement the values by 1. 4. After identifying the neighbors, we need to identify whether moving to all the neighboring spot is safe. Being safe would mean that the current row and column are well within the boundary of the maze and has a path. If it is safe recursively call the DFS function with the new position. 5. Whenever we make a move, ensure to add the move to the path. The path is a list that contains all the moves we have made to reach the current position. Change the cell value to anything other than 0,1. In the below code the cell value is changed to -1. This ensures we avoid moving in cycles. 6. Since we need to find all the paths to the destination, once we find a path change the cell value of the current position back to 1 and remove the last move from the path. This case is to be handled when the call is returned during the recursion. 7. We want the result to be in a specific format. Hence while declaring the neighbors, the following format is followed. We need the output to be in ascending order too. Hence while declaring the valid neighbors, we start with “D” then move to “L”, “R”, and “U”. We can avoid the need to sort it later. valid_neighbour = [(1, 0, “D”),(0,-1, “L”),(0, 1, “R”), (-1, 0, “U”)] The following code snippet is the algorithm to be followed to solve the given problem. class PathFinder: def isSafe(self, row, col, n, arr): return(0<=row<n and 0<=col<n and arr[row][col] == 1) def dfs(self, curr_row, curr_col, arr, output, path, n): if curr_row == n-1 and curr_col == n-1: output.append(path) return output valid_neighbour = [(1, 0, "D"),(0,-1, "L"),(0, 1, "R"), (-1, 0, "U")] for n_r, n_c, d in (valid_neighbour): if self.isSafe(curr_row+n_r, curr_col+n_c, n, arr): path += d arr[curr_row+n_r][curr_col+n_c] = -1 output = self.dfs(curr_row+n_r, curr_col+n_c, arr, output, path, n) arr[curr_row+n_r][curr_col+n_c] = 1 path = path[:-1] return output def findPath(self,arr, n): start_row = 0 start_col = 0 if arr[start_row][start_col] == 1: arr[start_row][start_col] = -1 return(self.dfs(0, 0, arr, [], "", n)) else: return [] Complexity analysis. Time Complexity We are visiting all the cells in our maze, which takes O(N²). At any point, we have 3 options to choose from our list of neighbors. Hence the time complexity is O(3*N²). Space Complexity We are recursively calling the DFS function, which means internally we have a stack that keeps track of the result. Hence the space complexity is the same as the time complexity i.e. O(3*N²) I would love to hear your feedback about my posts. Do let me know if you have any comments or feedback.
https://atharayil.medium.com/rat-in-a-maze-problem-1-day-30-python-6f0b3c2c70d3?source=post_internal_links---------0----------------------------
CC-MAIN-2021-39
refinedweb
850
72.76
Learn how to create a makefile for a software project, build the project and create executables for the project using makefile. Subscribe here to enable complete access to all technical articles, online tests and projects. This article will help you to gain required knowledge to successfully complete online tests, technical projects which are required to complete online courses and earn course completion certificates for software jobs. #include <stdio.h> #include "basic.h" int total,tot = 0; int main () { printf("This is a simple C Program\n"); total = sum(1,2); printf("Sum of two numbers is %d\n", total ); return 0; } int sum (int, int); #include "basic.h" int sum (int a, int b) { return a + b; }
https://www.mbed.in/c/how-to-write-makefile-in-linux-for-c/
CC-MAIN-2021-17
refinedweb
117
61.87
#include <Teuchos_Workspace.hpp> List of all members. Objects of this type are what should be created by the user instead of RawWorkspace objects since this class will properly initialize memory using placement new and allows typed operator[] access to the array elements. The default constructor, copy constructor and assignment operations are not allowed and objects can not be allocated with new. It is important to note that the constructors and destructors will only be called if call_constructors=true (the default) is passed to the consructor Workspace(). For build-in types that do not need constructors and destructors called, the client should pass in call_constructors=false . Otherwise we would have to call constructors and destructors on all of the memory and that could considerably slow things down. With simple built-in data types (i.e. call_constructors=false) the cost of creating and destroying one of these objects should be O(1) independent of how much data is requested. This is true as long as no dynamic memory has to be allocated (this is determined the object workspace_store passed to the constructor Workspace()). Definition at line 163 of file Teuchos_Workspace.hpp.
http://trilinos.sandia.gov/packages/docs/r7.0/packages/teuchos/doc/html/classTeuchos_1_1Workspace.html
crawl-003
refinedweb
189
53.21
Westacular129 I'm really impressed paramiko was added in the 1.3 update. That's awesome. However, I'm having some trouble getting it working. Specifically: calling the 'connect()' method on a SSHClient object is crashing Pythonista. Sample code: import paramiko client = paramiko.SSHClient() print 'Client instance created' client.load_host_keys("known_hosts") print 'Host keys loaded' client.connect(hostname="mylocalhost", username="myname", password="mypassword") print 'Connection opened' Running this outputs the first two print statements then Pythonista crashes. I've tried with and without using a private key instead of a password, and with a couple different hosts. The hosts I'm trying to connect to are listed in the known_hosts file. Anyone have any insights? Is paramiko working for other people? (For the record, this is on both an iPad 3 and iPhone 4, both running iOS 6.1.2) Westacular129 Thanks for the assistance here. I was able to get things working. One other issue, however, is how slow it is to connect using public key authentication. I did some searching, and found and I can confirm that the key length is the issue: with a 1024-bit key, authentication takes a fraction of a second. A 2048-bit key takes 50 seconds (on my iPad 3). (Helpful tip: Calling <code>paramiko.common.logging.basicConfig(level=paramiko.common.DEBUG)</code> enables verbose output analogous to ssh -vv) Westacular129 In the meantime... It would be kinda hackish (unless you're already using an HTML front-end for your Python app) but you could access it by creating a web server to serve a page that uses the HTML5 geolocation API, and then opening a browser to it..!
https://forum.omz-software.com/user/westacular129
CC-MAIN-2022-27
refinedweb
277
58.89
How to Get View Size in Android For efficient bitmap handling or dynamic View creation in an app, the area that a screen item or layout is using needs to be known. If no fixed sizes are allocated at design time the size of a View may not be known until an app is executed. This is because of the wide range of display sizes that Android supports. Just look on GSMArena to see the huge range of Android devices produced over the years, and to see the wide variation in screen sizes and pixel densities. The example code in this article shows how to read the screen size and the size of Views as the app runs. (Note: All Android screen items are derived from Views. A screen component, e.g. a TextView, is derived from the View class. Such screen components are also known as widgets. Layouts are ViewGroups and are also derived from Views.) Determining the Size of an Android View or Screen at Run Time To run the example code in this article first create a new Android project. Those new to Android programming can read the article Your First Android Hello World Java Program to see how. For this article the app is called View Size. Use a simple layout for activity_main.xml (the layout file may have another name). Add a TextView with id labXY and set the Text attribute to X,Y. Next to it add another TextView called textXY with Text set to ? (actually \? to make it valid in the XML). Here is the layout used for this example: <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns: <TextView android: <TextView android: </RelativeLayout> Add this code to the bottom of the onCreate method in MainActivity.java (or whatever the class was called). Add the required an imports for TextView and DisplayMetrics when prompted with the Alt-Enter: //object to store display information DisplayMetrics metrics = new DisplayMetrics(); //get display information getWindowManager().getDefaultDisplay().getMetrics(metrics); //show display width and height ((TextView)findViewById(R.id.textXY)).setText( Integer.toString(metrics.widthPixels)+","+Integer.toString(metrics.heightPixels)); This is the code running on an Android Virtual Device (AVD) with a 320×480 screen: Finding the Size of an Android View in Code Drop an ImageView onto the layout, here using the ic_launcher.png icon file, or other images can be used. The size of a View can be retrieved using the getWidth and getHeight methods. Change the code in the onCreate to set the TextView to the ImageView’s width and height (an import for View is required, again usually prompted for and added with Alt-Enter): View v = (View) findViewById(R.id.imageView); String x = Integer.toString(v.getWidth()); String y = Integer.toString(v.getHeight()); //show ImageView width and height ((TextView)findViewById(R.id.textXY)).setText(x+","+y); Mmmmm! The code is showing 0,0 for the ImageView size, even though we can see that it is not 0,0: This is because in onCreate the screen has not yet been laid out so the size of the ImageView has not been determined hence the getWidth() and getHeight() methods are returning zero. In fact they will likely return zero in onStart() and onResume(). What is needed is to override onWindowFocusChanged() to get the ImageView sizes: public void onWindowFocusChanged(boolean hasFocus){ super.onWindowFocusChanged(hasFocus); View v = (View) findViewById(R.id.imageView); String x = Integer.toString(v.getWidth()); String y = Integer.toString(v.getHeight()); //show ImageView width and height ((TextView)findViewById(R.id.textXY)).setText(x+","+y); } Finding the Size of an Android Layout in Code The same code can be used to get the size of the View (the layout, i.e. ViewGroup) in which the screen components sit. Construction To get the the size of a View as soon as it is known (rather than waiting for the onWindowFocusChanged event) attach a listener to its ViewTreeObserver. Do this by writing a class that implements ViewTreeObserver.OnGlobalLayoutListener in the Activity’s class. This new class will have an onGlobalLayout method that gets the View dimensions that can then be stored for later use (here they are displayed as before). Here is the example source code for the entire MainActivity.java file to show this way of getting the ImageView’s width and height: package com.example.viewsize; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.view.ViewTreeObserver; import android.widget.ImageView; import android.widget.TextView; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //Reference ImageView ImageView v = (ImageView) findViewById(R.id.imageView); //Attached a layout listener v.getViewTreeObserver().addOnGlobalLayoutListener(new MyGlobalListenerClass()); } //Declare the layout listener class MyGlobalListenerClass implements ViewTreeObserver.OnGlobalLayoutListener { @Override public void onGlobalLayout() { View v = (View) findViewById(R.id.imageView); String x = Integer.toString(v.getWidth()); String y = Integer.toString(v.getHeight()); //show ImageView width and height ((TextView)findViewById(R.id.textXY)).setText(x+","+y); } } } Download some example code in view-size.zip from this article, ready for importing into Android Studio. See the instructions in the zip file, alternatively the code can also be accessed via the Android Example Projects page. See Also - Using Immersive Full-Screen Mode on Android Developers - See the Android Example Projects page for lots of Android sample projects with source code. - For a full list of all the articles in Tek Eye see the full site alphabetical Index. Archived Comments Kestrel on December 15, 2014 at 4:20 am said: Hey fantastic article, can you also talk about the fitSystemWindows and how things are affected when its set or not set by default. Thanks in advance. Author:Daniel S. Fowler Published: Updated:
https://tekeye.uk/android/examples/ui/android-view-screen-size
CC-MAIN-2018-26
refinedweb
950
58.89
FSF Proposes .gnu TLD To ICANN 326 n3rd writes "It looks like the Free Software Foundation would like a .gnu TLD (Top Level Domain) in order to 'expand the name space, particularly for individuals and software developers who cannot find the name they want from .com, .net or .org'. If additional TLDs are going to be added, shouldn't they be more 'generic' so everyone can make use of them, not just the OSS community?" No. I want the TLD "Dot". Please? With Sugar on Top? Re:How about having *no* TLD (Score:1) Re:too narrow tld (Score:3) In fact, I think that ought to be the criterion used to judge whether a proposed TLD is appropriate: I can see creating country and language specific TLDs so that registrations can be handled by someone acting under the same legal system and speaking the same language. But that has already been done. How fine do we need to slice it? Re:In the unlikely event that this happens ... (Score:1) How about .free? (Score:1) For the uninitiated, Stallman complained that Linux used much of gnu's software (gcc compiler, utilities, etc) yet was named for the creator of its kernel (Linus Torvalds), not really giving Stallman's group proper credit. So Stallman proposed changing the name from linux to lignux, and this was actually done in protest in a ./configure script somewhere in a gnu utility (was it emacs? I can't recall). This kind of self-serving garbage is not especially useful. However, the idea of a TLD is not bad, but it should be a TLD like .free -- somethat that could be set up to allow both for advocacy and more transparent signalling to the common person, since .gpl, .gnu, .fsf etc... mean nothing to the masses. Re:Ralph Nader (Score:1) This [icann.org] and other "expressions of interest" can be viewed on ICANN's website [icann.org]. Additionally, CPT maintains a website [cptech.org] about new tldn's. - Vergil Re:thoughts on tld's.. (Score:1) Of course, this probably won't happen, given that consumer interests are not held in the highest regard by ICANN. Corporations tend to have rather a lot of representation. Given how North American society is, I don't see this changing anytime soon. Unfortunate, really. Re:This Is Ridiculous (Score:1) I think allowing arbitrary top-level domains would be the best thing. Re:Taco mentioned .dot at geekpride (Score:1) rOD. -- Re:TLD's SUCK! (Score:2) I read a Bob Metcalfe article in InfoWorld [infoworld.com] where he proposed junking the .com, .org, .net, etc. TLDs and just keeping the country codes. I like this idea. Each country controls its own domain, and can apply whatever bizarre local interpretation of trademark law it has to its domain names. Corporations would need to register in every country in which they want a virtual presence. The paperwork alone should keep cybersquatting to a minimum... How long...? (Score:4) ---- Re:The Solution: Allow ***ALL*** TLDs. (Score:2) Hmmmm.... (Score:3) Naw, don't think so. We need unifying domains, not ones to split 'us' up more -- that only suits the purposes of the direct marketroid collective. This is a dumb idea. Sorry, .rms ;) WWJD -- What Would Jimi Do? Re:This Is Ridiculous (Score:2) Well,heck, if you're going by that metric, better give one to Dr. Dobbs Journal - they've been indulging in promoting the free software community since 1976. Note the date: that's before it was even a twinkle in Stallman's eye. Read the latest issue for more on this. Simon cybersquatting (Score:2) I'm not proposing that anyone can get exclusive use of a TLD, as you seem to assume in your foo.com/net example. As for trademarks: there currently seems to be the weird assumption that anyone with a trademark is entitled to thattrademark.com. Perhaps I'm being optimistic, but I'm hoping that with a more open namespace, this special-status assumption would go away. -- Re:This Is Ridiculous (Score:2) Molog So Linus, what are we doing tonight? Re:Cool! Linux wins again. (Score:2) I don't wnat to discourage this, I just want to be realistic. Re:This Is Ridiculous (Score:2) Re:thoughts on tld's.. (Score:2) In the end most big companies are going to buy up all the TLD's to protect their brandname, and it makes sense, if you have hotelbookings.net, what is the chance you are going to lose half your customers the second time they visit and type ccTLDs make some sense, and a lot of good could be done by scrapping the current Personally though I think the Usenet hierarchy makes more sense, for a start it drills down e.g. comp.lang.perl (2000/07/12 not 12/07/2000) and it is expandable to allow for future additions. Although it has it's problems too, I'd say that if anyone can come up with a really good alternative, well... ...ok, probably everyone's going to ignore them and they will die poor and bitter, but you never know. oh yeah, DUMP TLD! (Score:2) Start a new. Maybe have the UN have a copyright / trademark office. You get a global mark from them. So Then get back local We the US can finally free the Internet of US centric. Now order comes back, oh this is all of course realy under the And while we are at it IP6 reverse the 254. for the xxx group 253. for casino. Re:This Is Ridiculous (Score:2) Can you imagine Stallman's outrage when Disney registers disney.gnu? He won't have any say in who does or does not get a .gnu domain, so it will just turn into another reason for him to start more boycotts. -- trademark classes (Score:2) -- Re:*.gnu.org (Score:2) Re:In My Opinion (Score:2) I say what we really need is a TLD expressly for non-commercial purposes. ".free" or something like it. Run by volunteers and a voting membership - not unlike Usenet. Cybersqatters could be voted out of their domains. Spammers are by definition, commercial, and are not eligible. Evidence of commercial activity would be grounds for revocation. Re:The Solution: Allow ***ALL*** TLDs. (Score:3) Re:The Solution: Allow ***ALL*** TLDs. (Score. I like the idea, but it breaks the hierarchical nature of DNS. Each "." in a machine name delimits a "zone of authority". With out any cacheing, you have to ask a root server for a server that can answer .org queries. Then you ask that server for a server that can answer .slashdot.org queries. Lastly you ask that server for the address of. Normally, most of this data is cached in the lower levels of the hierarchy, giving use reasonable DNS performance as well as managability. As good as this idea is, it won't be adopted any time soon because of the infrastructure changes needed to support an unlimited number of TLDs. Re:We should allow ANY TLD. (Score:2) As for the problem -- that's really only an artifact of the current system. Perhaps as a work-around, the "www" second-level domain would be disallowed in the new scheme. -- Re:Problems with .gnu and other observations. (Score:2) helloword.gnu would be a good spot for `hello world' in a large variety of languages. microsoft.gnu would contain most of the NT Server Resource kit, seems like. Another pointer to microsoft.com would not be acceptable use of microsoft.gnu. To be viable it would need be inclusive of the BSDs. The whole point of gnu (gnu's not unix) is to sidestep the trademark issues on the name unix. Seems like why rms wants .gnu (Score:2) Re:What's next? (Score:2) And I don't think "because free software people can't get the .net/.com/.org that they want" is a justification. I can't either, but I'm not petitioning for a TLD. Something to do with supply and demand. Someone beat me to the domain(s) I wanted. Re:*.gnu.org (Score:2) A joke too far (Score:4) "Go to" "Did you say .new?" "No, .gnu." Ack. ...phil Re:The Solution: Allow ***ALL*** TLDs. (Score:2) You wouldn't have infinite TLDs. I have experimentally discovered (using MSIE5 as an example) that the url box can be filled with up to 1033 characters. Allowing for "http://" and only a single character for the domain name itself you are still only left with 1024 chars for the TLD. (hmm. 1kb - is that a coincidence) Now, assuming all alphas and the numbers 0-9 there are 35^1024 possible TLDs. That's only about 1.33 x 10^1581. Microsoft could easily register that many. :) Sorry no. You are a fuckwit. (Score:3) And what wanker moderators gave this tosspot a score of 5? If you want to see what *should* be done with the DNS system have a look at the following link: TLD's are a batardified anyways... why not? (Score:3) What to do? Add more TLDs? I say why the hell not? It's not like they are anything more than cosmetic anyways these days. - Paradox Man of the C!!! Re:Problems with .gnu and other observations. (Score:3) Re:too narrow tld (Score:3) I think that Free and Open Source Software movments are taking up a good deal of the second-level name space, and predictably so, given the high level of net-savvy among FS and OSS advocates. Supporters of this type of development certainly span the spectrum from non-profit organizations through corporations and into academia. The creation of a TLD for FS/OSS would be a good courtesy to the rest of the world. Notably, however, This would be another FSF-sponsored perk that encourages developers to endorse copyleft. Imagine: Gimp.gnu, gnome.gnu, emacs.gnu, and gcc.gnu all become well-known URLs. The FSF could offer a free second-level domain name in this special TLD to young developers who adopt FSF principles. OSS advocates, BSD advocates, and others who view Stallman may be specifically excluded. They may want their own TLD -- and who knows, if RMS can get his, why can't ESR? The creation of a (a) Consolidate free software web sites under a common TLD -- freeing up SLDs under (b) Leverage a potentially popular TLD to encourage (at a minimum) lip service to the FSF. (c) Catalyze the conflict that RMS, ESR, et al perceive between free software movements. I'll be intrigued by ICANN's eventual decision on this. Re:This Is Ridiculous (Score:2) If Anybody Deserves a "Special Interest" Domain... (Score:4) Imagine that you have the choice between shopping at Amazon.com or Amazon.gnu. Which one do you choose? What message does that send to the world at large? A good one, I'd think... And I want .BSD (Score:3) OT - Background on IANA function (Score:2) Re:We should allow ANY TLD. (Score:2) First, enforce (technically, not legally, of course) the RFC, which specifies that a domain name is NOT a hostname. This would require the holder of to actually put their website at (or something like that), which would look silly and defeat the problem. Or, we could simply make www disallowed as a second-level domain. I think that would probably remove the issue. -- Monopoly (Score:2) And rightly so if you ask me. Why should an organisation cry freedom but yet have a monopoly/control over something like this? Freedom means that anyone can register anything. If I want to set up my website, and my registration was blocked, I would be Not Impressed(TM). The words censorship and hypocrisy would be springing very quickly to mind. too narrow tld (Score:4) Re:The Solution: Allow ***ALL*** TLDs. (Score:3) Not quite. I can still snatch up hot.sex, free.sex, gimme.sex, etc. and sell them all for lots of money. All this does, really, is strip the ".com" and add a dot somewhere in the middle. Someone will still have the common names, as the bidding war moves from linux.com to linux.gnu. If you want a common domain + TLD combo, you're still going to have to fight with everyone else just as we fight over This doesn't solve the trademark issue either: Apple (as the richest of all Apple * companies) will snatch up all the obvious Apple related names (apple.store, buy.apple, etc.). If I go to buy.apple, am I looking to buy actual apples or Apple hardware and software? Who decides? And does Apple own everything in the Anyway, if it ever goes through, I'm going only going to get stuff in the *.tld TLD, for obvious humor-related reasons. (domain.tld anyone?) Taco mentioned .dot at geekpride (Score:4) aych tee tee pee colon slash slash slash dot dot dot () There's trouble. *.gnu.org (Score:4) I think that the Free Software Foundation is a little late on the ball in supporting the community - they needed to have something like this years before. Unfortunately, most FSF software is done cathedral-style, and that's why Open Source is a stronger idea - because it builds a community. I can get *.sourceforge.net, but GNU has up until now made no moves towards supporting the Free Software community - which is why there isn't one. I'll support the community that supports me, thank you. In the mean time, push for a .oss for open source software. sorry all around (Score:2) -- Free Software != GNU (Score:2) There is a LOT of Free Software out there that is not GNU or GPL'ed or anything similar. In fact, I've shipped a fully functional embedded product without a byte of GNU or GPL'ed code, so it's not impossible to find lots of non GNU stuff out there. I really don't think we need to pollute the TLD namespace any futher by adding a TLD for one group's software movement. If anything, make it a more generic name like If Microsoft wanted (flame suit on) -- Kevin .dot domain? (Score:3) Why? So you can have "slash dot dot dot"? Or the domain dot.dot Let's go a level further and have dotdot.dot Throw in some dashes and you have morse code! Re:This Is Ridiculous (Score:2) Painful names (Score:2) <dot@dotat.at> whatever.gnu.org (Score:2) Even better, the FSF will get to keep all proceeds from providing names under gnu.org, instead of forking over money to a registrar for each .gnu that they would register. (Unless FSF plans on an alternate method of administering a TLD, which clearly ICANN isn't even close to considering. Jeez, they're still considering how to consider *adding* TLDs...how long will it take them to consider how to consider administering the consideration of considering administration of new TLDs?) They can easily have it... (Score:2) The FSF need merely convince RedHat, SuSE, Debian &al to ship Linux, ahem, GNU/Linux distributions with named (BIND) enabled by default and the appropriate delegation entry in the /etc/named.conf file. After all, all the computers I administrate have the pointers to the AlterNIC [alternic.org]'s root servers for the domains they serve (such as .PORN). Remember: the power lies not with they who operate the root servers but with they who call them root servers. Ha, ha, only serious. [tuxedo.org] Re:This Is Ridiculous (Score:2) I am happy that AT&T has the freedom to release Plan 9 under any license they want. I am happy that RMS has not achieved his goal of eliminating individual liberty. or what about (Score:2) From some other proposals (Score:2) My favorite is the one from eNom [icann.org] featuring the following: This is obviously the guy I want handling my TLD. This Is Ridiculous (Score:4) So I say: Re:for all you conspiracy theorists.. (Score:2) - another cosmic ray - Since this is a "top" level domain (Score:2) -Ben Reply from ICANN (Score:2) Dear Mr Stallman, In reference to your proposal [icann.org] for a .gnu TLD, we are currently examining rules and policies for extending the TLD namespace, not accepting individual applications for new TLDs. Rest assured your suggestion that we permit expansion of the namespace is being taken with all seriousness: indeed, I can go so far as to guarantee that we will not be considering any policies which reduce the existing namespace, and we would consider no change to be no progress. On the other hand, although we are familiar with the Free Software Foundation and its not unsubstantial contribution to the public good in terms of free software, we would like some clarification on your proposal. We note that there are a substantial number of free software projects released by individuals and organisations other than the FSF, and although a substantial number of these identify with GNU in spirit, many do not. A number of questions arise from this. Your clarification on these issues will be appreciated. Regards, ICANN RMS KUNG FU! (Score:2) Microsoft.gnu? (Score:2) Unless the control of registration in the And /whose/ alphabet is "natural"? (Score:2) (Yes, I'm an American. Always have been.) This is just a bit premature... (Score:3) As the article states, ICANN is not really accepting proposals for new TLDs. They are still developing policies for considering them. So although new TLDs like --- Time for a complete rethink (Score:2) I personally think we should take the time to completely rethink the whole system before we add more TLDs. Why not a system like: Add to this a more involved and enforced structure for TLDs, and we'll be in business. How about this: This should be goverend overall by an international body (to determine TLDs) and a body in each country to determine proper assignment of the TLDs. Each entity should be able to take only one TLD per domain name (i.e. slashdot.org couldn't also get slashdot.com). Existing trademark holders should get first crack at a domain name in the appropriate TLD, and if they opt not to get it, they relinquish the right to try to get it if someone else grabs it later. Domain name reselling should be made illegal (to prevent squatting). It's not a perfect system yet, I'm still mentally working it out. Please email me at pheonixx@bigfoot.com if you have input as to how this could be improved (or have good ideas for TLDs). I'd also like ideas as to whom ideas should be presented of this nature. -Jer What if we just did an audit first? (Score:3) Of course this is going to screw the lookup engines on the root servers which are optimized around having a small set of 3 letter TLDs.. It's fixable though. As a first step, I'd go for a .gnu. Free software makes the net run and is worthy of a .net of it's own. Since GNU is kind of a brand of free software maybe a .fs (free software) would be better. Any thoughts on usability? (Score:2) enough to think that way, let alone follow the rules (why do you think we're in this mess in the first place?). Look at General Motors with their "gmcanada.com" site (why not gm.ca? Because they didn't know about TLDs). It's easier to change how you represent things on the backend than it is to go and teach all the billions of people not currently using the internet how to use it as they start using it. When you want to ls a dir, do you type The best solution would be to have the hierarchy imposed, but to have a nice equivalent to the path statement to make it easier for humans to use. Or a nice way of translating between human requests for information, and the "real" location of things. Humans always think in terms of relativity and relations, not hierarchy. That's why we have $HOME --- Re:I see a flaw in your argument. (Score:4) Not according to the InterNIC's zone file, which is easily downloaded from [internic.net]. A summarized version: ; The use of the Data contained in Network Solutions' aggregated .com, .org, and .net top-level domain zone files (including the checksum ; ; files) is subject to the restrictions described in the access Agreement ; with Network Solutions. ARPA. IN SOA A.ROOT-SERVERS.NET. hostmaster.internic.net. ( ;End of file. (snip SOA) ARPA. 518400 IN NS A.ROOT-SERVERS.NET. (snip 8 root-servers.net entries, B-I in order of H, C, G, F, B, I, E, D) A.ROOT-SERVERS.NET. 518400 IN A 198.41.0.4 (snip the above root-servers.net entries' IP addresses) IN-ADDR.ARPA. 172800 IN NS A.ROOT-SERVERS.NET. (snip again, same order) So there are no sites under .arpa, just in-addr :) -------------------- I want the .tld TLD. (Score:3) Yeah, I know it isn't funny. Go away. --Shoeboy timeframe? (Score:3) -Superb0wl Re:This Is Ridiculous (Score:2) I think that our community (Open Source) being so dependant upon his [RMS] blessing is slightly ridiculous. With a community brought together to promote peer growth and a equal tiered organization, why do we herald RMS so highly? Yes he has done great things, yes he has done things I would never do - some things I couldn't do. But he is just a man, he is fallible. I believe most often he is in error. I am still happy with the work (life) he has contributed. nerdfarm.org [nerdfarm.org] TLD's SUCK! (Score:3) As it stands, the second they open up any new TLD's major corporations and domain squatters will grab up just about everything that is available. The definations for TLD's were good, but they were never adhered too, and currently I don't see any change to that. The whole system should now be ripped out, because as with anything else, it has become greedy mongering for. The tld's imposed organization ad structure that made sense, but no one had sense enough to stick with it. Granted, that cant really be blamed on any one person or organization as nobody forsaw the explosive persoronl and corporate growth of the internet untill it was already too late. Now it has grown so large that nothing at all is going to be done about TLD misuse ever, as anyone with money will feed their congressperson to oppose it. Gotta love corporate america. [mp3.com] We should allow ANY TLD. (Score:4) So why isn't this even being considered? As far as I can tell, it's because big companies want to be guaranteed that they can get the second-level domain corresponding to their trademarks under ALL existing TLDs. This is ridiculous, and totally unlike the way trademarks act in the real world. (If I have a trademark on the word "Foo" for my brand of widgets, I can't stop you from using that trademark for an entirely different kind of product, and I certainly can't stop you from using it in conversation, or as a nickname, etc.) Increasingly, it seems that big-money interests see the digital age as a chance to extend their (government-given) intellectual property rights much much farther than they've ever been before -- taking more and more rights away from the individual. So sure, allow a -- Re:Need some restrictions, too (Score:2) -- Re:And /whose/ alphabet is "natural"? (Score:2) translaterations for quoted and special characters (eg german uses ä -> ae, ö -> oe, etc.). For Chinese there is pinyan, and japanese has a standrad `into english lettering' encoding as well. The Solution: Allow ***ALL*** TLDs. (Score. This would END squatting because it would be impossible for Microsoft, etc. to register all forms of Microsoft.* as doing so would require infinite money. This also allows same named entities to coexist. Apple Records can have apple.records. Apple computer can have apple.computers. A farmer in WA can have apple.farms. While another company can have foster.farms. Unownable TLDs also ENDS the "domain brokering" business because specific domains cease to possess any value. If you have foo.com, foo.net, and foo.org, you can demand high $$$ from any foo entities. With infinite TLDs, there's always an alternative choice. How to implement this from a tech POV? Use the first letter of the TLD to divide up the TLDs among the root servers to balance the load. Subdivide for common letters. Will ICANN do this? Heck no. Bidding wars over limited domains generates big $$$. And trademark holders like the idea of "buying up all variations of our name so no one else can use it". So between the $$$ and politics, I suppose this sensible suggestion will never happen. Re:This Is Ridiculous (Score:2) ----------- "You can't shake the Devil's hand and say you're only kidding." Re:We should allow ANY TLD. (Score:2) -- In the unlikely event that this happens ... (Score:5) IT Re:We should allow ANY TLD. (Score:2) And the problem with the last bit is that company names aren't unique, and certainly aren't unique globally. -- Imagine the chaos (Score:2) Re:If Anybody Deserves a "Special Interest" Domain (Score:2) ----------- "You can't shake the Devil's hand and say you're only kidding." Re:for all you conspiracy theorists.. (Score:2) Don't forget .int [technocrat.net] (international), the quintessential top-level domain. FSF should know better (Score:4) Re:Taco mentioned .dot at geekpride (Score:2) Re:A joke too far (Score:2) My $.02 Arun most needed TLD (Score:4) that way all the crazy stuff that's not good for "normal healthy americans" can hang out there unmolested. on top of that we need a law saying you can't sue someone over their wish --- Re:Do we need a TLD for each language/environment? (Score:2) I want to see But what do I know, I program mainframes in assembler (and C) Finkployd Re:*.gnu.org (Score:5) This is the way to keep domains meaningful (or as meaningless as the DNS guru of the SLD cares to make it). It is how things are done in the .US TLD. Volunteers came forward to handle various cities and to distrbute the domains for those municipalities. If gnu.org was willing to let software developers have third level domains, I could go to ssh.gnu.org and know I would get the site(s) for ssh tools. The same holds true for movies; x-men.fox.com is 10^6 times better than AND it gives fox a little publicity to boot. Too many TLDs is just asking for trouble (although I think we need more than 3). Re:We should allow ANY TLD. (Score:3) Okay, so you failed to demonstrate how this would ease cybersquatting or trademark silliness, but here's why it would be a catastrophically bad idea to open up the TLDs to everyone. If you allow anyone to register whatever TLD they want, what's the difference between that and only having one TLD? You're just moving the problem upstream a level. But you've worsened the problem, because you can't just run to a different higher-level domain (eg taking foo.net when foo.com is taken), because there *is* no higher level. No. The answer, instead, is to create new TLDs, and regulate them better this time (only allowing nonprofits in .org, for example). Re:We should allow ANY TLD. (Score:2) for all you conspiracy theorists.. (Score:4) If you take it as given that the above paragraph is actually true, then Now, of course, you could claim that they [the Suited People] would be scared more, because free software people tend to defend their copylefted ground rather fiercely, but you'd be wrong. A (oh, and on that last note: what if a company does _some_ open source but not _all_? Apple, as part of their Darwin project, has released code under their own APSL but has also given out [or at least is about to give out] some code *cough* *cough* EGCS enhancements *cough* as GPLed (mostly for the purpose of being integrated into an existing GPLed codebase..). Based on this, should apple get an apple.gnu TLD to map to publicsource.apple.com, even though the majority of the software there is not actually GPLed?) As for "does the FSF deserve a TLD"..? well, hell, they give them to countries, right? I honestly think that the GNU foundation has a bigger impact on geopolitics than Christmas Island []. Unfortunately the whole question becomes very painful when you bring up the question of What About BSD? and What About Qt/KDE? I'd like to hope any TLD made will have a more loose definition of "free" than "the GPL". [i like the LGPL better personally, but that's a flamewar for another day..].. In other words i'd just be a hell of a lot happier with In My Opinion (Score:3) -- a modest proposal (Score:2) Anyone should be able to create a TLD, if they can set up a root-level name server for that TLD, prove that they can operate that root-level name server properly, prove that they can provide a 100% reliable connection to that root-level name server, and prove that they have a reasonable potential market for that TLD. (For example, .gnu is probably too narrow for a TLD, while .oss is probably sufficiently broad.) Each TLD owner (and there should be exactly one owner per TLD) should be required to impose (or not) and enforce restrictions on the nature of owners of domain in their TLD. For example, .com addresses should not be given out to entities not legally registered as corporations, partnerships, proprietorships or the like. This would be more likely if there were one owner per TLD, and they were legally responsible for ensuring that domains they issue conform to the guidelines under which the TLD was created. The existing TLDs should be destroyed as meaningless, and recreated under the above guidelines. .net would still be useful if limited to organizations which exist to provide network connectivity (ISPs, telecom companies) or services (ASPs, registrars). .com probably needs to be broken into several domains, by either geography or the type of for-profit entity. .edu needs to apply to more than just post-secondary institutions, and probably needs to be broken down geographically. The number of domains owned by a given entity should be limited. Each legal entity capable of issuing and enforcing trademarks should have a domain within an appropriate TLD for trademarks. For example, .tm.us for trademarks issued by the US Patent and Trademark Office. Then you could register etoys.tm.us, and there would be no possibility of confusion with etoy.org.fr. Then, refuse to allow anyone to register domains in the .tm.* domains except for the responsible trademark office. These changes would, collectively, greatly increase the utility of the namespace in today's environment (as opposed to the pre-commercial environment in which the in-use namespace was conceived) and reduce confusion and lawsuits (as well as cybersquatting, if the limitations on the number of domains was done well). Of course, it will never happen, since it would require a big renaming. Maybe 10 years ago it could have been done, but a second Great Renaming now is probably not possible. Re:whatever.gnu.org (Score:2) When we have .nu (Score:2) Problems with .gnu and other observations. (Score:5) For example, I recently saw in 2600 Magazine how Verizon (the result of the Bell Atlantic/GTE merger) registered something like seven hundred domains, all with "Verizon" in them... even insulting ones, like "verizonsucks.com". They had registered all these domains under the .com, .net and .org TLDs. When the 2600 guys couldn't register "verizonsucks.com", they registered "verizonREALLYsucks.com". In response, Verizon sent them a letter informing them of their violation of trademark laws. Read all about it straight from the horse's mouth [2600.com]. (This brings up the point: If Verizon registered "robdumas.com", could that be considered to be fraudulently using my name? I mean, after all, if I can't register a domain with THEIR name, would I/should I let them register a domain with MY name in it?) Anyway, simply adding a new TLD will just mean that they register there, too. The only way a .gnu TLD would be worth adding is if we, the Open Source community, somehow controlled it, so we could attempt to keep cybersquatters out, without compromising the freedom of it. Perhaps in order to GET a .gnu domain, you must PRODUCE something under the GNU Public License. Hey, maybe one day we'll all open up Slashdot to find that Microsoft wants to register "microsoft.gnu"! Ha! Two final point of interest, somewhat related to this story/thread: I'm interested to hear what others have to say about the topic. Reply here, or e-mail me [mailto]. ---------------------------------------- Robert Dumas Re:Need some restrictions, too (Score:2) WWJD -- What Would Jimi Do? Re:Taco mentioned .dot at geekpride (OFFTOPIC) (Score:2) This is coming from someone who's -- Re:We should allow ANY TLD. (Score:2) How is having any TLD more confusing than, say, allowing human beings to have any last name? (Imagine the trouble if we were restricted to "Hi, I'm Matthew Com...") --
https://slashdot.org/story/00/07/12/1710226/fsf-proposes-gnu-tld-to-icann
CC-MAIN-2016-40
refinedweb
5,677
74.69
The--big {} In this CSS methodology a block is a top-level abstraction of a new component, for example a button: .btn { }. This block should be thought of as a parent. Child items, or elements, can be placed inside and these are denoted by two underscores following the name of the block like .btn__price { }. Finally, modifiers can manipulate the block so that we can theme or style that particular component without inflicting changes on a completely unrelated module. This is done by appending two hyphens to the name of the block just like btn--orange. The markup might then look like this: <a class="btn btn--big btn--orange" href=""> <span class="btn__price">$9.99</span> <span class="btn__text">Subscribe</span> </a> If another developer wrote this markup, and we weren't familiar with the CSS, we should still have a good idea of which classes are responsible for what and how they depend on one another. Developers can then build their own components and modify the existing block to their heart's content. Without writing much CSS, developers are potentially capable of creating many different combinations of buttons simply by changing a class in the markup: See the Pen BEM example by CSS-Tricks (@css-tricks) on CodePen. At first this syntax might seem slower than simply making a new class for each type of button, but this is not the case for several reasons we'll cover. Why should we consider BEM? - If we want to make a new style of a component, we can easily see which modifiers and children already exist. We might even realize we don't need to write any CSS in the first place because there is a pre-existing modifier that does what we need. - If we are reading the markup instead of CSS, we should be able to quickly get an idea of which element depends on another (in the previous example we can see that .btn__pricedepends on .btn, even if we don't know what that does just yet.) - Designers and developers can consistently name components for easier communication between team members. In other words, BEM gives everyone on a project a declarative syntax that they can share so that they're on the same page. Harry Roberts identified another key benefit of using a syntax like BEM when he writes about improving developer confidence: This is the main reason we end up with bloated code bases, full of legacy and unknown CSS that we daren't touch. We lack the confidence to be able to work with and modify existing styles because we fear the consequences of CSS' globally operating and leaky nature. Almost all problems with CSS at scale boil down to confidence (or lack thereof): People don't know what things do any more. People daren't make changes because they don't know how far reaching the effects will be. Likewise, Philip Walton argues that this problem can be fixed if enough developers stick to the principles of BEM: While 100% predictable code may never be possible, it's important to understand the trade-offs you make with the conventions you choose. If you follow strict BEM conventions, you will be able to update and add to your CSS in the future with the full confidence that your changes will not have side effects. So if developers can work on a project more confidently, then they're sure to make smarter decisions about how these visual components should be used. This methodology might not be a perfect cure for all these ailments, but it certainly gives developers a standard on which to write better, more maintainable code in the future. Another smart part of BEM is that everything is a class and nothing is nested. That makes CSS specificity very flat and low, which is a good idea. It means you won't end up fighting with yourself over specificity. Let’s take a look at some of the problems with BEM... Problems with BEM CSS Of course nobody will twist your arm if you break from BEM rules. You could still write a CSS selector like this: .nav .nav__listItem .btn--orange { background-color: green; } That looks like it has parts of BEM going on, but it's not BEM. It has nested selectors, and the modifier doesn't even accurately describe what's going on. If we did this, we'd be screwing up the specificity flatness that is so helpful with BEM. A block (such as .nav) should never override the styles of another block or modifier (such as .btn--orange). Otherwise this would make it almost impossible to read the HTML and understand what this component does; in the process we're bound to greatly shake another developer's confidence in the codebase. This goes for HTML, as well: what would you expect if you saw the following markup? <a class="btn" href=""> <div class="nav__listItem">Item one</div> <div class="nav__listItem">Item two</div> </a> What's probably going on here is that an element in a completely unrelated block has the code a developer needed, but the child elements don't require a .nav class as the parent. This makes for an exceptionally confusing and inconsistent codebase which should be avoided at all costs. So we can summarize these problems by: - Never overriding modifiers in an unrelated block. - Avoiding making unnecessary parent elements when the child can exist quite happily by itself. More examples of BEM in action Accordion demo See the Pen BEM Accordion by CSS-Tricks (@css-tricks) on CodePen. In this example there is one block, two elements and one modifier. Here we've can created an .accordion__copy–open modifier which lets us know we shouldn't use it on another block or element. Navigation demo See the Pen BEM Menu by CSS-Tricks (@css-tricks) on CodePen. This navigation demo has 1 block, 6 elements and 1 modifier. It's even perfectly OK to create blocks without modifiers at all. At some point in the future a developer can always bolt on (or bind to) new modifiers so long as the block remains consistent. Dislikes of BEM Perhaps you don't like the double-underscores or double-dashes thing. Fine, use something else that is unique that you will consistently enforce. Here's another sentiment: Not sure I'm sold on BEM. .site-search .site-search__field .site-search--full Why not: .site-search .site-search input .site-search .full — Samuel Fine (@samuelfine) March 11, 2015 Those last three selectors all have different specificity levels. They either require parents or not. Without any rules in place, they don't say as much as the ones on top. Is it possible that this tiny, isolated example feels perfectly fine to you and never ends up biting you in the butt? Perhaps. But the more CSS you have in a project, the more little things like this add up, the more specificity and complexity battles you go through. BEM sounds super useful if you don't know how HTML or CSS work. — Samuel Fine (@samuelfine) March 11, 2015 Not to pick on Samuel here, but his sentiments are shared by a lot of people so it makes for a good example. They see BEM, and they just outright reject it. If you want to dislike BEM, that's absolutely fine, but I think it would be hard to argue that having a set of rules that aid in understanding and assist in keeping CSS maintainable is a bad idea. In the SMACSS methodology, you’re likely to find a CSS classname with three letters. Modifiers then follow the module name with a hyphen: /* Example Module */ .btn { } /* Modifier of the btn class */ .btn-primary { } /* Btn Module with State */ .btn.is-collapsed { } That's just a different naming approach to the same kind of problem. It’s pretty similar, but you’re just being more specific about dependencies and keeping specificity flatter. In OOCSS, blocks are similarly generic. /* Example Module */ .mod { } /* Part of Module */ .inner { } /* Talk Module */ .talk { } /* Variation of part inside Module */ .talk .inner { } So you would use multiple classes in the HTML for variations. The inside part isn't named like it has a dependency, so it is less clear but potentially more reusable. BEM would do .mod__inner and .mod--talk and .mod--talk__inner. These are just variations on methodology. Remember that nobody is twisting your arm here, these are self-imposed rules where the value comes from following them. Sass and BEM For those of you writing Sass and enjoy nesting as a way of scoping styles, you can still author in a nested format, but get CSS that isn't nested, with @at-root: .block { @at-root #{&}__element { } @at-root #{&}--modifier { } } Gets you: .block { } .block__element { } .block--modifier { } And you can get as abstract as you want! Check out Danield Guillan's BEM Constructor or Anders Schmidt Hansen's Expressive BEM. Summary To wrap things up I think it's fair to say that even though BEM won't solve all our problems it is extraordinarily useful for constructing scalable and maintainable interfaces where everyone on the team should have a clear idea of how things can be improved. This is because a great deal of front end development is not just about the nice tricks that solve one little problem in the short term; we need agreements, promises and binding social contracts between developers so that our codebase can adapt over time. Generally I like to think of BEM as an answer to Nicolas Gallagher's question: Replace "can you build this?" with "can you maintain this without losing your minds?" — Nicolas Gallagher (@necolas) July 24, 2013 I’m with Samuel on this one, I don’t like it. I understand the pros and cons, but for me the cons outweigh the pros. Sometimes we’ll add a prefix to a class name so the relationship between things is obvious, i.e: .form .form-fieldset .form-text instead of .form .form fieldset .form input[type=text] But that’s as far as we take it. This idea behind dashes and underscores is kind of messy and confusing to me. Yeah, the dashes and underscores look wierd For me, it seems to make it much easier to look at one element and tell where all (or at least a good solid chunk) of its styling is coming from. In the .form-fieldsetexample above, what if I want a specialized fieldsetin a formthat’s green? Now I have .form-fieldset-green–is this a green fieldsetinside a formor is a green class on an element inside the fieldsetinside the form? To me that distinction between elements through the __and modifiers through --works wonders. Now I know that .form__fieldset--greenis green fieldset inside a format quick glance. Agreed, let’s not go back to 2006 and have ourselves some huge bowls of class soup A while ago I stumbled upon this:. Started using it and in my opinion its clearer then lots of underscores etc. And code looks cleaner too. Re-factoring is easier when using BEM. Without dashes and underscores, I bet you will HAVE to use nesting and with nesting you will run into cascading overwrites and uncertainty when you need to rename or remove classes. You also will not be able to reuse nested class that easily in a new place and you will have to re-factor again. Here you can find more details on the topic with example. I am a big fan of BEM.I am using BEM for all my office and personal projects from last two years.BEM never been a pain in the ass, especially when you work on large projects and large teams. the html looks clean, readable and easily understandable. helps in creating a perfect modularization for style sheets. Helps and tends you to write or develop more modular codes. with the help of sass or less you can make website authoring to a kickass experience. Most of my friends complained about the underscore and long names which look’s weird, need to type more, lot of bullshit blah blah. but the main benefit I see from my experience Understanble HTML document Helps you in writing modular stylesheet Easy stylesheet maintenance BEM make you think webpage as composition of components which helps in creating reusable stylesheets BEM improves readability in javascript code while dealing with class names. My biggest benefit that I got from BEM is, it trained me a lot to thinking in modular way. not only css,but also in programming. I can feel the change and the advantages that i gained.I don’t how to explain it, yeah.. its true. Give it a try. Peace SCSS and BEM works for me, I would normally write something like: Question: What if you have… …and need to CTRL+F for .block__title? Wouldn’t it make more sense for all classes to be easily searchable? Nesting looks cleaner, but I think there’s a definite drawback in not being able to CTRL+F for something inside the codebase. BEM (and other component methodologies) promote a one-component-per-file approach. So finding stuff begins with opening the file for that component (Ctrl-P or Ctrl-T or whatever Navigate-to-File shortcut your editor has). This is great because it immediately reduces the scope of your search. If the file is too big to visually scan, you simply Ctrl-F for &__title. @Jeremy – @Mike summed it up pretty well. Being that the block has been named correctly and your file structure is logical you won’t struggle to find what you need. I had the same worry before but haven’t looked back since. Choose a file structure that suits you and the project best, and use CTRL + SHIFT + F in Sublime to find a class quickly across multiple .scss files. Maps can help too. Thanks guys. That makes sense. The lates Sass version supports BEM in the following way: Which would result in You can see it online here – The same syntax would work for LESS as well. In case any LESS users were curious. There is no need in @at-root #{&}__element, because &__elementis also working in sass. I didn’t like the verbose look of BEM at first but it’s amazing how quickly I got over it. It’s easier for me to understand structure now glancing at BEM CSS and it helps coming up with naming too. Personnaly I love this : it put a little bit deepness into selector but it correct something that bother me with bem : the length of the class title. I don’t know in what mesure confortable selector is important with deepness, but I do prefer it. I’ve been using BEM on my last few projects and I think it works well. The only thing I’ve done differently is switch up the underscores and dashes since I prefer dashes and my CSS usually contains more elements than modifiers. I love BEM. At first I shyed away from it because it’s so ugly but then I realised I can use mixins to abstract the formatting in css. In scss it’s more characters than it’s worth but with indented sass it’s kind of beautiful gracefully compiles into Here are the mixins for those wandering I like this method. Thanks, Charlotte. Hi guys, what do you think about following library which takes similar approach? This looks great! Thanks Charlotte :) That looks great, thanks! even i also don’t like this… may be we can go for camel case pattern. .btn {} /* Element that depends upon the block */ .btnPrice {} It will be help full to maintain the code pattern in js also…. Sass + BEM is a great reason to use BEM. Both seem to be meant for writing CSS that you DON’T GET CONFUSED BY. I guess my BEM is more just .parent-child and I use few modifiers, if ever. I have taken to writing high level layout blocks with a l_prefix like: BEM would be more like .l_header__nav, but I use dashes simply because if I want to select any element of the selector, dashes are better for double-clicking in text editors. (Underscores are word-characters so double-clicking will select the whole selector.) May be a weird reason to do that, but it helps my workflow. I’ll chime in as, for my sins, I find CSS architecture eternally fascinating. IMHO any approach that attempts to rationlise and enforce HTML classes and CSS selectors is better than no system. The more complicated the system/UI, the truer this becomes. You can dislike BEM syntax (I’m not a fan) but the principles buy you far more than using no system at all (particularly at scale). I also dislike the practice in Sass of using the parent selector to nest; you lose the one to one relationship with your markup (you can’t select a HTML class from Dev tools and search for the selector in a Sass codebase). For very large complex UIs (and depending upon how you are building them) I have found different approaches more advantageous (I call my own Enduring CSS) than BEM, principally the use of a micro-namespace as a means of containment. I have found this in practice to be more robust, faster to iterate on, more understandable from a naming POV (that last point is entirely subjective though). Whatever, you choose, however you adapt from what you begin with, to have some approach is infinitely better place to be than no defined approach at all! Hey Ben, if you structure your Sass files so that each block gets its own folder and its own scssfile, then searching by a selector becomes no longer necessary as looking at .footer__copyrightwill lead you to the footerfolder at once without any searches, then it’s only a matter of finding “you can’t select a HTML class from Dev tools and search for the selector in a Sass codebase).” Use sourcemaps instead…. @Alex I’m using Sublime at present, I can double-click an HTML class in the DOM, CMD+C and then in Sublime CMD+R and CMD+V to find that Symbol project wide. Within a second it takes me straight to that selector in my Sass/CSS ready to type. I find that infinitely quicker than manually browsing for a component folder (I have in excess of 100 components). @ewfwefewfewewf – souremaps mean I need to edit in the browser. I prefer to edit in my text editor. OFFTOPIC– @Ben Frain Although you can edit in the browser (Chrome) and save the file , that’s a browser feature rather than a source maps feature. How I edit in my text editor and use source maps: Enable source maps (Chrome). View the line a specific rule is located in the source/preprocessed file. Edit. If you use Sublime Text you don’t have to “find” that rule, just press CTRL+G(Windows) and type the line number. To clarify your point about SMACSS, if .calloutis a variant of .module, it should be named .module-callout. There is very little difference between BEM and SMACSS. In SMACSS, it talks of modules, sub-modules, and sub-components. These map directly to blocks, modifiers, and elements. Is there a single developer here who has actually used BEM on a project and not bought into it? its easy to dismiss it because it ‘looks funny’ or you ‘dont like the __ or –‘ but thats just left over thinking from the ‘best practices’ which we already know are not necessarily best at all. The bigger the project and the more people contributing to it – the bigger the benefits of something like BEM. As for Sam’s tweet, would you honestly feel comfortable joining a project and changing the .full rule? I highly doubt it, which will lead to higher specificity selectors and as the project grows – less consistency/maintainability. (which wastes time & money and doesn’t look good) Give it a try, you might be surprised. Exactly, once you forgo any initial concerns and actually start using this approach on a project it’s amazing how useful it becomes, and how strange not using it seems. I challenge any naysayers to give it a go on a project, I think you’ll be surprised at how it changes the way you see your CSS. It’s almost indispensable once you get your head around it. This. After couple of projects with BEM (and SASS) I realized that there had been significantly less issues with classnames and conflicts. It’s just one of those things that kind of silently grew on me. One think I like about it is that I can safely use generic words (block, area, container) as BEM -element names. It really speeds up the development when I don’t have to think new names that much. And, like many have said here, the @at-root can be removed with new SASS version. Like this: Great write up on BEM. I see that there are mixed opinions on it whicvh is great and reflects the expressiveness of css. I find BEM to be both scalable and readable (which is why we use it). At first we used it purely to identify parent-child relationships and I struggled to find a use for modifiers at all but the more we used it the more we realised that used correctly you can build extremely flexible and lean architecture! If anyone is interested I wrote a little WordPress script to create dynamic BEM menus and (if you like BEM) I’m sure you will appreciate how much easier it is to create complicated multi level navigation with BEM syntax rather than .menu-name li > ul > li{}. If you have never used BEM before it serves as a practical usage example: Too verbose, and looking too weird. Intermixing underscores with double dashes with single dashes with camelCaps. No thank you sir. Just using single dashes for inheritance AND sublevel elements works absolutely fine, doesn’t look weird or verbose, and doesn’t invite to write selectors that are too specific. Thanks for a great article Joe, Robin and the bunch. In my experience it depends a lot on the complexity of a given project, personal preference (my mental model) and the team I’m in. Some projects are too small (not very complex) to make sense using a BEM-ish approach, while other projects that require high modularization have, in my experience, benefited greatly from BEM. In the case of the startup team I’m a part of, it just makes it easier to discuss and understand our code when things are very component-based and follows BEM. Well, the “Roberts meets Gallagher meets Snook meets our own blend” version of BEM, that is. For us, we need things to be very much like LEGOs – able to move around independently, be removed or added easily – since we need to iterate quickly based on customer feedback and user testing results. BEM helps us a lot with that. Truth be told, when I first saw BEM I was not very convinced, but after trying it out I began to really enjoy it. Maybe it’s like React’s “give it five minutes”. All of the benefits of BEM make sense to me and I like it. My biggest complaint with it is the classnames get really really long. Especially the deeper you get in the module. For instance assume the following HTML/CSS: .accordion .accordion__title .accordion__title__icon And then let’s say I want a modifier on .accordion__title__icon – class=”accordion__title__icon accordion__title__icon–facebook” I realize that we could shorten the name of the class, but that sort of defeats the purpose of making everything easy for other developers to quickly understand what’s going on. With BEM you should probably avoid using code like “accordion__title__icon accordion__title__icon–facebook”. You’d be better off making ‘accordion’ and ‘icon’ as separate components. Then just combining them. This has the advantage of each is useable elsewhere in your site without needing the other. The goal is to abstract each piece so it can be used independently elsewhere. Hey Neal, I agree with @Andrew H here in that you usually don’t need to nest so deep. If you have an element inside of an element then the top-most element can probably be a separate block. I once wrote an article about BEM mixins, if you are interested, please take a look. I agree with guys above. However I don’t like that pattern of specifying base class together with modifier class, it is really redundant ( class=”accordion__title__icon accordion__title__icon–facebook”). Here you can learn about a simple workaround. I’m fine with enforcing consistency and having a naming convention but the dual underscores looks horrible, especially when combined with single/double hyphens. It’s an oft-repeated misconception that BEM specifically requires double underscores or dashes. That’s their default recommendation, in order to support hyphen-separated names, e.g. .menu-button__submit-icon. But it’s valid to adopt a Pascal-cased approach e.g. .menuButton_submitIcon. See the examples in their docs. I suggest you read ‘Modern CSS Architecture and Front-End Development’ by Harry Roberts from the Smashing Book #4. If you like the concepts of BEM but not the syntax, there are other options, like SUIT: I take things one further. I use namespaces in my CSS. Harry shows some of the benefits of it here: (has Harry ever done a guest blog here? He should. Try to get him to. ) I only make one amendment. I use ‘.namespace-block-element–modifier’ because underscores are to easy to miss. Seems like the first “C” in CSS is the most dreaded thing… :-) Rightfully so, since you can’t stop the cascade. For those of you who don’t like to write long CSS class names. Stop doing it by hand, try BH template engine for this: This template code: applied to this json: will give you this html: for the love of god i hope this doesn’t catch on. its ugly as sin and feels like a time machine to 2004 specificity is NOT your enemy if used correctly All the comments about how “ugly” the double underscores is seems to be missing the point. Whether or not it’s ugly, BEM is certainly clear what the intentions are. Clarity and structure is the point not how pretty or ugly the markup and CSS is. @Brendan, I did use it on the project and came to dislike it even more. It is abuse of CSS. One even may venture further and claim that it basically goes against some core principles of CSS. It may have it’s place, but it is overused already. First, kudos for trying it before judging it. However, I do strongly disagree that it BEM is abusive, or antithetical, to CSS. Can you expound on this strong viewpoint? CSS is a vague specification. It’s unique design goals included compactness, device-agnosticism, and shared authority between publisher and user (which turned out to have little long-term importance). Nothing in BEM contradicts these tenets in any way. BEM merely adds “cooperative componentization” to CSS: rules are grouped together logically, and each group respects a common set of strict constraints on selector construction. Aside from the ugly__syntax--conventions(which can be changed) my biggest objection is that you have a chain of class names in your HTML, e. g. class="btn btn--big btn--orange" This way you have a lot of variations which can be combined freely … but does this help to get a consistent style on your website? If you wouldn’t do classes that are named based on characteristics like size or color, but based on function, maybe suddenly there are considerably fewer meaningful combinations. And many of them could be done by giving a parent element a reasonable class. Why make the button bigger? Because the user has a touch device? Then give the body the class .touchDeviceand many more elements can be adapted simultaneously. Yes that creates specificity, but as el generico wrote: It’s not your enemy if used correctly. If possible and not too confusing I try to group my classes in CSS so that I don’t have to define basic things repeatedly. Example: This way I don’t have to write class="btn btn-deactivated"but class="btn-deactivated"is enough. What’s in the classname that’s in the style, btn and deactivated. I like my CSS and HTML short and concise. Class chains clearly aren’t my thing. Yey, finally I found another person with same view on the problem! I’m so happy now :) Please take a look at my article which describes another way to group modifier classes, using attribute selectors. I wonder what you think. Sergey, the idea to use the CSS selectors [class^="block--"], [class*=" block--"]is great. So you can also shorten your class lists in the CSS files. I’ve used something similar on a website that consisted of equivalent slides. With [class^="slide-"]I gave the base styles to all slides; while with .slide-1, .slide-2, .slide-3etc. I set individual properties like the background image. Sure, you could write short and concise CSS in BEM methodology. One approach is to use preprocessors like SASS, so you can define your styleguide explicitly: You also can use full BEM stack and therefore avoid writing HTML by hand: Couldn’t we use partial attribute selectors in our CSS too ? [class*=–disabled]{pointer-events:none;} Wouldn’t this cover any .block–disabled item. Fine question. The semantics of “disabled” might mean different things in different logical contexts. If we’re talking about an input field, disabled might mean “this control is read-only”. At the higher levels of abstraction that BEM blocks enable, we might have a listing of Product blocks in our Product Listings block. Such a Product might itself have a “disabled” state, which could mean “this product is unavailable for sale because it’s out of stock”. These two definitions of disabled are different, and will have different presentational implications. With your suggestion, we ignore and do not permit logical context in our code design. The word “disabled” is assumed to have one common meaning regardless of the context in which it’s applied. Ultimately, that discourages working at higher levels of abstraction because it’s cumbersome and painful to re-define the meaning of class names with the cascade. And without abstraction, we are forced to think about the entire front-end in terms of low-level HTML primitives, which wastes our limited cognitive capacity. In the worst case it exhausts that capacity, making the front-end indecipherable, unpredictable, and prone to regression. Was hoping the article would address my main gripes with BEM (which I otherwise love), which sometimes make me end up writing crazy long classess like section-name__content__blurbs__blurb__title: How do you decide what is a block? Surely the entire page isn’t a single block, but how do you decide how to decompose it? How do you name elements whose only purpose is to make some CSS hack/feature work? Imagine you have a heroelement, which to the eye just contains a headlineand a taglineas ostensible children. You’d love your classes to be .hero, .hero__headline, and .hero__tagline, but you needed a couple intermediate elements to accomplish some design goal (e.g. a wrapper, a pre-flexbox container for vertical centering — use your imagination). Those elements need styles, so are you forced to write .hero__wrapper__container__headline? Sometimes I do it, but I also think of it as a reductio ad absurdam for the whole convention. Other times I fudge and say “the wrapper element isn’t so much a child of the parent as part of the implementation of the block, so I’ll call it .hero--wrapperand reduce the length of the child selectors by one.” But this dilutes the naming convention. Namespaces. Need a hack to make code work? Prefix with “_”. “How do you decide what is a block?” Any element that is self-containing and can be decomposed. If you can move this anywhere on the page and have it function exactly how it does anywhere else. That is a block. Navigation, content area, side-bar, footer, header, carousel, etc. Zack, there’s no reason to mirror nesting structure in element’s name. Herolayout could be something like this: Unless you have elements with the same name on different nesting levels (which is not a great idea on its own) you still got a bulletproof protection against css selectors’ collision. Roman, I’ve never seen a problem to layout in more classic and semantic way: Therefore, LESS or SCSS code looks something like that: Clean and simple, isn’t? This layout could be easily broken by nested block, as block1’s selectors would affect block2 elements. BEM naming may be not that clean and simple, but it guarantees bulletproof incapsulation. I’ve forked the first pen to provide a brief example of BEM templating: It’s upsetting to see a lot of discussion in the comments around “proper” class names. After all, BEM is not telling you how to name your classes. Instead it is proposing a way to separate your code into atomic reusable components. Just look at the basic block declaration in BH syntax: It has nothing to do with html, css or js. But the block itself could contain logic implemented in all of these technologies (and even more). For the .mod--talk__innerexample, I prefer keeping the modifiers on the block whenever possible. So, this would be: Otherwise, you’d need a new modifier class for each element of a block. I suppose this messes with specificity, but .mod–talk .mod__inner should have precedence anyway. But, I guess this brings up the question: Should elements be nested inside blocks? You’re spot on with the first block of code – only nesting them inside a modifier, or as a separate modified class e.g. .mod__inner--wide {} The following would be redundant, as .mod__inneris named in such a way that we already know it’s an element of .mod: You’re reducing the amount of fighting you’ll have to do with specificity as components develop. First of all, I hope you are modularizing your CSS whether you use BEM or not. Secondly, take a look at your current projects. Do you often nest unrelated modules inside of your modules? If that’s the case then use the BEM approach. If not, use an approach that makes the HTML and CSS more readable. I wrote Title CSS as a way to easily locate module classes and create a scope for short descendant classes. I find that using “orange” as a class name in the example is really a bad idea. Because, of course you’ll have someone write a .sidebar .orange { color: blue; }, BEM or not. Why not use .primaryor .secondary? Here is a good blogger explaining semantic css. I often get the feedback from the backend guys that using BEM creates much more work for them and the project manager doesn’t like to hear that. Their argument is that it is easier for them to output instead of < form class=”signup__sidebar”> etc. As the first variant is already coming out of the CMS just like that, but the second requires more coding work to get like that. And it is not just about the form, but any other plugins/extensions they use for the CMS. How should this be seen? In my example above variant one was: and the second was: I just call it .butts, as in buttons. so it would be like, .butts {} .butts>span:first-of-type {} .butts>span:last-of-type {} I dunno why you would ever give children of these bad boys classes. In my opinion, BEM is an absolute craziness and it makes HTML and CSS code bizarre. Okay, even if your project is very complicated with a lot of stuff delivered by many teams, so why don’t follow Web Components approach that keeps everything clear and simple? Because of it is not supported by browsers. And polyfills are very slow. So, if I were to follow this structure, would this be appropriate for a navigation element? And how much is too much? Say for example I have some small styled element in the link, like an icon, would that add a fourth layer? How far is too far when dealing with BEM? Can you go too far? No. Correct code would be: @Sergey – You’ve got your elements and modifiers mixed up: Try this: Thanks David! I’m only good at canonical BEM naming: This thread perfectly reveals how developers couldn’t catch BEM conventions right. I use my own system as I’m not a fan of the BEM class names. I get the whole single selector thing but I find it much quicker creating templates with shorter class names. Sub element class names always start with double underscore and modifiers with a single dash. I find it’s much easier to read in both the HTML and SCSS, for example: HTML: SCSS: I do something similar but with the child combinator in internal selectors. Otherwise, you expose yourself to risk of regressions and selector battles when composing components. E.g. if this Accordion ends up composing an ArticleBlurb, which may have its own __content, then the Accordion’s __content styles will be applied to the ArticleBlurb’s. This is easily addressed with the child combinator: You lose flexibility of adding arbitrary elements into the Accordion structure, but that’s a feature not a bug. A consistent structure makes components much easier to manage. Knappster, I also do the same nesting style (along with Mike) but my naming convention is different. Since “Accordion” and every other module class starts with an uppercase class name, I’m free to name a descendant class with any lowercase name since classes are case sensitive. For more information on this naming convention: Keep in mind that we should also be focusing on the efficiency of our CSS. I would argue that efficiency should trump our ease of development when it comes down to it. Nick, I strongly disagree. “Premature optimization is the root of all evil.” There is generally far greater risk to a project from unorganized CSS than from unoptimized selectors. Is performance/efficiency something to be aware of and understand? Yes. But it should not be the primary focus. Optimize only when necessary. Unlike most programming languages, CSS is a particularly sensitive software technology in this regard, as it doesn’t provide strong abstraction mechanisms behind which one can hide gnarly optimizations. That said, there are other ways to optimize presentation than through selectors. Limit use of shadows and transparency. Prefer CSS3 transitions/animations to JavaScript ones. Concatenate stylesheets to reduce HTTP overhead. Valid point, my example is a bit over simplified I think. As a new web designer & developer it is useful for breakpoints for responsive design. Because codes are more cleaner.
https://css-tricks.com/bem-101/?utm_source=CSS-Weekly&utm_campaign=Issue-157&utm_medium=web
CC-MAIN-2017-34
refinedweb
6,560
63.9
Doug Hennig Doug Hennig continues his discussion of VFP 9 report listeners by presenting a set of classes that output the contents of a report run to a cursor and use that cursor to provide a "live" report preview surface. When you run a report in VFP 8 or earlier, the output is sort of a black box: You have little control over the preview window, don't have any information about what got rendered where, and can't provide a "live" preview surface (one in which click events can be trapped to perform some object-specific action). Over the past two months, I've discussed the new ReportListener class in VFP 9 and how it can be used to control report output in ways that previously weren't possible. The ReportListener subclasses I've shown so far performed some type of visible output, such as HTML, reports with dynamic formatting, and so forth. This month, the output from a listener won't really go anywhere obvious to the user; instead, it's sent to a cursor so we can track what got rendered where. Having this information provides all kinds of interesting uses, such as a live preview surface, a dynamically generated table of contents, the ability to find text, conditionally highlighting certain report objects, and so on. Just before the report is run, the code in the BeforeReport event creates a cursor or table to hold the rendered report contents. To create a table, set the lUseCursor property to .F. and cOutputDBF to the name and path of the table to create (if you don't specify the name, a SYS(2015) name is used in the Windows temp directory). To create a cursor, set lUseCursor to .T. and cOutputAlias to the alias to use for the cursor (if you don't specify the alias, a SYS(2015) name is used). In either case, the table or cursor has columns for the record number in the FRX for the report object, the OBJTYPE and OBJCODE values from the FRX (which indicate what type of object it is), the left, top, width, and height of the rendered object, the "continuation type" parameter passed to the Render method (see the VFP Help topic for Render for a discussion of this parameter), the contents of the object if it's a field or label, and the number of the page on which it appears. function BeforeReport local lcTable with This * If a table name and/or an alias wasn't specified, * create default names. if empty(.cOutputDBF) .cOutputDBF = addbs(sys(2023)) + sys(2015) + ; '.dbf' endif empty(.cOutputDBF) if empty(.cOutputAlias) .cOutputAlias = ; strtran(juststem(.cOutputDBF), ' ', '_') endif empty(.cOutputAlias) * If the cursor is already open, close it. If the * table already exists, nuke it. use in select (.cOutputAlias) if file(.cOutputDBF) erase (.cOutputDBF) erase forceext(.cOutputDBF, 'FPT') erase forceext(.cOutputDBF, 'CDX') endif file(.cOutputDBF) * Create either a cursor or a table. lcTable = iif(.lUseCursor, 'cursor ' + ; .cOutputAlias, 'table ' + .cOutputDBF) create &lcTable (FRXRECNO I, OBJTYPE I, ; OBJCODE I, LEFT I, TOP I, WIDTH I, HEIGHT I, ; CONTTYPE I, CONTENTS M nocptrans, PAGE I) index on PAGE tag PAGE endwith * Do the usual behavior. dodefault() endfunc As each object in the report is rendered, the Render event fires. The code in this event in DBFListener adds a record to the cursor. Since the text of a field or label is passed in Unicode, it has to be converted back to normal text using STRCONV() to make it useful. Render uses the helper methods SetFRXDataSession and ResetDataSession defined in its parent class to switch to the data session the FRX cursor is in and back again. This allows Render to get the OBJTYPE and OBJCODE values from the FRX for the current object. Note: This code doesn't currently do anything special with images because I haven't decided what to do with them yet. function Render(tnFRXRecNo, tnLeft, tnTop, tnWidth, ; tnHeight, tnObjectContinuationType, ; tcContentsToBeRendered, tiGDIPlusImage) local lcContents, ; liObjType, ; liObjCode with This if empty(tcContentsToBeRendered) lcContents = '' else lcContents = strconv(tcContentsToBeRendered, 6) endif empty(tcContentsToBeRendered) .SetFRXDataSession() go tnFRXRecno in FRX liObjType = FRX.OBJTYPE liObjCode = FRX.OBJCODE .ResetDataSession() insert into (.cOutputAlias) ; values (tnFRXRecNo, liObjType, liObjCode, ; tnLeft, tnTop, tnWidth, tnHeight, ; tnObjectContinuationType, lcContents, ; .PageNo) endwith endfunc The Destroy method (not shown here) closes the cursor or table and deletes the table if the lDeleteOnDestroy property is .T. When DBFListener is used as the listener for a report, nothing appears to happen; the report isn't previewed, printed, output to HTML, or anything else. However, after the report run is complete, a cursor or table is available containing information about each report element and where it was rendered. SFPreviewForm is a form class providing a report preview dialog with different capabilities than the preview window that comes with VFP. It raises events when report objects are clicked and supports other capabilities, such as finding text. It has to use some trickery to do this: Since a preview page is a GDI+ image, nothing specific happens when you click on some text in the image. SFPreviewForm supports report object events by creating a shape object on the preview surface for every rendered object. These shapes can, of course, capture events such as mouse movement or clicks, making it possible to have a live preview surface. The shapes aren't added to the form itself, but to a container that sits on the form. Since a different set of shapes must be created for each page as you navigate through the preview, it's easier to delete the container (which deletes all of the shapes at once) and create a new one than to remove each individual shape prior to adding new ones. The main method in SFPreviewForm is DisplayPage. This method displays the current page of the report and creates shape objects in the same size and position as each report object on the page. How does DisplayPage know what report objects appear on the page? By looking in the cursor created by DBFListener, of course. lparameters tnPageNo local lnPageNo, ; lcObject, ; loObject with This * If we haven't been initialized yet, do so now. if vartype(.oListener) = 'O' if not .lInitialized .InitializePreview() endif not .lInitialized * Ensure we have a shape container with no shapes. .AddShapeContainer() * Ensure a proper page number was specified. if between(tnPageNo, .nFirstPage, .nLastPage) lnPageNo = tnPageNo else lnPageNo = .nFirstPage endif between(tnPageNo, .nFirstPage, .nLastPage) * Select the output cursor and create a shape around * each report object on the specified page. select (.cOutputAlias) seek lnPageNo scan while PAGE = lnPageNo .AddObjectToContainer() endscan while PAGE = lnPageNo * Set the current page number and draw the page. .nCurrentPage = lnPageNo .DrawPage() * Flag whether we're on the first or last page. .lFirstPage = lnPageNo = .nFirstPage .lLastPage = lnPageNo >= .nLastPage * Refresh the toolbar if necessary. .RefreshToolbar() * If we don't have a listener object, we can't * proceed. else messagebox('There is no listener object.', 16, ; .Caption) endif vartype(.oListener) = 'O' endwith This code starts by calling InitializePreview if the preview hasn't been initialized yet, and then calling AddShapeContainer to add the container used to hold the shapes to the form. We won't look at AddShapeContainer here; it simply removes any existing container and adds a new one from the class whose class name and library are specified in the cContainerClass and cContainerLibrary properties. DisplayPage then ensures that a valid page number was specified and spins through the rendered output cursor, adding a shape for each object on the current page to the container. It then sets the nCurrentPage property to the page number and calls DrawPage to display the preview image for the current page on the form. DisplayPage updates lFirstPage and lLastPage so the buttons in a toolbar can be properly enabled or disabled (for example, the Last Page button is disabled if lLastPage is .T.), and then refreshes the toolbar. InitializePreview, which is called from DisplayPage the first time that method is called, ensures that certain properties are initialized properly. As the comments in this method indicate, one complication is that if you use a RANGE clause for a report run, such as RANGE 6, 7, the pages may be numbered 6 and 7 but when you call the listener's OutputPage method to draw the preview image on the form, the first page is 1, the second page is 2, and so forth. To overcome the potential mismatch between these numbering schemes, InitializePreview sets the nFirstPage and nLastPage properties to the first and last page numbers (6 and 7 in this example) and nPageOffset as the value to subtract from a "real" page number to get the output page number. InitializePreview also puts the report page height and width into the nMaxWidth and nMaxHeight properties. These values are used to size the container used for the report preview; if they're larger than the form size, scrollbars will appear because the form's ScrollBars property is set to 3-Both. Note a couple of complications here. First, the page height and width values are in 960ths of an inch, while the form uses pixels. Fortunately, it's easy to convert from 960ths of an inch to pixels: Divide the value by 10, since the report engine renders at 96 DPI. The second complication is that if the DBFListener object isn't the lead listener for a report run, its GetPageWidth and GetPageHeight methods don't return valid values. Fortunately, _ReportListener handles this by setting the custom SharedPageWidth and SharedPageHeight properties to the appropriate values. Finally, InitializePreview clears some properties used for finding text (we'll look at those later), opens the class library used for the shapes that will be added to the form for the report objects, and flags that initialization has been done so this method isn't called a second time. with This * Set the starting and first page offset. Even though * we may not have output the first page due a RANGE * clause, the pages are numbered starting with 1 from * an OutputPage point-of-view. .nFirstPage = .oListener.CommandClauses.RangeFrom .nPageOffset = .nFirstPage - 1 * The Width and Height values are 1/10th of the * values from the report because those values are in * 960ths of an inch and the report engine uses a * resolution of 96 DPI. Our listener may be a * successor, so use the appropriate Shared properties * if they exist. Also, get the last page number using * either SharedOutputPageCount (which may not have * been filled in if the listener is the lead listener * and has no successor) or OutputPageCount, adjusted * for the offset. if pemstatus(.oListener, 'SharedPageWidth', 5) .nMaxWidth = .oListener.SharedPageWidth/10 .nMaxHeight = .oListener.SharedPageHeight/10 if .oListener.SharedOutputPageCount > 0 .nLastPage = ; .oListener.SharedOutputPageCount + ; .nPageOffset else .nLastPage = .oListener.OutputPageCount + ; .nPageOffset endif .oListener.SharedOutputPageCount > 0 else .nMaxWidth = .oListener.GetPageWidth()/10 .nMaxHeight = .oListener.GetPageHeight()/10 .nLastPage = .oListener.OutputPageCount + ; .nPageOffset endif pemstatus(.oListener, 'SharedPageWidth', 5) * Clear the find settings. .ClearFind() * Open the appropriate class library if necessary. if not '\' + upper(.cShapeLibrary) $ ; set('CLASSLIB') .lOpenedLibrary = .T. set classlib to (.cShapeLibrary) additive endif not '\' ... * Flag that we've been initialized. .lInitialized = .T. endwith DrawPage, called from DisplayPage to draw the current preview page image on the form, calls the OutputPage method of the listener, passing it the page number (adjusted for the starting offset), the container used as the placeholder for the image, and the value 2, which indicates the output should go to a VFP control. DrawPage also calls HighlightObjects to highlight any report objects we want highlighted; I'll discuss this later. Note that the Paint event of the form also calls DrawPage because when the form is redrawn (such as during a resize), the placeholder container is redrawn and therefore the preview image is lost, so DrawPage restores it. with This if vartype(.oListener) = 'O' .oListener.OutputPage(.nCurrentPage - ; .nPageOffset, .oContainer, 2) .HighlightObjects() else messagebox('There is no listener object.', 16, ; .Caption) endif vartype(.oListener) = 'O' endwith AddObjectToContainer, called from DisplayPage, adds a shape of the class specified in cShapeClass (the class library specified in cShapeLibrary was previously opened in InitializePreview) to the shape container for the current report object. The shape is sized and positioned based on the HEIGHT, WIDTH, TOP, and LEFT columns in the cursor, although, as we saw earlier, these values must be divided by 10 to convert them to pixels. local lcObject, ; loObject with This lcObject = 'Object' + transform(recno()) .oContainer.AddObject(lcObject, .cShapeClass) loObject = evaluate('.oContainer.' + lcObject) with loObject .Width = WIDTH/10 .Height = HEIGHT/10 .Top = TOP/10 .Left = LEFT/10 .nRecno = recno() .Visible = .T. endwith endwith return loObject OnObjectClicked handles a click on the shape by raising the appropriate event for the click type. The benefit of using RAISEEVENT() is that any object can use BINDEVENT() to ObjectClicked, ObjectDblClicked, or ObjectRightClicked to implement the desired behavior without having to subclass SFPreviewForm. You could even have multiple behaviors if you wish, since multiple objects can bind to the same event. Any object that binds to these events will receive as a parameter a SCATTER NAME object for the current record in the report contents cursor. lparameters tnRecno, ; tnClickType local loObject select (This.cOutputAlias) go tnRecno scatter memo name loObject do case case tnClickType = 1 raiseevent(This, 'ObjectClicked', loObject) case tnClickType = 2 raiseevent(This, 'ObjectDblClicked', loObject) otherwise raiseevent(This, 'ObjectRightClicked', loObject) endcase There are several other methods in SFPreviewForm. Show instantiates a toolbar using the class and library names specified in the cToolbarClass and cToolbarLibrary properties if lShowToolbar is .T. The FirstPage, PreviousPage, NextPage, and LastPage methods call DisplayPage, passing the appropriate value to display the desired page. SaveFormPosition and SetFormPosition save and restore the size and shape of the preview form between report runs. I'll discuss the rest of the methods next month. loListener = newobject('DBFListener', ; 'DBFListener.PRG') report form Customers object loListener * Show the report in our custom previewer. loForm = newobject('SFPreviewForm', 'SFPreview.vcx') with loForm .cOutputAlias = loListener.cOutputAlias .Caption = 'Customer Report' .oListener = loListener .FirstPage() endwith TestSFPreview.PRG then instantiates an object to handle clicks in the preview surface and binds the various click events to it. Finally, it displays the Debug Output window (because that's where click events will be echoed by the click handler class) and shows the preview form. loHandler = createobject('ClickHandler') bindevent(loForm, 'ObjectClicked', loHandler, ; 'OnClick') bindevent(loForm, 'ObjectDblClicked', loHandler, ; 'OnDblClick') bindevent(loForm, 'ObjectRightClicked', loHandler, ; 'OnRightClick') * Display the debug output window and the preview * form. activate window 'debug output' loForm.Show(1) Here's part of the definition of the click handler class (the OnDblClick and OnRightClick methods aren't shown because they're nearly identical to OnClick). The ObjType property of the passed object indicates what type of report object was clicked (for example, 5 means a label and 8 means a field), and Contents contains the contents in the case of a label or field. define class ClickHandler as Custom procedure OnClick(toObject) do case case inlist(toObject.ObjType, 5, 8) debugout 'You clicked ' + ; trim(toObject.Contents) case toObject.ObjType = 7 debugout 'You clicked a rectangle' case toObject.ObjType = 6 debugout 'You clicked a line' case toObject.ObjType = 17 debugout 'You clicked an image' endcase endproc enddefine When you run TestSFPreview.PRG, you'll see the preview form shown in Figure 1. Although this looks similar to the preview form that comes with VFP, try clicking on various report objects. You'll see information about the object echoed to the Debug Output window (I decided to send output there rather than WAIT WINDOW because the latter interfered with the DblClick event). This simple example doesn't do much, but imagine the possibilities: jumping to another section of the report or a different report altogether, launching a VFP form, providing a shortcut menu that displays different options depending on the particular report object that was right-clicked, supporting bookmarks, and so on. Figure 1 You may have noticed that the toolbar contains a couple of interesting-looking buttons. These are used for finding text within the report. I'll discuss that topic next month. Click the Download button for the code. To find out more about FoxTalk and Pinnacle Publishing, visit their Web site at Note: This is not a Microsoft Corporation Web site. Microsoft is not responsible for its content. This article is reproduced from the April 2005 issue of FoxTalk. Copyright 2005,.
http://msdn.microsoft.com/en-us/library/ms947692.aspx
crawl-002
refinedweb
2,705
53.71
First solution in Clear category for The Stones by tigerhu3180 def stones(pile, moves): results = [True] + [False] * pile for i in range(1, pile + 1): leave = [0 if i - j <= 0 else i - j for j in moves] if all([results[s] for s in leave]): # for the next player #The current player loses if all of the results for the next player are True. #The current player can win if there is at least one choice that is False. results[i] = False # for the current player else: results[i] = True # for the current player return 1 if results[pile] == True else 2 if __name__ == '__main__': print("Example:") print(stones(17, [1, 3, 4])) #These "asserts" using only for self-checking and not necessary for auto-testing assert stones(17, [1, 3, 4]) == 2 assert stones(17, [1, 3, 4, 6, 9]) == 1 assert stones(99, [1]) == 2 print("Coding complete? Click 'Check' to earn cool rewards!") Sept. 27, 2018 Forum Price Global Activity ClassRoom Manager Leaderboard Coding games Python programming for beginners
https://py.checkio.org/mission/the-stones/publications/tigerhu3180/python-3/first/share/ad46b5a584dedc245171459a59072dd5/
CC-MAIN-2020-05
refinedweb
173
56.52
Download | JavaDoc | Source | Forums | Support Available as of Camel 2.6 This cookbook shows how to load and add routes from XML files into an existing CamelContext. You can define Camel routes in XML files using the <routes> tag with the namespace "". Suppose we have the bar route as shown below in the barRoute.xml XML file. <routes xmlns=""> <!-- here we define the bar route --> <route id="bar"> <from uri="direct:bar"/> <to uri="mock:bar"/> </route> <!-- we could add more routes if we like, but in this example we stick to one route only --> </routes> We can then load this route and add to the existing CamelContext using the following lines of code: // load route from XML and add them to the existing camel context InputStream is = getClass().getResourceAsStream("barRoute.xml"); RoutesDefinition routes = context.loadRoutesDefinition(is); context.addRouteDefinitions(routes.getRoutes()); If you are using older versions of Camel, you can do this as well but it requires a bit more work. See this commit log.
http://camel.apache.org/loading-routes-from-xml-files.html
CC-MAIN-2013-20
refinedweb
166
64.61
RongYao 2 Posted September 19, 2014 Hello guys, i'm new to the autoit, previously used batch to automate things but decide to give autoit a try since i see many cool things can be done with it and it is not as hard as it looks thought. I was looking for a program which would allow me to autosave in certain drawing programs and i found this. Photoshop Autosave'?do=embed' frameborder='0' data-embedContent>> So, credits to the guy that made it, it is amazing. I took the script and tried to add input box so people to be able to change the period for autosave, also removed the variables and made script read from file, so people to not need to recompile the whole script again and again, just to use it. expandcollapse popup#include <GUIConstantsEx.au3> #include <MsgBoxConstants.au3> #include <WindowsConstants.au3> #include <File.au3> Opt('TrayMenuMode', 1) Global $interval = (1000 * ($sminutess * 60))() $titlefile = "autosave.txt" FileOpen($titlefile, 0) For $i = 1 to _FileCountLines($titlefile) If WinActive(FileReadLine($titlefile, $i)) Then Send('^s') endif Next FileClose($titlefile) EndFunc This script works without an issue, true it does not check if file exists or have rights to be read, but it works if autosave.txt is in the same directory and has lines inside. The only problem is the input box for me, i wanted to use custom one and i can't figure out how to do it, i need to rewrite the whole thing, still thats my first attempt to work with autoit and it does not goes well. Then i've tried to find good example of inputbox with updown controls limited to use only digits and i found one. Then I edited it to suit my preferences before merge it with the script above and replace the inputbox i use there. #include "GUIConstants.au3" $title = GUICreate("My GUI UpDown",320,150,-1,-1, $WS_SIZEBOX) $input = GUICtrlCreateInput ("10",10,10, 50, 20, $ES_NUMBER) $updown = GUICtrlCreateUpdown($input) GUICtrlSetLimit($updown,1440,0) $old = 10 ; Attempt to resize input control GUICtrlSetPos($input, 10,10, 300, 50 ) GUISetState () ; Run the GUI until the dialog is closed While 1 $msg = GUIGetMsg() If $old <> Int(GUICtrlRead($input)) Then If $old < Int(GUICtrlRead($input)) Then; up $old = ((Int(GUICtrlRead($input)) - $old) * 1) + $old If $old > 1440 Then $old = 0 GUICtrlSetData($input,$old) Else $old = (($old - Int(GUICtrlRead($input))) * -1) + $old If $old < 0 Then $old = 0 GUICtrlSetData($input,$old) EndIf EndIf If $msg = $GUI_EVENT_CLOSE Then GUIDelete($title) Wend Thing is i dont know how to replace from the first script with the one above, i'm trying to set global interval value before gui deletion but it always ends up returns 0 and it not work as expected. Share this post Link to post Share on other sites
https://www.autoitscript.com/forum/topic/164411-custom-input-box-and-global-variable/
CC-MAIN-2019-35
refinedweb
467
53.44
mask problembhargavi reddy Jun 13, 2012 1:49 AM I am trying to mask a movieclip. But mask (shape of rectangle) is displayed over the content instead of masking the content in flash as3. Please anyone help me... 1. Re: mask problemvipul.khandelwal Jun 13, 2012 3:43 AM (in response to bhargavi reddy) Hi, Please try this, it is working perfectly. import flash.events.Event; //mc is the instance of stage movieClip which has to be shown. //myMask is instance of movieclip in which region movieClip mc is to be shown. mc.mask = myMask; mc.addEventListener(Event.ENTER_FRAME, onEnter); //Keep movieClip mc at initial postion and myMask in center of the stage. function onEnter(e:Event):void { mc.x += 10; } Regards, Vipul 2. Re: mask problembhargavi reddy Jun 13, 2012 9:36 PM (in response to vipul.khandelwal) Thaks for your reply It is also working but my problem is different. Luckily with the help of my senior, I got the solution. 3. Re: mask problemvipul.khandelwal Jun 14, 2012 2:26 AM (in response to bhargavi reddy) Hi, It is good tht you gotthe solution, you stated that problem is something else, please share the problem so that i can also be aware about that. Regards, Vipul 4. Re: mask problembhargavi reddy Jun 14, 2012 9:08 PM (in response to vipul.khandelwal) Hi Vipul, Its good to ask about the problem and solution. I will explain you in detail what the problem is and how I solved it. Actually my problem is I was trying to load data from URL and add the loaded data to a movieclip (I assumed this movieclip as appsHolder). I want to add Scrolling for this one. For that I created one class with masking, scrolling functionalities. In that class I created one movieclip called holder and add the previous appsHolder to holder by calling a funtion. Here I applied masking to holder. and also every time the data is loading, I create one new appsHolder. As I mentioned above I got a problem in masking. I am trying to analyse my mistake and found that every time creating a new appsHolder generates a problem. Immediatley I removed that code and create appsHolder only once. And also I want to mention another thing, masking applied for either holder or appsHolder doesn't represents difference. I don't know whether it is logical or not. But finally the problem is solved.
https://forums.adobe.com/thread/1022248?tstart=0
CC-MAIN-2016-50
refinedweb
408
67.65
19 February 2008 23:29 [Source: ICIS news] CARACAS (ICIS news)--Japanese trading house Sojitz Corp has been approved as a minority partner in Braskem's and Pequiven's joint venture project to build a new petrochemical complex in ?xml:namespace> "They know the country, they know Pequiven, they're a shareholder of Braskem," Grubisich told ICIS news by telephone. "I think they can bring a very good contribution because they do understand Braskem's market." Sojitz was brought into the joint venture in order to have a third company that is currently active in Venezuela but not bound by state-owned company regulations. The trading house will hold a 2% stake in the joint venture and will not be involved in the project's strategic decision making, Grubisich said previously. The $3.5bn (€2.4bn) Jose Petrochemical Complex will include a 450,000 tonnes/year polypropylene (PP) plant to start up in the second half of 2010 and a natural gas-fed cracker with capacity of 1.3 m tonnes/year scheduled for the second half of 2012. As a Japanese company, Sojitz is a potential source of low-cost finance from The three companies have agreed to each provide $90 million for engineering studies and hope to establish a final investment decision on the PP plant by the beginning of the second half of this year. An investment decision on the polyethylene (PE) plant is expected by the beginning of the second half of 2009, said Grubis
http://www.icis.com/Articles/2008/02/19/9102109/japan-sojitz-joins-braskem-pequiven-in-venezuela.html
CC-MAIN-2014-42
refinedweb
249
53.75
urlreversi: Revert your shortened URLs Dependency: compile "org.grails.plugins:urlreversi:1.0" Summary Installation grails install-plugin urlreversi Description Introduction What it doesThis plugin reverses a shortened url - for example. See further documentation below. Use case exampleA typical use case for this plugin can be in an grails app that mashes up with twitter posts. Regardless of what shrinking service is used in any tweet - this plugin should be able to resolve the original link on demand and transparently. This can be useful in community environments to improve user convenience or to do some stats about your "community links". Similar toolsThere are dozens of similar technologies out there. For example users can install the longurlplease Firefox extension from to have only original urls while surfing. A more similar technology is the service that is hosted at. With this plugin such a service can be realized really easy in a grails app. Ideas for using this plugin within your grails appYou might want to use this plugin in your app: If you have some shortened links that shall be demystified. If you want to detect link doublettes from different shortening services. How to use - How to use the tag(lib) - As a text in your html page will result in the text : <div></div> <div><urlreversi:revert2Long</div> - As a link in your html page Which will of course result in this html: <a href=""></a> <a href="${urlreversi.revert2Long(url:'')}">${urlreversi.revert2Long(url:'')}</a> - How to use the service in your controller class is enough to make use of the Service. def urlReverterService - Combined example: AJAX GSP Code: def urlReverterService def index = { } def ajax = { def longUrl = urlReverterService.urlReversi(params.url) render "Long Url: ${longUrl.toString()}" } <h1>Ajax call: <g:remoteLinkAjax Link</g:remoteLink></h1> <p id="upd">I am the ajax element that gets updated</p> - Differences between tag and service The service doesn't catch exceptions while the tag does: The tag returns the input url param in case of an exception or an empty string. The is true even if the given url is invalid. Simple usage example
http://www.grails.org/plugin/urlreversi
CC-MAIN-2016-40
refinedweb
351
54.42
Leaf¶ Leaf is a powerful templating language with Swift-inspired syntax. You can use it to generate dynamic HTML pages for a front-end website or generate rich emails to send from an API. Package¶ The first step to using Leaf is adding it as a dependency to your project in your SPM package manifest file. // swift-tools-version:5.2 import PackageDescription let package = Package( name: "MyApp", platforms: [ .macOS(.v10_15) ], dependencies: [ /// Any other dependencies ... .package(url: " from: "4.0.0"), ], targets: [ .target(name: "App", dependencies: [ .product(name: "Leaf", package: "leaf"), // Any other dependencies ]), // Other targets ] ) Configure¶ Once you have added the package to your project, you can configure Vapor to use it. This is usually done in configure.swift. import Leaf app.views.use(.leaf) This tells Vapor to use the LeafRenderer when you call req.view in your code. Note Leaf has an internal cache for rendering pages. When the Application's environment is set to .development, this cache is disabled, so that changes to templates take effect immediately. In .production and all other environments, the cache is enabled by default; any changes made to templates will not take effect until the application is restarted. Warning For Leaf to be able to find the templates when running from Xcode, you must set the custom working directory for you Xcode workspace. Folder Structure¶ Once you have configured Leaf, you will need to ensure you have a Views folder to store your .leaf files in. By default, Leaf expects the views folder to be a ./Resources/Views relative to your project's root. You will also likely want to enable Vapor's FileMiddleware to serve files from your /Public folder if you plan on serving Javascript and CSS files for instance. VaporApp ├── Package.swift ├── Resources │ ├── Views │ │ └── hello.leaf ├── Public │ ├── images (images resources) │ ├── styles (css resources) └── Sources └── ... Rendering a View¶ Now that Leaf is configured, let's render your first template. Inside of the Resources/Views folder, create a new file called hello.leaf with the following contents: Hello, #(name)! Then, register a route (usually done in routes.swift or a controller) to render the view. app.get("hello") { req -> EventLoopFuture<View> in return req.view.render("hello", ["name": "Leaf"]) } // or app.get("hello") { req async throws -> View in return try await req.view.render("hello", ["name": "Leaf"]) } This uses the generic view property on Request instead of calling Leaf directly. This allows you to switch to a different renderer in your tests. Open your browser and visit /hello. You should see Hello, Leaf!. Congratulations on rendering your first Leaf view!
https://docs.vapor.codes/leaf/getting-started/
CC-MAIN-2022-21
refinedweb
430
69.18
From: Dave Jones <davej@suse.de> To: Linux Kernel <linux-kernel@vger.kernel.org> Subject: Linux 2.5.9-dj1 Date: Tue, 23 Apr 2002 15:45:27 +0100 More of the same. Back up to date with Linus, and roll in some more pending bits. As usual,.. Patch against 2.5.9 vanilla is available from: Merged patch archive: Check before reporting known bugs that are also in mainline. -- Davej. 2.5.9-dj1 o Resync against 2.5.9 | Configure enhanced to look in /boot/`uname -r` (Me) o Fall back to PCI BIOS if direct access fails. (Me) o Bump size of xconfig variable buffer (Me) o 64bit fixes for x86-64 MTRR driver. (Me) o GL641USB based CF-Reader USB support. (Gert Menke) o Bring x86-64 bluesmoke up to date with ia32. (Me) | And drop non-x86-64 bits. o UP CPU number microoptimisation. (Mikael Pettersson) o ATM resources compile fix. (Frank Davis) o readahead reformatting. (Steven Cole) o Death of SYMBOL_NAME (Brian Gerst) o Add more missing Config.help entries. (Steven Cole) o remove old SCSI-EH methods from Scsi_Host_Template (Christoph Hellwig) | This likely breaks many SCSI drivers. They were broken anyway, | and only worked by chance. With this, they stand a chance of being fixed. o meye driver request_irq bugfix. (Stelian Pop) o Add kernel command line params to meye driver. (Stelian Pop) o Slabcache namespace cleanup. (Ryan Mack) o SIGURG SUSv3 compliance. (Christopher Yeoh) o Ultrastor region handling cleanup. (William Stinson) o Megaraid region handling cleanup. (William Stinson) o Buslogic region handling cleanup. (William Stinson) o IrDA driver update. (Jean Tourrilhes) o Fix ESSID related wireless crash. (Jean Tourrilhes) o Attempt rd.c surgery. (Me, Andrew Morton) | works/doesn't work feedback appreciated. o Fix reboot=bios cache handling. (Robert Hentosh) o Recognise P4 Xeon in mptable. (James Bourne) o 64bit fixes for smbfs. (Urban Widmark) o nfsd double down() fix. (Anton Blanchard) o x86 io.h cleanup revisited. (Brian Gerst) o kjournald open files fix. (Ph. Marek) o Make expfs compilable on old compilers. (Andrew Morton) o Nail the per-cpu-areas problem once and for all. (Rusty Russell) 2.5.8-dj1 o Detect existing disk geometry in scsicam.c (Doug Gilbert) o Various request_region cleanups. (Evgeniy Polyakov) | Via Rusty's trivial patchbot, and cleaned a little by me. o Yet more request_region cleanups. (William Stinson) o IBM USB Memory key support. (Alexander V. Inyukhin) o Add missing IA64 helptexts. (Steven Cole) o Fix BFS superblock allocation error. (Brian Gerst) o romfs superblock cleanups. (Brian Gerst) o Limit charset size in NLS UTF8 (Liyang Hu) o NCR 53c810 PCI class fixup. (Graham Cobb) o Dynamically size LDT on alloc. (Manfred Spraul) o Disable ACPI C3 on PIIX4 whilst busmastering. (Dominik Brodowski) o hitfb compile fix. (James Simmons) o Various ALSA include compile fixes. (Russell King) o fatfs includes compile fix. (Russell King) o Stricter HTML generation from SGML. (Erik van Konijnenburg) o wdt977 BKL removal. (Dave Hansen) o Various suser -> capability checks. (Colin Slater) o Don't miss preemption opportunities. (Robert Love) o Fix up broken strtok->strsep in tmscsim.c (Dan D Carpenter) o Small kernel-api docbook updates. (Erik Mouw) o Various small touchscreen fixes. (James Simmons) o virt_to_bus fixes for synclink driver. (Paul Fulghum) o Correct nfsservctl capability.h comment. (Chris Wright) o Cleanup x86 io.h functions. (Brian Gerst) o Make 'make tags' work with bitkeeper. (Peter Chubb) o Correct Num/Caps_lock state ioctl flags mixup (Rok Papez) o Small Farsync driver fixes. (Francois Romieu, Kevin Curtis) o Make st.c not oops when there are no tapes. (Douglas Gilbert) o Add PnP scanning to AD1848 OSS driver. (Zwane Mwaikambo) o AHA152x update (ISAPNP,ABORT fixed & 2.5 fixes). (Juergen E. Fischer) o Bluesmoke warning fixes. (Robert Love) o Make per-cpu setup compile on uniprocessor (Robert Love) o Fix various framebuffer merge funnies. (James Simmons) o Fix migration_thread preemption race. (Robert Love) o IDE TCQ updates. (Jens Axboe) o SIGIO generation on FIFOs & pipes. (Jeremy Elson) o PNPBIOS SMP fixes. (Thomas Hood et al) o attach_mpu401() cleanup on failure (Zwane Mwaikambo) o Make P4 thermal interrupt warning a compile option. (Me) | init check for same now also checks for Intel P4. o Offer Athlon background MCE checker on i386 too. (Me) - To unsubscribe from this list: send the line "unsubscribe linux-kernel" in the body of a message to majordomo@vger.kernel.org More majordomo info at Please read the FAQ at
http://lwn.net/2002/0425/a/2.5.9-dj1.php3
crawl-003
refinedweb
747
71.31
There are two kinds of developers: 1) the ones who have (accidentally) checked passwords and connection strings into source code repositories and 2) the ones that lie about it. It is a problem, we have all done it. It is annoying. When developing ASP.NET applications, you can set yourself up so that it will not happen as easily. In this blog post, I describe how I have started doing it. Most Web Apps rely on "secrets" in order to work right. Examples include database connection strings, client secrets, API keys, passwords, etc. These secrets are used to access information and APIs needed by the application. The secrets can be added to configuration files such as appsettings.json or web.config, but what often happens is that these files end up getting checked into source code repositories with the secrets included. Depending on how widely the source code is shared, the secrets could now be compromised and with distributed source code management tools such as Git, it is not completely straight forward to purge these secrets from the revision history. Moreover, it is impossible to make sure they are purged from all the copies that have been checked out. It is also quite common to need different sets of secrets when developing locally on your laptop, when you deploy for testing, and when deploying for production. Managing these different sets of secrets can add complications. Most developers have used some system of multiple configuration files. Some are checked into the source core repository, some are excluded and only used locally etc., but mistakes happen, especially when debugging or when you are in a hurry and sooner or later, the secrets end up on GitHub and then you have a problem. Here is my recipe for avoiding the problem: Do not add secrets to configuration files. Ever. Until recently, that was easier said than done, but when working with ASP.NET CORE 2.0 applications in Visual Studio 2017, it is actually pretty easy. I will walk through how to manage a couple of user secrets for an ASP.NET application and how to specify them when we deploy that application on Azure. I have created an empty ASP.NET CORE 2.0 MVC application in Visual Studio 2017. After creating the application, you can right-click on the Solution Explorer and find the menu item "Manage User Secrets": When you click on that, it will open a file called "secrets.json". This file doesn't actually live in your source code folder and so it will not accidentally get checked in. If you would like to find the file, it is actually in %APPDATA%\microsoft\UserSecrets\<userSecretsId>\secrets.json. Where <userSecretsId> is a unique ID associated with your application. Let us add a few secrets to this file: { "myAppSetting": "This is my secret setting", "ConnectionStrings": { "myConnectionString": "This is my secret connection string" } } To access these values in the application, we can use the Microsoft.Extensions.Configuration module. In this application, go to the HomeController.cs file and add: using Microsoft.Extensions.Configuration; At the top and in the HomeController class definition, add something like: public class HomeController : Controller { public IConfiguration Configuration { get; set; } public HomeController(IConfiguration config) { Configuration = config; } //...Rest of the class definition } Now the HomeController can use the Configuration to access the variables that we have just added to secrets.json. To illustrate this, make the following changes to the Index() function of the HomeController class: public IActionResult Index() { ViewData["myAppSetting"] = Configuration["myAppSetting"]; ViewData["myConnectionString"] = Configuration.GetConnectionString("myConnectionString"); return View(); } And in the Index.cshtml file, replace the contents with: @{ ViewData["Title"] = "Home Page"; } <div> <h1>Secrets test application</h1> <b>myAppSetting:</b> @ViewData["myAppSetting"]<br/> <b>myConnectionString:</b> @ViewData["myConnectionString"]<br/> </div> If you then start debugging the application you should see something like this the index page below: If we go ahead and publish that to an Azure Web App, we would see something like this: The settings are not there as we would expect, since the secrets.json file is not deployed with the application. However, we can provide the settings as settings to the Web App: If we hit save and refresh in the browser. The settings now show up: So we now have a workflow where we can manage setting on our local development machine, but they are managed in a file that will not get checked into the repository and we can use the Web App configuration to specify the settings when deploying. If you are using Visual Studio Team Services for CI/CD and you want to set your secrets as part of the deployment, you can use the Azure WebApp Configuration task from the Marketplace. That's it. If you would like to read more about managing app secrets, have a look at this page. Let me know if you have comments/concerns/suggestions. I would also like to hear about any other schemes that you recommend for managing secrets with other environments than ASP.NET CORE 2.0. How does this work outside of Azure webapp? Environment variables or similar? @Trond, if you are deploying outside an Azure Web App, you need to provide the settings in the web.config or appsettings.json file when you deploy. Or you could have another file that you read during configuration for that deployment environment. At least that is how I would do it. Hope that helps. And if you’re using Docker, you can take advantage of the Secrets management functionality to allocate secrets to your .NET Core apps 🙂 … Docker secrets are encrypted at-rest, encrypted in-transit and mounted in-memory via tempfs -> @Andrew, good point.
https://blogs.msdn.microsoft.com/mihansen/2017/09/10/managing-secrets-in-net-core-2-0-apps/
CC-MAIN-2017-39
refinedweb
946
55.84
. Working with the AWS CDK in C# .NET is a fully-supported client language for the AWS CDK and is considered stable. C# is the main .NET language for which we provide examples and support. You can choose to write AWS CDK applications in other .NET languages, such as Visual Basic or F#, but AWS offers limited support for using these languages with the CDK. You can develop AWS CDK applications in C# using familiar tools including Visual Studio, Visual Studio Code, the dotnet command, and the NuGet package manager. The modules comprising the AWS Construct Library are distributed via nuget.org We suggest using Visual Studio 2019 Prerequisites To work with the AWS CDK, you must have an AWS account and credentials and have installed Node.js and the AWS CDK Toolkit. See AWS CDK Prerequisites. C# AWS CDK applications require .NET Core v3.1 or later, available here Third-party Language Deprecation: language version is only supported until its EOL (End Of Life) shared by the vendor or community and is subject to change with prior notice. The .NET toolchain includes dotnet, a command-line tool for building and running .NET applications and managing NuGet packages. Even if you work mainly in Visual Studio, this command can be useful for batch operations and for installing AWS Construct Library packages. Creating a project You create a new AWS CDK project by invoking cdk init in an empty directory. mkdir my-project cd my-project cdk init app --language csharp cdk init uses the name of the project folder to name various elements of the project, including classes, subfolders, and files. Hyphens in the folder name are converted to underscores. However, the name should otherwise follow the form of a C# identifier; for example, it should not start with a number or contain spaces. The resulting project includes a reference to the Amazon.CDK.Lib NuGet package. It and its dependencies are installed automatically by NuGet. Managing AWS Construct Library modules The .NET ecosystem uses the NuGet package manager. The main CDK package, which contains the core classes and all stable service constructs, is Amazon.CDK.Lib. Experimental modules, where new functionality is under active development, are named like Amazon.CDK.AWS., where the service name is a short name without an AWS or Amazon prefix. For example, the NuGet package name for the AWS IoT module is SERVICE-NAME.Alpha Amazon.CDK.AWS.IoT.Alpha. If you can't find a package you want, search Nuget.org The .NET edition of the CDK API Reference also shows the package names. Some services' AWS Construct Library support is in more than one module. For example, AWS IoT has a second module named Amazon.CDK.AWS.IoT.Actions.Alpha. The AWS CDK's main module, which you'll need in most AWS CDK apps, is imported in C# code as Amazon.CDK. Modules for the various services in the AWS Construct Library live under Amazon.CDK.AWS. For example, the Amazon S3 module's namespace is Amazon.CDK.AWS.S3. We recommend writing C# using directives for the CDK core constructs and for each AWS service you use in each of your C# source files. You may find it convenient to use an alias for a namespace or type to help resolve name conflicts. You can always use a type's fully-qualfiied name (including its namespace) without a using statement. NuGet has four standard, mostly-equivalent interfaces; you can use the one that suits your needs and working style. You can also use compatible tools, such as Paket The Visual Studio NuGet GUI Visual Studio's NuGet tools are accessible from Tools > NuGet Package Manager > Manage NuGet Packages for Solution. Use the Browse tab to find the AWS Construct Library packages you want to install. You can choose the desired version, including pre-release versions of your modules and add them to any of the open projects. All AWS Construct Library modules deemed "experimental" (see Versioning) are flagged as pre-release in NuGet and have an alpha name suffix. Look on the Updates page to install new versions of your packages. The NuGet console The NuGet console is a PowerShell-based interface to NuGet that works in the context of a Visual Studio project. You can open it in Visual Studio by choosing Tools > NuGet Package Manager > Package Manager Console. For more information about using this tool, see Install and Manage Packages with the Package Manager Console in Visual Studio The dotnet command The dotnet command is the primary command-line tool for working with Visual Studio C# projects. You can invoke it from any Windows command prompt. Among its many capabilities, dotnet can add NuGet dependencies to a Visual Studio project. Assuming you're in the same directory as the Visual Studio project ( .csproj) file, issue a command like the following to install a package. Note that since the main CDK library is included when you create a project, you should ever only need to explictly install experimental modules. Experimental modules require you to specify an explicit version number. dotnet add package Amazon.CDK.AWS.IoT.Alpha -v VERSION-NUMBER You may issue the command from another directory by including the path to the project file, or to the directory that contains it, after the add keyword. The following example assumes that you are in your AWS CDK project's main directory. dotnet add src/ PROJECT-DIRpackage Amazon.CDK.AWS.IoT.Alpha -v VERSION-NUMBER To install a specific version of a package, include the -v flag and the desired version. To update a package, issue the same dotnet add command you used to install it. For experimental modules, again, you must specify an explicit version number. For more information about managing packages using the dotnet command, see Install and Manage Packages Using the dotnet CLI The nuget command The nuget command line tool can install and update NuGet packages. However, it requires your Visual Studio project to be set up differently from the way cdk init sets up projects. (Technical details: nuget works with Packages.config projects, while cdk init creates a newer-style PackageReference project.) We do not recommend the use of the nuget tool with AWS CDK projects created by cdk init. If you are using another type of project, and want to use nuget, see the NuGet CLI Reference AWS CDK idioms in C# Props All AWS Construct Library classes are instantiated using three arguments: the scope in which the construct is being defined (its parent in the construct tree), an id, and props, a bundle of key/value pairs that the construct uses to configure the resources it creates. Other classes and methods also use the "bundle of attributes" pattern for arguments. In C#, props are expressed using a props type. In idiomatic C# fashion, we can use an object initializer to set the various properties. Here we're creating an Amazon S3 bucket using the Bucket construct; its corresponding props type is BucketProps. var bucket = new Bucket(this, "MyBucket", new BucketProps { Versioned = true }); Add the package Amazon.JSII.Analyzers to your project to get required-values checking in your props definitions inside Visual Studio. When extending a class or overriding a method, you may want to accept additional props for your own purposes that are not understood by the parent class. To do this, subclass the appropriate props type and add the new attributes. // extend BucketProps for use with MimeBucket class MimeBucketProps : BucketProps { public string MimeType { get; set; } } // hypothetical bucket that enforces MIME type of objects inside it class MimeBucket : Bucket { public MimeBucket( readonly Construct scope, readonly string id, readonly MimeBucketProps props=null) : base(scope, id, props) { // ... } } // instantiate our MimeBucket class var bucket = new MimeBucket(this, "MyBucket", new MimeBucketProps { Versioned = true, MimeType = "image/jpeg" }); When calling the parent class's initializer or overridden method, you can generally pass the props you received. The new type is compatible with its parent, and extra props you added are ignored. A future release of the AWS CDK could coincidentally add a new property with a name you used for your own property. This won't cause any technical issues using your construct or method (since your property isn't passed "up the chain," the parent class or overridden method will simply use a default value) but it may cause confusion for your construct's users. You can avoid this potential problem by naming your properties so they clearly belong to your construct. If there are many new properties, bundle them into an appropriately-named class and pass them as a single property. Generic structures In some APIs, the AWS CDK uses JavaScript arrays or untyped objects as input to a method. (See, for example, AWS CodeBuild's BuildSpec.fromObject() method.) In C#, these objects are represented as System.Collections.Generic.Dictionary<String, Object>. In cases where the values are all strings, you can use Dictionary<String, String>. JavaScript arrays are represented as object[] or string[] array types in C#. You might define short aliases to make it easier to work with these specific dictionary types. using StringDict = System.Collections.Generic.Dictionary<string, string>; using ObjectDict = System.Collections.Generic.Dictionary<string, object>; Missing values In C#, missing values in AWS CDK objects such as props are represented by null. The null-conditional member access operator ?. and the null coalescing operator ?? are convenient for working with these values. // mimeType is null if props is null or if props.MimeType is null string mimeType = props?.MimeType; // mimeType defaults to text/plain. either props or props.MimeType can be null string MimeType = props?.MimeType ?? "text/plain"; Building, synthesizing, and deploying The AWS CDK automatically compiles your app before running it. However, it can be useful to build your app manually to check for errors and run tests. You can do this by pressing F6 in Visual Studio or by issuing dotnet build src from the command line, where src is the directory in your project directory that contains the Visual Studio Solution ( .sln) file. The stacks defined in your AWS CDK app can be synthesized and deployed individually or together using the commands below. Generally, you should be in your project's main directory when you issue them. cdk synth: Synthesizes a AWS CloudFormation template from one or more of the stacks in your AWS CDK app. cdk deploy: Deploys the resources defined by one or more of the stacks in your AWS CDK app to AWS. You can specify the names of multiple stacks to be synthesized or deployed in a single command. If your app defines only one stack, you do not need to specify it. cdk synth # app defines single stack cdk deploy Happy Grumpy # app defines two or more stacks; two are deployed You may also use the wildcards * (any number of characters) and ? (any single character) to identify stacks by pattern. When using wildcards, enclose the pattern in quotes. Otherwise, the shell may try to expand it to the names of files in the current directory before they are passed to the AWS CDK Toolkit. cdk synth "Stack?" # Stack1, StackA, etc. cdk deploy "*Stack" # PipeStack, LambdaStack, etc. You don't need to explicitly synthesize stacks before deploying them; cdk deploy performs this step for you to make sure your latest code gets deployed. For full documentation of the cdk command, see AWS CDK Toolkit (cdk command).
https://docs.aws.amazon.com/cdk/v2/guide/work-with-cdk-csharp.html
CC-MAIN-2022-40
refinedweb
1,901
55.95
In this shot, we will discuss how to generate an inverted hollow equilateral triangle using asterisks in Python. We can print a plethora of patterns using Python. A prerequisite for doing so is having a good understanding of loops. Here, we will be using simple for loops to generate the inverted triangle. A triangle is said to be equilateral if all three sides are of the same length. An inverted equilateral triangle is an upside-down triangle with equal sides. To execute it using Python, we will be using two for loops nested within an outer for loop: Let’s look at the code snippet below. def inverted_hollow_triangle(n): # Loop over number of rows and columns for i in range(n): # Spaces across rows for j in range(i): print(" ", end="") # Conditions for creating the pattern for k in range(2*(n-i)-1): if k==0 or k==2*(n-i-1) or i==0: print("*", end="") else: print(" ", end="") print() inverted_hollow_triangle(9) In line 4, we create a loop to iterate over the number of rows. In lines 7 and 8, we create a loop that gives the initial spaces (before characters) across each row. In lines 11 to 15, we create another inner loop to form the given pattern. In lines 13 to 15, we specify that whenever the condition for either being the left asterisk or the right asterisk is met, a * is printed. In case the conditions aren’t met, we print empty spaces. In line 16, the print() statement is used to move to a new line. RELATED TAGS CONTRIBUTOR View all Courses
https://www.educative.io/answers/how-to-generate-an-inverted-hollow-triangle-using-asterisks
CC-MAIN-2022-33
refinedweb
269
61.67