text stringlengths 20 1.01M | url stringlengths 14 1.25k | dump stringlengths 9 15 ⌀ | lang stringclasses 4
values | source stringclasses 4
values |
|---|---|---|---|---|
Hi guys. In the last article, we discussed how to add styles in React Native. In this article, we will discuss how to create React Native Class based Components.
Before we begin, let’s discuss the difference between class based component and functional based component.
React Native Functional based Components
Functional based component is a great way to introduce you to React Native. But its functionality is little bit limited. In functional based components, you put data in one end and JSX comes in the other end. That’s the only thing it can do. There’s no capability to do more complex tasks such as fetch data or initiate more complicated operations. We normally use functional based components for representational needs like displaying some content to the user. It’s only ability is to present static data.
React Native Class based Components
React Native Class based Components are more complex and more code to be written. But they have more functionalities which functional based components doesn’t have. They can be used for fetching data, easier to use to write large components and also easier to organize large amounts of data because we gets a nice class type structure where you can add many helper methods in there. These types of components are called class based because it is based on ES6 classes(ES6 is the new version of JavaScript) that extends a base class called Component.
Let’s create a class based component. Before that we need to create a file structure because if you are building a project, you should have a nice file structure.
Creating a file structure for your project
First create a folder inside your project folder named ‘src’. Inside that folder, create another folder named ‘components’. Now move App.js from its current position to inside ‘src’ folder. Now your file structure should be as following.
Now you have changed the position of App.js file. So, you have to change index.js file according to that. You have to change the path of import statement of App.js file inside index.js file.
import {AppRegistry} from 'react-native'; import App from './src/App'; import {name as appName} from './app.json'; AppRegistry.registerComponent(appName, () => App);
Now we are done with creating file structure for now. Let’s build a class based component now.
Creating a class based component
First, create a javaScript file inside components folder and name it ‘DataList.js’. Inside that file, write the following code.
import React, { Component } from 'react'; import { Text, View } from 'react-native'; class DataList extends Component { render(){ return( ); } } export default DataList;
Here, just like in class based components we have to import the two react native libraries. As I mentioned before we extend a base class called Component. That means we are borrowing bunch of functionalities from that class. For that, as you can see in the first line of code, we have imported Component class from react library. Inside that class based component, we write a render method and return method inside the render method. We have to export the component at the end as well. This is how you create a React Native Class based Components. Let’s add some JSX into that code.
import React, { Component } from 'react'; import { Text } from 'react-native'; class DataList extends Component { render(){ return( <Text>Class based Components has more functionalities.</Text> ); } } export default DataList;
We have finished coding a basic class based component now. But, if you run the app now, you wouldn’t see any change in the UI because we didn’t import it in App.js. We know index.js is the only file that runs in mobile app as I have mentioned in a previous chapter. App.js have been imported into index.js. So, to show DataList.js, we need to import it in App.js. Add the following import statement in App.js.
import DataList from './components/DataList';
Now, we have to add the DataList component inside return method in App.js, as a JSX element.
To keep one root element, wrap the current JSX elements with another View tag in App.js as given below.
const App = () => { return ( <View> <View style={styles.viewStyle}> <Text style={styles.textStyle}>Hello World!</Text> </View> <DataList/> </View> ); }
We added View tag as a root element and entered DataList component inside that. This is how you import a component inside another component. Now, let’s run our app again.
Well, we have got what we wanted. We have previous header section as well as new DataList class component.
I have given you the whole code of App.js, DataList.js and index.js below.
DataList.js
import React, { Component } from 'react'; import { Text } from 'react-native'; class DataList extends Component { render(){ return( <Text>Class based Components has more functionalities.</Text> ); } } export default DataList;
App.js
//Import a library to help to create a component. import React from 'react'; import { Text, View } from 'react-native'; import DataList from './components/DataList'; //Create the component. const App = () => { return ( <View> <View style={styles.viewStyle}> <Text style={styles.textStyle}>Hello World!</Text> </View> </DataList> </View> ); } const styles = { viewStyle: { backgroundColor: '#04A5FA', justifyContent: 'center', alignItems: 'center', height: 60, paddingTop: 15, shadowColor: '#000', shadowOffset: { width: 0, height: 2 }, shadowOpacity: 0.2, elevation: 2, position: 'relative' }, textStyle: { fontSize: 20, fontWeight: 'bold' } } //Render it to the device. export default App;
index.js
import {AppRegistry} from 'react-native'; import App from './src/App'; import {name as appName} from './app.json'; AppRegistry.registerComponent(appName, () => App);
This is only the creation of class based components. We will learn more about class based components and what it can do, in the future articles.
Thank you. | http://coderaweso.me/react-native-class-based-components/?utm_source=rss&utm_medium=rss&utm_campaign=react-native-class-based-components | CC-MAIN-2020-16 | en | refinedweb |
Hide Forgot
abrt 1.0.9 detected a crash.
architecture: x86_64
Attached file: backtrace
cmdline: /usr/lib64/openoffice.org3/program/swriter.bin -writer
component: openoffice.org
crash_function: writerfilter::(anonymous namespace)::DomainMapper::utext
executable: /usr/lib64/openoffice.org3/program/swriter.bin
global_uuid: 72c7d780b9da16fe13f15d0d0643e96503b6f61a
kernel: 2.6.32.12-115)
How to reproduce
-----
1. Happens everytime i open a *.docx file
2.
3.
Created attachment 415443 [details]
File: backtrace
*** This bug has been marked as a duplicate of bug 583386 *** | https://partner-bugzilla.redhat.com/show_bug.cgi?id=594397 | CC-MAIN-2020-16 | en | refinedweb |
Opened 7 years ago
Closed 7 years ago
#6342 enhancement closed fixed (fixed)
Deprecate twisted.python.hashlib
Description
hashlib was introduced in py2.5 and
twisted.python.hashlib was added in 2007 (#2763) to "allow[s] application code to transparently use APIs which existed before C{hashlib} was introduced or to use C{hashlib} if it is available."
Twisted supports Python 2.6 and up and twisted's hashlib can be deprecated, and uses of it replaced, to make it easier to support py3 and discourage users from using this module.
Initially I wanted to file a ticket for porting this module to py3 but why port it when its there for (now) unsupported versions of Python.
Attachments (3)
Change History (19)
comment:1 Changed 7 years ago by
Changed 7 years ago by
comment:2 Changed 7 years ago by
comment:3 Changed 7 years ago by
comment:4 Changed 7 years ago by
comment:5 Changed 7 years ago by
Thanks for your contribution.
- Don't delete the existing test. Even if people shouldn't be using the code, we don't want the code to break. The tests should only be removed when the code they are testing gets removed.
- You'll want to make sure that the warning is suppressed in those tests (using the
.suppressattribute and
twisted.trial.util.suppress).
- Similarily, the module docstring doesn't want to be completely deleted. On the other hand, it should be changed to include the deprecation information (
twisted.python.deprecate._getDeprecationDocstringhas the standard format for that). It probably also wants to be changed to indicate that twisted doesn't use it anymore.
- There are still a couple of uses t.p.hashlib left after applying your patch. - `twisted/conch/client/knownhosts.py'
twisted/conch/ssh/keys.py
twisted/web/server.py
- Your change needs a news file.
- The conditional (try) logic in
t.p.hashlibcan be removed. On supported versions, the
exceptwill never trigger.
- Refer to 'stdlib' or 'standard library' not 'Python Core'.
Changed 7 years ago by
lastest patch
comment:6 Changed 7 years ago by
comment:7 Changed 7 years ago by
Thanks for your contribution.
- You can probably just do something likeThe code was structured the way it was before so it only did the import once. (Although, on further consideration, I'm not sure why the code wasn't like that to begin with.
from hashlib import md5, sha1
- 13.0.0 was the most recent release, so 13.1.0 will be the next release. That will be the release where this will be deprecated.
- Calls to
.flushWarningsshould include a function to blame. This is to verify that the stacklevel argument is set correctly. It should point to the function that is invoking the deprecated functionality.
- The spacing between functions and classes doesn't follow the coding standard.
- (minor) Also, there typically isn't a blank line after method docstrings
- There is a spurious blank line at the begining of hashlib's module docstring.
Changed 7 years ago by
comment:8 Changed 7 years ago by
comment:9 Changed 7 years ago by
comment:10 Changed 7 years ago by
comment:11 Changed 7 years ago by
comment:12 Changed 7 years ago by
Reviewing...
comment:13 Changed 7 years ago by
Code Review
Thanks for the branch. Here's a quick review.
Notes:
- Branch merges cleanly to trunk
- Tests pass locally on Fedora 18 x86_64
I spotted one minor thing:
- source:branches/deprecate-hashlib-6342/twisted/python/test/test_hashlib.py
- test_deprecation
- "Test to" in docstring is unnecessary
Otherwise the branch looks fine and I couldn't find any remaining uses of twisted.python.hashlib. Fix that docstring and then merge.
-RichardW.
comment:14 Changed 7 years ago by
Thanks for the review, I'll fix that docstring and merge.
You can see an example deprecation in
twisted/conch/insults/__init__.pyand the applicable tests in
twisted/conch/test/test_insults.py. | https://twistedmatrix.com/trac/ticket/6342 | CC-MAIN-2020-16 | en | refinedweb |
#include <vtkDebugLeaks.h>
vtkDebugLeaks is used to report memory leaks at the exit of the program. It uses the vtkObjectFactory to intercept the construction of all VTK objects. It uses the UnRegister method of vtkObject to intercept the destruction of all objects. A table of object name to number of instances is kept. At the exit of the program if there are still VTK objects around it will print them out. To enable this class add the flag -DVTK_DEBUG_LEAKS to the compile line, and rebuild vtkObject and vtkObjectFactory.
Definition at line 42 of file vtkDebugLeaks.h.
Reimplemented from vtkObject.
Definition at line 46 of file vtkDebugLeaks.h.
Definition at line 73 of file vtkDebugLeaks.h.
Definition at line 74 of file vtkDebugLeaks.h.
Call this when creating a class of a given name.
Call this when deleting a class of a given name.
Print all the values in the table. Returns non-zero if there were leaks.
Get/Set flag for exiting with an error when leaks are present. Default is on when testing and off otherwise.
Get/Set flag for exiting with an error when leaks are present. Default is on when testing and off otherwise.
Definition at line 82 of file vtkDebugLeaks.h. | https://vtk.org/doc/release/5.8/html/a00508.html | CC-MAIN-2020-16 | en | refinedweb |
Hello all!
I've begun coding for the ArbotiX and the Dynamixel AX-12 servos using the Arduino IDE on Ubuntu Linux (with the BioloidController library). I've installed and configured everything according to the online instructions for the Arduino and the ArbotiX, and I'm able to load programs and control my servos no problem.
My problem lies with the Serial Monitor in the Arduino IDE. I'm trying to display servo data like position, load etc., and program debug output, but nothing will output to the Serial Monitor. Even a simple "Hello World!" produces no output.
e.g.
#include <ax12.h>
void setup() {
Serial.begin(38400);
}
void loop() {
Serial.println("Hello World!");
delay(1000);
}
I read somewhere that the Serial Monitor on Linux will not work correctly with certain versions of GCC (edit: programs compiled with certain versions of GCC). I'm hoping someone here can help!
My setup is as follows (some of which I realise is redundant given my problem, but just in case...
):):
Ubuntu 10.04 LTS (32-bit version)
ArbotiX Robocontroller and the Pololu ISP
AX-12 servos (from the Bioloid Comprehensive Kit)
Arduino 0018 (with the BioloidController library)
From a terminal my versions of gcc (gcc --version) and avr-gcc (avr-gcc -version) are as follows:
gcc (Ubuntu 4.4.3-4ubuntu5) 4.4.3
avr-gcc (GCC) 4.3.4
Does anyone else have a similar setup to mine and experience or knowledge of this issue?
Thanks,
Stephen
Bookmarks | http://forums.trossenrobotics.com/showthread.php?4386-Arduino-IDE-Serial-Monitor-output-on-Linux&s=1bb95f2af2ca5d9e8cfe72f65fe9bbd0 | CC-MAIN-2020-16 | en | refinedweb |
react-native-line-sdk, the react-native wrapper for LINE
A few days ago we released our very first React Native framework to the open source community. react-native-line provides an easy-to-use interface for you to use Line’s mobile SDK seamlessly on your app, without having to worry about Android or iOS differences.
How to use it?
To start working with react-native-line-sdk, you need to add it to your react-native project using your package manager of preference. For example:
npm install react-native-line-sdk
Then, you need to link the native implementations to your project running:
react-native link react-native-line-sdk
After that, you need to follow the Android and iOS guides available here
Example usage
As an example, let’s make a login flow that uses Line’s SDK:
First, you need to require the
LineLogin module on your js file:
import LineLogin from 'react-native-line-sdk'
Then, on your call to action (for example, a TouchableOpacity) you need to call the
login function. This will open Line’s own UI (App, or browser, if the app is not installed on the device) and it will resolve the promise when the user finishes that flow successfuly.
LineLogin.login() .then((user) => { /* Here, send the user information to your own API or external service for autentication. The user object has the following information: { profile: { displayName: String, userID: String, statusMessage: String, pictureURL: String?, } accessToken: { accessToken: String, expirationDate: String, } } */ }) .catch((err) => { // The promise will be rejected if something goes wrong, check the error message for more information. });
At this point, you should use the promise callbacks to handle the information returned by Line and continue your autentication flow as needed.
Where to go from here
We hope our article works as a good introduction to this open source library. On GitHub you’ll find everything you need to get started. If you want to collaborate, feel free to contribute with this library. If you need help to develop your project, drop us a line! | https://blog.xmartlabs.com/2017/11/27/React-native-line/ | CC-MAIN-2020-16 | en | refinedweb |
Recently I've had to build a bunch of REST API's and I've been writing them mostly with Node.js and express. I ran into a scenario where I was building an internal admin panel and I wanted to ensure there was a proper authentication & authorization scheme to both
- Authenticate users who were allowed to access the panel
- Provide permissions and authorize certain API's only for select roles/users
Solving for (1) is fairly easy nowadays because with the power of libraries such as Passport or delegating authentication to a Backend-as-a-Service platforms like Firebase, getting that working is a quick task and a non-issue. However, the harder work comes with authorization. How do I ensure that only properly authenticated/authorized users could access the API's that I was writing? That is the focus for this post.
Implementing an authorization rule
Creating an authorization rule is actually not that difficult. Let's say you will only allow a user to modify his/her own data if he/she is the owner of that data. Assuming you follow standard security practices and provide an Authorization HTTP header for one of the following Authentication types, it's as simple as re-authenticating and validating that the user is who he says he is, checking whether the user has access to his own account, and then allowing him to update it.
As a simple example, I'm going to describe a use case where you are making a
POST request to a url endpoint ending in
/:userId/verify, where
userId is the id of the user you want to make the update. Let's also say the user has already been authenticated on the browser and sends an Authorization header with the request: a JWT token using the Bearer token schema.
So your header might look like:
Authorization: Bearer <JWT token>
And your express code to handle this request might look like:
import { userUpdate } from '../services/users' import { getBearerToken, verifyTokenAndGetUID } from '../utils/authentication' ... router.post('/:userId/verify', (req, res, next) => { const authHeader = req.headers.authorization const { userId } = req.params const data = req.body if (!authHeader) { return res.status(403).json({ status: 403, message: 'FORBIDDEN' }) } else { const token = getBearerToken(authHeader) if (token) { // This promise returns the userId of this token // We will validate whether the current authenticated user has access to update the current userId. return verifyTokenAndGetUID(token) .then((userId) => { if (req.auth && req.auth.userId && userId === req.auth.userId) { return userUpdate(userId, data) } else { res.status(401).json({ status: 401, message: 'UNAUTHORIZED' }) } }) .catch((err) => { logger.logError(err) return res.status(401).json({ status: 401, message: 'UNAUTHORIZED' }) }) } else { return res.status(403).json({ status: 403, message: 'FORBIDDEN' }) } } })
In layman's terms, this code block is doing the following:
- If an authorization token is not provided, return a
403
- If a token is provided, make sure it's of the right Authorization scheme
- If not, return a
401. Otherwise, verify the token and retrieve the user id for this token.
- If it is not a valid/verifiable token, return
401. Otherwise check if the returned user id it is allowed to make the update against the provided user id in the HTTP request
- If not, return
401. Otherwise, continue with the request.
This works great for what we need this API to do. Only one problem - you don't want to have to write this over and over again for each REST API endpoint you create. There's a principle in software development called DRY (don't repeat yourself), so let's make it so that we don't have to redundantly write this same authorization rule everywhere.
Express middleware to the rescue
If you've done any sort of development in express, you may be aware of a lil something called Express Middleware. The TL;DR is that express middleware performs the following tasks:
- Execute any code.
- Make changes to the request and the response objects.
- End the request-response cycle.
- Call the next middleware function in the stack.
For any API endpoint that we write, we can bind an application-level middleware and have it run the authorization rule before deciding whether or not to proceed. Using the example from before, this is how we can rewrite it:
// Router import { userUpdate } from '../services/users' import { isUserAuthenticated } = '../authMiddleware' router.post('/:userId/verify', isUserAuthenticated, (req, res, next) => { const { userId } = req.params const data = req.body if (res.locals.auth && res.locals.auth.userId && userId === res.locals.auth.userId) { return userUpdate(userId, data) } else { res.status(401).json({ status: 401, message: 'UNAUTHORIZED' }) } })
// Authorization Rules Middleware // authMiddleware.js export const isUserAuthenticated = (req, res, next) => { const authHeader = req.headers.authorization if (!authHeader) { return res.status(403).json({ status: 403, message: 'FORBIDDEN' }) } else { const token = getBearerToken(authHeader) if (token) { return verifyTokenAndGetUID(token) .then((userId) => { // ------------------------------------ // HI I'M THE UPDATED CODE BLOCK, LOOK AT ME // ------------------------------------ res.locals.auth = { userId } next() }) .catch((err) => { logger.logError(err) return res.status(401).json({ status: 401, message: 'UNAUTHORIZED' }) }) } else { return res.status(403).json({ status: 403, message: 'FORBIDDEN' }) } } }
Notice that we put the middleware into its own module so that it can be reused in any other express endpoint as necessary. You'll also see that in our Express route initialization, that we add this middleware as part of the
app.METHOD initilization, where it will execute the authorization rule before continuing. In our updated code block within the authorization rule, you'll see that we call
next() to pass control to the next middleware function. Otherwise, the request will be left hanging.
One last thing to notice is that once the middleware authorization rule is done, we need to pass the data back onto the next middleware function (i.e to do the user id validation). So you'll see that we are passing the returned
userId through
res.locals, which stores any object scoped throughout the lifetime of this request. This is recommended through even the official express docs.
And that's it!
More and more middleware
Writing this middleware will enable us to write an authorization rule once, and then for every request to
app.METHOD that needs this rule, we can run simply add the middleware to the request. The best part is that we can add as many as we want to the request by simply wrapping it in an array!
Here is an example of a series of REST API's that I have implemented that leverage similar authorization middleware:
/** * Gets all newsletters created */ router.get('/', [isUserAuthenticated], (req, res, next) => { res.api(getNewsletterHistory()) }) /** * Schedules a newsletter to be sent */ router.post('/', [isUserAuthenticated, isAdminUser], (req, res, next) => { const data = req.body res.api(scheduleAndSendWeeklyNewsletter(data)) }) /** * Schedules a test newsletter to be sent to the specified email */ router.post('/test', [isUserAuthenticated, isAdminUser], (req, res, next) => { const data = req.body const { email, content } = data res.api(sendTestNewsletter(email, content)) }) /** * Gets all scheduled newsletters */ router.get('/scheduled', [isUserAuthenticated], (req, res, next) => { res.api(getScheduledNewsletters()) }) /** * Deletes a scheduled newsletter */ router.delete('/scheduled', [isUserAuthenticated, isAdminUser], (req, res, next) => { const data = req.query res.api(deleteScheduledNewsletter(data)) }) export default router
You'll see that some of the API's have different rules. "READS" only requires the user to be authenticated, but making any "WRITES" requiers to the user to be an admin user. (If you look closely, you'll also notice that I wrote a custom middleware to standardize all API responses as well, but more on that in a future post).
Got any other suggestions?
In a year of security breaches and GDPR, data privacy has become super important. So if you're an Express pro, have other ideas, or if my solution is trash and you got a better one, please share it! | https://caffeinecoding.com/leveraging-express-middleware-to-authorize-your-api/ | CC-MAIN-2020-16 | en | refinedweb |
Difference between revisions of "FOCS Scripting Tutorial"
Revision as of 11:34, 23 March.
Creating a new entry
- Create a new file in the default/scripting/buildings/ directory, name it TUTORIAL_ONE.focs.txt
BuildingType name = "BLD_TUTORIAL_ONE" description = "BLD_TUTORIAL_ONE_DESC" buildcost = 15 buildtime = 1 icon = ""
- It is good practice to make sure the file ends with a blank line.
This creates a very basic building type that could be built anywhere but has no effect.
No player would be able to build this building however, as their empire does not know how.
For now, we will just give the knowledge to everyone at the start of the game:
- Edit default/scripting/starting_unlocks/items.inf
- Add the following line at the top
Item type = Building name = "BLD_TUTORIAL_ONE"
If you start the game now and select the production screen at your home planet, you will see:
ERROR: BLD_TUTORIAL_ONE
Hover over that and the tooltip shows:
ERROR: BLD_TUTORIAL_ONE_DESC
This is because we have not told the game what our building should be labelled as, just to use the key reference of BLD_TUTORIAL_ONE.
Just like the filename, key references could be named anything, regardless of what label we want to use.
The name entry in the definition needs to be unique, but description can be shared among other entries if needed.
The key references are looked up based on the language selected, in one of the stringtables.
You can start with the file that suits you best, for this example we will use the english file.
- Edit default/stringtables/en.txt
- On the next blank line enter the following
BLD_TUTORIAL_ONE A new building type from the scripting tutorial. BLD_TUTORIAL_ONE_DESC This is a brand new building type we just created.
- Make sure there are blank lines before and after these new entries.
If you.
Entry Files
All of the FOCS entry files have a double extension of .focs.txt.
These files will be loaded regardless of the rest of their filename, or how deeply nested in the sub-directory they are.
Some special entry files have the extension .inf.
While most of these files can be freely edited, they can not be renamed or moved.
Any other file extension is not loaded into the game, unless an entry file specifically includes it.
The extension .macros is commonly used to denote scripting macros used in various entry files.
Entries that are not wanted in the game currently, but kept around for reference, are typically given the extension .disabled.
Entry files should never #include a file with another entry definition in it.
Directory Structure
Entry files are categorized by their type and should remain within the directory for that type (nested sub-directories are ok).
For example Tech entries can be anywhere in default/scripting/techs/, but should never be in default/scripting/fields/.
This only applies to the actual definition files, those with the extension .focs.txt.
The following directories within default/scripting are for .focs.txt entries:
Required files
These are relative to default/scripting/:
Additionally, definitions listed in any starting_unlocks/ file or monster_fleets.inf need to be avaiable.
The default AI may assume any or all of the default entries to exist.
Macros
A basic macro definition looks like this:
FIRST_ONE '''2'''
The three apostrophies denote preformatted text, meaning any newlines are part of the macro.
Macro names should be in all uppercase, with underscores in place of spaces. They should also be uniquely named.
References to a macro are done by adding double brackets:
buildtime = [[FIRST_ONE]]
The game will end up seeing this as buildtime = 2
Macros may also use arguments:
NEW_MACRO '''@[email protected] * @[email protected]'''
- Multiplies the first argument by the second.
[[NEW_MACRO(2,3)]]
- Results in 6 (2 * 3)
You can pass other macros for the arguments:
[[NEW_MACRO(FIRST_ONE,4)]]
- Results in 8 (2 * 4)
Macros are mainly used to keep consistant values for multiple definitions.
When this is the case, it is best to have the macro definition in a file by itself, so other files can include it.
Sometimes macros are used for a complicated formula to help the readablity of the file. There is no need for these macro definitions to be separated if they are never used in another definition.
Including other files
Files are usually included for macro definitions.
You can include another file with the #include directive:
#include "some_file.macros"
- Includes the file named some_file.macros
The directive should by on a line by itself, without any spaces before #include. There is no restriction on what files are included, however you should not include files containing another FOCS entry in it. This would lead to a conflict when the entry is loaded twice.
Troubleshooting
If the entry is in the game, but does not show the name or the description correctly, check the stringtable entry for your selected language.
Typically if there is a problem with the game parsing an entry, it will show the error in the console window. The error will also be in the log file freeorion.log, which is located in your user directory (Options > Directories > Save files (parent directory))
If there are no errors shown, you can make sure the file is loading by setting the log level to TRACE.
Either edit the config.xml file in your user directory or launch the game with the --log-level TRACE argument.
The client log file (freeorion.log) will now show each file as it was loaded in, as well as any files that were skipped.
If you need further help, post a question in the forums.. | https://freeorion.org/index.php?title=FOCS_Scripting_Tutorial&diff=next&oldid=9325 | CC-MAIN-2020-16 | en | refinedweb |
analog_clock 0.0.4
Flutter Analog Clock Widget #
Clean and fully customizable analog clock widget.
Installation #
In your
pubspec.yaml file within your Flutter Project:
dependencies: analog_clock: ^0.0.1
Features #
- Modern and clean analog clock interface.
- Fully customizable.
- Live clock.
- Custom datetime.
Usage #
import 'package:analog_clock/analog_clock.dart'; AnalogClock( decoration: BoxDecoration( border: Border.all(width: 2.0, color: Colors.black), color: Colors.transparent, shape: BoxShape.circle), width: 150.0, isLive: true, hourHandColor: Colors.black, minuteHandColor: Colors.black, showSecondHand: false, numberColor: Colors.black87, showNumbers: true, textScaleFactor: 1.4, showTicks: false, showDigitalClock: false, datetime: DateTime(2019, 1, 1, 9, 12, 15), );
Parameters #
Example #
Demo app can be found in the
example/ folder.
0.0.1 #
- Fully working version without tests.
0.0.2 #
- Fixing Dart Pub link.
0.0.3 #
- Ability to showing all the numbers around the clock and bumping up the kotlin version thanks to @pidmid
0.0.4 #
- Migrating example project to AndroidX and fixing kotlin bug.
import 'package:analog_clock_example/demo.dart'; import 'package:flutter/material.dart'; import 'package:analog_clock/analog_clock.dart'; void main() => runApp(MyApp()); //void main() => runDemo(); class MyApp extends StatefulWidget { @override _MyAppState createState() => _MyAppState(); } class _MyAppState extends State<MyApp> { @override Widget build(BuildContext context) => MaterialApp( home: Scaffold( body: AnalogClock(), )); }
Use this package as a library
1. Depend on it
Add this to your package's pubspec.yaml file:
dependencies: analog_clock: :analog_clock/analog_clock.dart';
We analyzed this package on Mar 27, 2020, and provided a score, details, and suggestions below. Analysis was completed with status completed using:
- Dart: 2.7.1
- pana: 0.13.6
- Flutter: 1.12.13+hotfix. | https://pub.dev/packages/analog_clock | CC-MAIN-2020-16 | en | refinedweb |
It is used to get/set stream buffer. If sb is a null pointer, the function automatically sets the badbit error state flags (which may throw an exception if member exceptions has been passed badbit).
Some derived stream classes (such as stringstream and fstream) maintain their own internal stream buffer, to which they are associated on construction. Calling this function to change the associated stream buffer shall have no effect on that internal stream buffer: the stream will have an associated stream buffer which is different from its internal stream buffer (although input/output operations on streams always use the associated stream buffer, as returned by this member function).
Following is the declaration for ios::rdbuf function.
get (1) streambuf* rdbuf() const; set (2) streambuf* rdbuf (streambuf* sb);
The first form (1) returns a pointer to the stream buffer object currently associated with the stream.
The second form (2) also sets the object pointed by sb as the stream buffer associated with the stream and clears the error state flags.
sb − Pointer to a streambuf object.
A pointer to the stream buffer object associated with the stream before the call.
Basic guarantee − if an exception is thrown, the stream is in a valid state. It throws an exception of member type failure if sb is a null pointer and member exceptions was set to throw for badbit.
Accesses (1) or modifies (2) the stream object.
Concurrent access to the same stream object may cause data races.
In below example explains about ios::rdbuf function.
#include <iostream> #include <fstream> int main () { std::streambuf *psbuf, *backup; std::ofstream filestr; filestr.open ("test.txt"); backup = std::cout.rdbuf(); psbuf = filestr.rdbuf(); std::cout.rdbuf(psbuf); std::cout << "This is written to the file"; std::cout.rdbuf(backup); filestr.close(); return 0; } | https://www.tutorialspoint.com/cpp_standard_library/cpp_ios_rdbuf.htm | CC-MAIN-2020-16 | en | refinedweb |
Users of Visual Studio 2003 and newer may directly go to the next post#2 and skip this one.
- - -
Q: How to use 'CString' in non-MFC applications?
A: In most cases, you don't need to do that. In order to use 'CString' you have to statically or dynamically link your application to the entire MFC. This would not only increase the size of your executable file, the number of its dependencies, but also makes your program non-portable (especially if it is a Console application).
The recommended solution is to use the Standard C++ Class 'std::string'. It is as powerful as 'CString', is portable, using it does not imply adding a huge amount of things you don't need to your project and last, but not least, it is part of the programming language.
This being said, if you still want to use 'CString' in your non-MFC application, here it is whar you have to do:
Include 'afx.h' in one of your main headersOpen the menu 'Project -> Settings'. On the 'General' register of the settings dialog box choose 'Use MFC in a Shared DLL' or 'Use MFC in a Static Library' from the dropdown box called 'Microsoft Foundation Classes'.Rebuild your project.A simple sample of a console application using 'CString' looks like this:
Code:
#include <afx.h>
#include <iostream>
int main()
{
CString s("Hello");
std::cout << s.GetBuffer(0) << std::endl;
return 0;
}
#include <afx.h>
#include <iostream>
int main()
{
CString s("Hello");
std::cout << s.GetBuffer(0) << std::endl;
return 0;
}
Last edited by JeffB; June 17th, 2009 at 02:35 PM.
Reason: Fixed include using html characters
Forum Rules | http://forums.codeguru.com/showthread.php?231164-C-String-How-to-use-CString-in-non-MFC-applications&p=678875&mode=threaded | CC-MAIN-2015-40 | en | refinedweb |
Porting an Application to iPhone Using Flash CS5
Last week saw a very significant development in the relationship between Apple and Adobe. Flash is back in the iPhone picture. In this tutorial, I will show you how to convert an exisiting Flash movie to an iPhone application using Flash Professional CS5.
Step 1: Choose a Flash App
The first thing you need to do is select the application that you want to port. In this example we'll be working with the Digital Clock app we created in another ActiveTuts+ tutorial.
Step 2: Create a new iPhone OS File
Launch Flash CS5 and create a new iPhone OS Document.
Step 3: Landscape
As you can see, the default stage size is 320x480 px, which is the iPhone full screen resolution in portrait mode (this is holding the iPhone vertically).
However, this application is has a Landscape format and it won't look good if we adapt the interface to Portrait. Your first instinct is probably to rotate the interface 90° and build the app that way. It will work, but it will be very difficult and you will probably end up with neck pain. For this reason Flash CS5 includes a Publish option to make the iPhone application in landscape mode.
Set the stage size to 480x320 px and continue with the next step, we'll see how to set the app to Landscape mode in step 10.
Step 4: Interface
To port the interface, a simple copy and paste will be enough. Yes, it's that simple!
However, in most cases you will need to optimize the graphics, which involves size, alignment and the balance between vectors and bitmaps. Since we are using simple graphics, we'll focus on the alignment and the size of the elements.
Step 5: iPhone Adjustments
The original application size doesn't match the iPhone size, so the first thing to do is change the background size to fit the stage.
The current size of the clock text will look too small in the iPhone, select it and change the size to 120px.
Step 6: Class File
Copy and paste the class file to the source folder, no changes need to be made to this file.
Step 7: Document Class
Remember to add the class name to the Class field in the Publish section of the Properties panel.
Step 8: Test for Errors
You can now test your movie to see if everything works as intended.
Step 9: iPhone OS Settings
Here comes the part you're interested in; the iPhone part.
Now you have a perfectly working Flash movie, it's time to convert it to an iPhone application. Go to the Properties panel, Publish section and press the iPhone OS Settings button.
Step 10: General
You will now enter a window full of settings. These settings are:
- Output File: The name of the ipa file that will be created, this can be whatever you want.
- App Name: The name that will be shown in your iPhone below the icon.
- Version: The current version of the application; you need to edit this on every test for iTunes to update the app succesfully.
- Aspect Ratio: The view mode of your app.
- Full Screen: Hides the top info bar (signal, bluetooth, wifi, battery, etc).
- Auto Orientation: Uses the accelerometer to change the orientation without writing code.
- Rendering: A very important option, using the gpu for rendering in complex graphics applications will highly increase the performance.
- Included Files: The files to be included with your app. If you are loading content from an XML, TXT or any other source you should add those files here.
Step 11: Launch Image
Every iPhone application displays an image at launch while loading the essentials to show the app. This image is the Default.png file we included in step 10. It's recommended to show the same screen that the app will show when fully loaded, but you can use it to show your company logo, loading screen, title screen, or any other useful info.
The image must be 320x480 it doesn't matter if you're working in landscape mode.
Step 12: Deployment
For the Deployment tab, you will need to be a member of the iPhone Developer Program and follow the instructions in the Provisioning Portal to get the necesary files to compile your application.
Step 13: Certificates
There are three different kinds of certificates. The first is the Apple Worldwide Developer Certificate (WWDC). This certificate is compiled alongside one of the other two certificates: either a Developer certificate or a Distribution certificate. These are used for testing applications and deploying to the Apple Store, respectively.
Step 14: Provisioning Profile
The Provisioning Profile is basically a file that states which application we're testing and on which devices can we test it.
Step 15: App ID
An Identifier of your application, each application ID is required to have its own unique namespace that looks something like com.yourcompany.YourApp. This is also generated in the developer program site and included in your provisionig profile.
Step 16: Deployment Type
Select an option depending on the kind of certificate and provisioning profile you're working with. A Developer Certificate can be used for Quick Publishing and a Distribution Certificate is needed for deployment, using this kind of certificate will create an app ready to be submitted to the app store.
Step 17: Icons
Next is a simple one, the Icons tab.
Three sizes of icons must be used 29x29px, 57x57px (this is the icon shown in the device) and 512x512px. Don't worry about the round corners, iTunes will automatically generate them.
Step 18: Publish
When you're done filling the settings press the Publish button, a progress bar will appear showing the remaining time. The time it takes depends on your application and the files included. Also, more time is needed when publishing for deployment.
Step 19: Device Testing
An .ipa file will be created in your source folder, drag it or double-click it to open in iTunes. You will see the icon of your app with the other applications.
Sync your iPhone and get ready to run your new app!
Step 20: Submit App
If you're done porting your prefered application to iPhone and want to share it with the rest of the world, you can submit it to the App Store. Login at iTunes Connect and follow the guided instructions.
Conclusion
Now you know how easy it is to develop iPhone applications using Flash Pro CS5, start making your own!
I hope you liked this tutorial, thank you for reading!
Tuts+ tutorials are translated into other languages by our community members—you can be involved too!Translate this postPowered by
| http://code.tutsplus.com/tutorials/flash-for-iphone--active-5377 | CC-MAIN-2015-40 | en | refinedweb |
You're probably here because you don't know everything.
Acknowledgement
of a problem is the first step toward its solution.
Thinking you know what you think you know is the problem,
you know?
Tara Z. Manicsic
@tzmanics
Developer Experience Engineer @ Netlify
promises
i promise i'll get back to you as soon as i know
const myFirstPromise = new Promise((resolve, reject) => { // do something asynchronous which eventually calls either: // // resolve(someValue); // fulfilled // or // reject("failure reason"); // rejected });
async/await
make this asynchronous and then ahh, wait here until i get back to you
also, it's just a more readable promise
function resolveAfter2Seconds() { return new Promise(resolve => { setTimeout(() => { resolve('resolved'); }, 2000); }); } async function asyncCall() { console.log('calling'); var result = await resolveAfter2Seconds(); console.log(result); // expected output: 'resolved' }
currying
i see you have many parameters, why don't you curry them in separate buckets
function volume(l,w,h) { return l * w * h; } const aCylinder = volume(100,20,90) // 180000l function volume(l) { return (w) => { return (h) => { return l * w * h } } } const aCylinder = volume(100)(20)(90) // 180000
curry
immutability
an object whose state can not be modified after it is created
const obj = { prop: 42 }; Object.freeze(obj); obj.prop = 33; // Throws an error in strict mode console.log(obj.prop); // expected output: 42
const confusion
this
this is hard
i can't do this
globalThis
is exactly what it says it is: the globalThis
ECMAScript
scripting-language specification for JS
TC39 is the technical committee
the cloud
why it's named the cloud
serverless
serverless
==
worry less
microservices
micro: extremely small services:
the things your app does
micro: extremely small services:
the things your app does
microapps
micro: extremely small apps:
applications
micro puppies
micro: extremely small puppies:
tiny baby doggies
If you know someone is pretending they know but you know they don't know...
- what do you know
- you don' t know me
- i dare you
- shut your mouth
Tara Z. Manicsic
@tzmanics
Developer Experience Engineer @ Netlify
Serverless, Async/Await, Immutability and Other Things You Pretend to Understand
By Tara Z. Manicsic
Serverless, Async/Await, Immutability and Other Things You Pretend to Understand
Join me as we walk through plain English descriptions and joyful anecdotes of these mysterious terms. I aim to help you understand these terms enough to explain them to all the people you know that also pretend to understand them. “Currying? Sounds delicious!” is something you can avoid saying after this session. | https://slides.com/tzmanics/acknowledgement-of-a-problem-is-the-first-step-towards-its-solution | CC-MAIN-2022-33 | en | refinedweb |
Java — Thread Priorities | Code Factory
- Every Thread in Java has some priority. It may be default priority generated by JVM or customized priority provided by programmer.
- The valid range of thread priorities is 1 to 10. Where 1 is minimum priority and 10 is more priority.
- Thread class defines the following constant to represent some standard priorities.
Thread.MIN_PRIORITY
Thread.NORM_PRIORITY
Thread.MAX_PRIORITY
- Thread schedular will use priorities while allocating processor. The thread which is having highest priority will get chance first.
- If 2 threads have same priority then we can’t expect exact execution order, It depends on Thread Schedular.
- Thread class defines the following methods to get and set priority of a thread
/* Returns this thread's priority. */
public final int getPriority()/* Changes the priority of this thread. */
public final void setPriority(int newPriority)
- In setPriority method allowed values range 1 to 10 otherwise RE :
IllegalArgumentException
t.setPriority(7); // ✓
t.setPriority(17); // X
- The default priority only for the main thread is 5. But for all remaining threads default priority will be ingerited from parent to child. That is whatever priority thread has the same priority be there for the child thread.
package com.example.thread;public class ThreadTest {
public static void main(String... args) {
System.out.println(Thread.currentThread().getPriority());
//Thread.currentThread().setPriority(15); // RE : IllegalArgumentException
Thread.currentThread().setPriority(7);
MyThread t = new MyThread();
System.out.println(t.getPriority());
}
}class MyThread extends Thread {
}
Output :
5
7 | https://34codefactory.medium.com/java-thread-priorities-code-factory-5a13dbb2f9ee?source=post_internal_links---------0---------------------------- | CC-MAIN-2022-33 | en | refinedweb |
The objective of this post is to explain how to serve a simple HTML page from the ESP32, using the Arduino core. The tests of this ESP32 tutorial were performed using a DFRobot’s ESP-WROOM-32 device integrated in a ESP32 FireBeetle board.
Introduction
The objective of this post is to explain how to serve a simple HTML page from the ESP32, using the Arduino core. You can check on this previous post how to set the libraries needed for us to create a HTTP server.
Our web page will be a simple HTML form that we will serve from the asynchronous HTTP server. Please note that we will not create any CSS for styling our form, so it will be a pretty raw one, just to illustrate how to serve the HTML.
The tests of this ESP32 tutorial were performed using a DFRobot’s ESP-WROOM-32 device integrated in a ESP32 FireBeetle board.
The HTML code
We will start by designing the HTML code independently from the Arduino code. Then, we will use some tools to convert it to a compact string format we can use on the ESP32.
Explaining in detail the HTML code and how everything works is outside the scope of this post. So, basically, we are going to create a very simple form with two inputs and a submit button, as can be seen below.
<form onSubmit = "event.preventDefault()"> <label class="label">Network Name</label> <input type = "text" name = "ssid"/> <br/> <label>Password</label> <input type = "text" name = "pass"/> <br/> <input type="submit" value="Submit"> </form>
We are labeling the inputs as “Network Name” and “Password”, so this could be a possible implementation of a form to input a network’s WiFi credentials.
Please note that in this tutorial we are only going to cover the part of displaying the HTML content, so we are not going to develop the endpoint to receive the data from the form. Thus, we do the event.preventDefault() call on the submit action so nothing actually happens when we click the button.
Since we are developing for a microcontroller, which is a resource constrained device, we can compress the previous HTML for a single line format, thus getting rid of all the unnecessary tabs and new lines.
Although this will make the code hard to read for a person, it makes no difference to the client which will interpret it and allows us to save some space on the ESP32.
To perform this operation, we can use this online tool, which will minify our HTML code. To prevent problems, when working with complex HTML pages, my recommendation is that you always try the code locally after compressing it, to confirm no problem has occurred in the process.
To do so, you can simply paste the minified code in a text file, save with with a .html extension and open it with a web browser. If everything is ok, then you can use it on the ESP32.
You can check below at figure 1 the result of minifying the code with the online tool mentioned.
Figure 1 – Minification of the HTML code.
Nonetheless, we can not directly use this code as a string in Arduino because of the quotes it has. Thus, we will need to escape them.
Since HTML code typically has lots of quotes, the easiest way to get the escaped version is by using a tool such as this online one.
So, to escape the code, simply copy the previously minified version of the HTML and paste it on the tool, unchecking the “split output into multiple lines” option before starting the operation. You can check the expected result in figure 2.
Figure 2 – Escaping the minified HTML code in an online tool.
Now that we have the HTML code as a single line escaped C string, we can move on to the Arduino code.
The code
The code for this tutorial is similar to this previous one, with the exception that we are now going to serve a more complex HTML code, which we will store in the FLASH memory.
Since the HTML content is static, putting it on the FLASH Memory avoids consuming RAM, leaving this resource available for other uses. This is useful specially when our program serves a lot of static pages, thus consuming a lot of RAM if not placed in the FLASH.
To start the code, we will write all the needed library includes. We will also declare as global variables the credentials needed for connecting to the WiFi network.
#include <WiFi.h> #include <FS.h> #include <AsyncTCP.h> #include <ESPAsyncWebServer.h> const char* ssid = "yourNetworkSSID"; const char* password = "yourNetworkPass";
Next we will declare an object of class AsyncWebServer, which we will use to setup the server. Note that as input of the constructor we need to pass the port where the server will be listening for requests.
AsyncWebServer server(80);
To finalize the global declarations, we will create a variable in the PROGMEM that will contain the HTML code we have prepared.
Update: As explained in this blog post, in the ESP32 constant data is automatically stored in FLASH memory and can be accessed directly from FLASH memory without previously copying it to RAM. So, there is no need to use the PROGMEM keyword below and it is only defined due to compatibility with other platforms. You can check the PROGMEM define on this file. This forum post also contains more information about this subject. Thanks to MOAM Industries and Russell P Hintze for pointing this. The PROGMEM keyword was removed from the final code below, but you can test with it to confirm that it is indeed defined and doesn’t cause any compilation problem.
const char HTML[]<label class=\"label\">Network Name</label><input type=\"text\" name=\"ssid\"/><br/><label>Password</label><input type=\"text\" name=\"pass\"/><br/><input type=\"submit\" value=\"Submit\"></form>";
Moving on to the setup function, we will start by opening a serial connection and then connect the ESP32 to the WiFi network. You can check in more detail here how to connect the ESP32 to a WiFi network.
Serial.begin(115200); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(1000); Serial.println("Connecting to WiFi.."); } Serial.println(WiFi.localIP());
After the connection to the WiFi network, we will take care of the webserver setup. So, we will need to bind a server route to a handling function that will return the HTML we defined when a client makes a request. We will use the “/html” route.
If you need a more detailed explanation on the functions signatures and how the binding works, please consult this previous post.
server.on("/html", HTTP_GET, [](AsyncWebServerRequest *request){ request->send(200, "text/html", HTML); });
Note that we are specifying the return content-type as “text/html” so the client (in our case it will be a web browser) knows that it must interpret the received content as such.
Also, take in consideration that the last parameter of the send function is the content that we are actually returning to the client and, in our case, it is the HTML variable we defined early.
Now that we have handled the configurations of the server, we simply need to call the begin function on the server object, so it starts listening to incoming HTTP requests. Since the server works asynchronously, we don’t need to perform any call on the main loop, which may be left empty.
You can check the full source code below.
#include <WiFi.h> #include <FS.h> #include <AsyncTCP.h> #include <ESPAsyncWebServer.h> const char*<label class=\"label\">Network Name</label><input type=\"text\" name=\"ssid\"/><br/><label>Password</label><input type=\"text\" name=\"pass\"/><br/><input type=\"submit\" value=\"Submit\"></form>"; void setup(){ Serial.begin(115200); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(1000); Serial.println("Connecting to WiFi.."); } Serial.println(WiFi.localIP()); server.on("/html", HTTP_GET, [](AsyncWebServerRequest *request){ request->send(200, "text/html", HTML); }); server.begin(); } void loop(){ }
Testing the code
To test the code, you simply need to compile it and upload it to your device using the Arduino IDE. Once it is ready, just open the serial monitor and wait for the connection to the WiFi network.
When it finishes, the local IP of the ESP32 on your Wireless network should get printed to the serial monitor. Copy that IP, since we will need it to connect to the server.
Then, open a web browser of you choice and write the following URL on the address bar, changing {yourEspIp} by the IP you have just obtained.
You should get an output similar to figure 3, which shows the HTML page being served and rendered by the browser.
Figure 3 – HTML form rendered in the browser.
Related posts
22 thoughts on “ESP32 Arduino async HTTP server: Serving a HTML page from FLASH memory”
Pingback: ESP32 Async HTTP web server: websockets introduction | techtutorialsx
Pingback: ESP32 Async HTTP web server: websockets introduction | techtutorialsx
Pingback: ESP32 Arduino web server: Receiving data from JavaScript websocket client – techtutorialsx
Pingback: ESP32 Arduino web server: Receiving data from JavaScript websocket client – techtutorialsx | https://techtutorialsx.com/2017/12/16/esp32-arduino-async-http-server-serving-a-html-page-from-flash-memory/ | CC-MAIN-2022-33 | en | refinedweb |
Data-Intensive Text Processing with MapReduce Jimmy LinThe iSchool University of Maryland Chris Dyer* Department of Linguistics University of Maryland *Presenting Tuesday, June 1, 2010 This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 United StatesSee for details
(Banko and Brill, ACL 2001) (Brants et al., EMNLP 2007) No data like more data!
cheap commodity clusters + simple, distributed programming models = data-intensive computing for the masses!
Outline of Part I • Why is this different? • Introduction to MapReduce (Chapters 2) • MapReduce “killer app” #1 (Chapter 4) Inverted indexing • MapReduce “killer app” #2: (Chapter 5)Graph algorithms and PageRank
Outline of Part II • MapReduce algorithm design • Managing dependencies • Computing term co-occurrence statistics • Case study: statistical machine translation • Iterative algorithms in MapReduce • Expectation maximization • Gradient descent methods • Alternatives to MapReduce • What’s next?
Divide and Conquer “Work” Partition w1 w2 w3 “worker” “worker” “worker” r1 r2 r3 Combine “Result”
It’s a bit more complex… Fundamental issues Different programming models scheduling, data distribution, synchronization, inter-process communication, robustness, fault tolerance, … Message Passing Shared Memory Memory Architectural issues P1 P2 P3 P4 P5 P1 P2 P3 P4 P5 Flynn’s taxonomy (SIMD, MIMD, etc.),network typology, bisection bandwidthUMA vs. NUMA, cache coherence Different programming constructs mutexes, conditional variables, barriers, … masters/slaves, producers/consumers, work queues, … Common problems livelock, deadlock, data starvation, priority inversion… dining philosophers, sleeping barbers, cigarette smokers, … The reality: programmer shoulders the burden of managing concurrency…
Source: Ricardo Guimarães Herrmann
Source: MIT Open Courseware
Source: MIT Open Courseware
Typical Problem • Iterate over a large number of records • Extract something of interest from each • Shuffle and sort intermediate results • Aggregate intermediate results • Generate final output Map Reduce Key idea:functional abstraction for these two operations
Map Map f f f f f Fold Reduce g g g g g
MapReduce • Programmers specify two functions: map (k, v) → <k’, v’>* reduce (k’, v’) → <k’, v’>* • All values with the same key are reduced together • Usually, programmers also specify: partition (k’, number of partitions ) → partition for k’ • Often a simple hash of the key, e.g. hash(k’) mod n • Allows reduce operations for different keys in parallel combine(k’,v’) → <k’,v’> • “Mini-reducers” that run in memory after the map phase • Optimizes to reduce network traffic & disk writes • Implementations: • Google has a proprietary implementation in C++ • Hadoop is an open source implementation in Java
k1 v1 k2 v2 k3 v3 k4 v4 k5 v5 k6 v6 map map map map a 1 b 2 c 3 c 6 a 5 c 2 b 7 c 9 Shuffle and Sort: aggregate values by keys a 1 5 b 2 7 c 2 3 6 9 reduce reduce reduce r1 s1 r2 s2 r3 s3
MapReduce Runtime • Handles scheduling • Assigns workers to map and reduce tasks • Handles “data distribution” • Moves the process to the data • Handles synchronization • Gathers, sorts, and shuffles intermediate data • Handles faults • Detects worker failures and restarts • Everything happens on top of a distributed FS (later)
“Hello World”: Word Count Map(String input_key, String input_value): // input_key: document name // input_value: document contents for each word w in input_values: EmitIntermediate(w, "1"); Reduce(String key, Iterator intermediate_values): // key: a word, same for input and output // intermediate_values: a list of counts int result = 0; for each v in intermediate_values: result += ParseInt(v); Emit(AsString(result));
UserProgram (1) fork (1) fork (1) fork Master (2) assign map (2) assign reduce worker split 0 (6) write output file 0 worker split 1 (5) remote read (3) read split 2 (4) local write worker split 3 output file 1 split 4 worker worker Input files Map phase Intermediate files (on local disk) Reduce phase Output files Redrawn from Dean and Ghemawat (OSDI 2004)
How do we get data to the workers? SAN Compute Nodes NAS What’s the problem here?
Distributed File System • Don’t move data to workers… Move workers to the data! • Store data on the local disks for nodes in the cluster • Start up the workers on the node that has the data local • Why? • Not enough RAM to hold all the data in memory • Disk access is slow, disk throughput is good • A distributed file system is the answer • GFS (Google File System) • HDFS for Hadoop (= GFS clone)
GFS: Assumptions • Commodity hardware over “exotic” hardware • High component failure rates • Inexpensive commodity components fail all the time • “Modest” number of HUGE files • Files are write-once, mostly appended to • Perhaps concurrently • Large streaming reads over random access • High sustained throughput over low latency GFS slides adapted from material by Dean et al.
GFS: Design Decisions • Files stored as chunks • Fixed size (64MB) • Reliability through replication • Each chunk replicated across 3+ chunkservers • Single master to coordinate access, keep metadata • Simple centralized management • No data caching • Little benefit due to large data sets, streaming reads • Simplify the API • Push some of the issues onto the client
Application GFS master /foo/bar (file name, chunk index) File namespace GSF Client chunk 2ef0 (chunk handle, chunk location) Instructions to chunkserver Chunkserver state (chunk handle, byte range) GFS chunkserver GFS chunkserver chunk data Linux file system Linux file system … … Redrawn from Ghemawat et al. (SOSP 2003)
Master’s Responsibilities • Metadata storage • Namespace management/locking • Periodic communication with chunkservers • Chunk creation, replication, rebalancing • Garbage collection
MapReduce “killer app” #1: Inverted Indexing (Chapter 4)
Text Retrieval: Topics • Introduction to information retrieval (IR) • Boolean retrieval • Ranked retrieval • Inverted indexing with MapReduce
Architecture of IR Systems Documents Query online offline Representation Function Representation Function Query Representation Document Representation Index Comparison Function Hits
How do we represent text? • “Bag of words” • Treat all the words in a document as index terms for that document • Assign a weight to each term based on “importance” • Disregard order, structure, meaning, etc. of the words • Simple, yet effective! • Assumptions • Term occurrence is independent • Document relevance is independent • “Words” are well-defined
What’s a word? 天主教教宗若望保祿二世因感冒再度住進醫院。這是他今年第二度因同樣的病因住院。 وقال مارك ريجيف - الناطق باسم الخارجية الإسرائيلية - إن شارون قبل الدعوة وسيقوم للمرة الأولى بزيارة تونس، التي كانت لفترة طويلة المقر الرسمي لمنظمة التحرير الفلسطينية بعد خروجها من لبنان عام 1982. Выступая в Мещанском суде Москвы экс-глава ЮКОСа заявил не совершал ничего противозаконного, в чем обвиняет его генпрокуратура России. भारत सरकार ने आर्थिक सर्वेक्षण में वित्तीय वर्ष 2005-06 में सात फ़ीसदी विकास दर हासिल करने का आकलन किया है और कर सुधार पर ज़ोर दिया है 日米連合で台頭中国に対処…アーミテージ前副長官提言 조재영 기자= 서울시는 25일 이명박 시장이 설안에 대해 `군대라도 동원해 막고싶은 심정''이라고 말했다는 일부 언론의 보도를 부인했다.
McDonald's slims down spuds Fast-food chain to reduce certain types of fat in its french fries with new cooking oil. NEW. … 16 × said 14 × McDonalds 12 × fat 11 × fries 8 × new 6 × company, french, nutrition 5 × food, oil, percent, reduce, taste, Tuesday … Sample Document “Bag of Words”
Boolean Retrieval • Users express queries as a Boolean expression • AND, OR, NOT • Can be arbitrarily nested • Retrieval is based on the notion of sets • Any given query divides the collection into two sets: retrieved, not-retrieved • Pure Boolean systems do not define an ordering of the results
aid 0 1 all 0 1 back 1 0 brown 1 0 come 0 1 dog 1 0 fox 1 0 good 0 1 jump 1 0 lazy 1 0 men 0 1 now 0 1 over 1 0 party 0 1 quick 1 0 their 0 1 time 0 1 Representing Documents Document 1 Term Document 1 Document 2 The quick brown fox jumped over the lazy dog’s back. Stopword List for is of Document 2 the to Now is the time for all good men to come to the aid of their party.
Term Doc 2 Doc 3 Doc 4 Doc 1 Doc 5 Doc 6 Doc 7 Doc 8 aid 0 0 0 1 0 0 0 1 all 0 1 0 1 0 1 0 0 back 1 0 1 0 0 0 1 0 brown 1 0 1 0 1 0 1 0 come 0 1 0 1 0 1 0 1 dog 0 0 1 0 1 0 0 0 fox 0 0 1 0 1 0 1 0 good 0 1 0 1 0 1 0 1 jump 0 0 1 0 0 0 0 0 lazy 1 0 1 0 1 0 1 0 men 0 1 0 1 0 0 0 1 now 0 1 0 0 0 1 0 1 over 1 0 1 0 1 0 1 1 party 0 0 0 0 0 1 0 1 quick 1 0 1 0 0 0 0 0 their 1 0 0 0 1 0 1 0 time 0 1 0 1 0 1 0 0 Inverted Index Term Postings aid 4 8 all 2 4 6 back 1 3 7 brown 1 3 5 7 come 2 4 6 8 dog 3 5 fox 3 5 7 good 2 4 6 8 jump 3 lazy 1 3 5 7 men 2 4 8 now 2 6 8 over 1 3 5 7 8 party 6 8 quick 1 3 their 1 5 7 time 2 4 6
Boolean Retrieval • To execute a Boolean query: • Build query syntax tree • For each clause, look up postings • Traverse postings and apply Boolean operator • Efficiency analysis • Postings traversal is linear (assuming sorted postings) • Start with shortest posting first AND ( fox or dog ) and quick quick OR fox dog dog 3 5 fox 3 5 7 dog 3 5 OR = union 3 5 7 fox 3 5 7
Extensions • Implementing proximity operators • Store word offset in postings • Handling term variations • Stem words: love, loving, loves … lov
Ranked Retrieval • Order documents by how likely they are to be relevant to the information need • Estimate relevance(q, di) • Sort documents by relevance • Display sorted results
Ranked Retrieval • Order documents by how likely they are to be relevant to the information need • Estimate relevance(q, di) • Sort documents by relevance • Display sorted results • Vector space model (leave aside LM’s for now) • Document →weighted feature vector • Query→weightedeature vector
Vector Space Model t3 d2 d3 d1 θ φ t1 d5 t2 d4 Assumption: Documents that are “close together” in vector space “talk about” the same things Therefore, retrieve documents based on how close the document is to the query (i.e., similarity ~ “closeness”)
Similarity Metric • How about |d1 – d2|? • Instead of Euclidean distance, use “angle” between the vectors • It all boils down to the inner product (dot product) of vectors di • q cos(θ) = ---------- |di| |q|
Term Weighting • Term weights consist of two components • Local: how important is the term in this document? • Global: how important is the term in the collection? • Here’s the intuition: • Terms that appear often in a document should get high weights • Terms that appear in many documents should get low weights • How do we capture this mathematically? • Term frequency (local) • Inverse document frequency (global)
TF.IDF Term Weighting weight assigned to term i in document j number of occurrence of term i in document j number of documents in entire collection number of documents with term i
TF.IDF Example tf idf 1 2 3 4 0.301 0.301 4,2 complicated 5 2 complicated 3,5 0.125 0.125 contaminated 4 1 3 contaminated 1,4 2,1 3,3 0.125 0.125 4,3 fallout 5 4 3 fallout 1,5 3,4 0.000 0.000 3,3 4,2 information 6 3 3 2 information 1,6 2,3 0.602 0.602 interesting 1 interesting 2,1 0.301 0.301 3,7 nuclear 3 7 nuclear 1,3 0.125 0.125 4,4 retrieval 6 1 4 retrieval 2,6 3,1 0.602 0.602 siberia 2 siberia 1,2
Sketch: Scoring Algorithm • Initialize accumulators to hold document scores • For each query term t in the user’s query • Fetch t’s postings • For each document, scoredoc += wt,d wt,q • Apply length normalization to the scores at end • Return top N documents
MapReduce it? • The indexing problem • Must be relatively fast, but need not be real time • For Web, incremental updates are important • Crawling is a challenge itself! • The retrieval problem • Must have sub-second response • For Web, only need relatively few results
Indexing: Performance Analysis • Fundamentally, a large sorting problem • Terms usually fit in memory • Postings usually don’t • How is it done on a single machine? • How large is the inverted index? • Size of vocabulary • Size of postings
Vocabulary Size: Heaps’ Law V is vocabulary size n is corpus size (number of documents) K and are constants Typically, K is between 10 and 100, is between 0.4 and 0.6 When adding new documents, the system is likely to have seen most terms already… but the postings keep growing
Postings Size: Zipf’s Law • George Kingsley Zipf (1902-1950) observed the following relation between frequency and rank A few words occur frequently…most words occur infrequently • Zipfian distributions: • English words • Library book checkout patterns • Website popularity (almost anything on the Web) f = frequency r = rank c = constant or
MapReduce: Index Construction • Map over all documents • Emit term as key, (docid, tf) as value • Emit other information as necessary (e.g., term position) • Reduce • Trivial: each value represents a posting! • Might want to sort the postings (e.g., by docid or tf) • MapReduce does all the heavy lifting! | https://www.slideserve.com/jasia/jimmy-lin-the-ischool-university-of-maryland-powerpoint-ppt-presentation | CC-MAIN-2022-33 | en | refinedweb |
public class DelegatingExecutor extends Object implements org.springframework.core.task.TaskExecutor
In addition to the delegate, the async configuration properties and the task name is stored, so we know which task this executor is for and we are able to determine the timeout.
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
public DelegatingExecutor(org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor delegate, ExecutorConfigurationProperties executorConfigurationProperties, String taskName)
delegate- the delegate
executorConfigurationProperties- the configuration properties
taskName- the task name
public void execute(Runnable task)
Configures a
SharedTaskContextHolder before delegating execution.
executein interface
Executor
executein interface
org.springframework.core.task.TaskExecutor
public ExecutorStatisticsView getExecutorStatistics() | http://www.hawaiiframework.org/docs/2.0.0.M10/api/org/hawaiiframework/async/DelegatingExecutor.html | CC-MAIN-2022-33 | en | refinedweb |
C
Architectural Considerations
The Qt Safe Renderer runtime component is designed to be integrated into a system that has separate processes for safety-critical and non-safety functionality. This topic describes essential architectural aspects in the Qt Safe Renderer runtime.>/.
For more information about how to integrate the Qt Safe Renderer runtime component into your system, see Integrating Qt Safe Renderer.
Partitioning Safety-Critical Functionality
The Qt Safe Renderer runtime component has been studied for several architectural models for the underlying system. In case of all kind of underlying architectural models, Qt Safe Renderer observes the status of the main UI, that is, the UI that contains all non-safe UI elements. Errors in the main UI do not affect the rendering of safety-critical information. Instead, Qt Safe Renderer restarts the main UI after detecting errors. As the Qt Safe Renderer runtime and the main UI run on separate processes, the main UI functionality does not depend on the Qt Safe Renderer runtime.
Qt Safe Renderer receives a periodical heartbeat signal that indicates the main UI is running. If the heartbeat signal times out, Qt Safe Renderer assumes that the main UI is no longer running.
Note: The application developer must implement heartbeat handling in the application side. It is not automatically handled by the Qt Safe Renderer. For more information, see the Telltales: Rendering Safety-Critical UI example.
Qt Safe Renderer is only responsible for rendering the safe content to the screen. Non-safe content is rendered using the compositor provided by the underlying system.
Architectural Options
Software architecture for a system that combines Qt and Qt Safe Renderer breaks one CPU virtually in two. Depending on the operating system used and the level of functional safety certification that is required, this may be possible to do within the operating system itself. If it is not possible, the addition of a hypervisor can keep software in each portion isolated from one another. In either case, the goal is to certify the smaller portion for functional safety while the remaining software can be built using standard practices and existing methodologies.
Using of external monitor component makes it possible to run Qt Safe Renderer on the QM hardware. The control and monitor functionality is in separate hardware with the rendering process. The monitor verifies the rendering output based on the output CRC values and compares the results to the expected CRCs. The output monitor requires the hardware which supports the output CRC calculation.
For more information about the architectural models, see the Qt Safe Renderer architecture documentation and White Paper: Functional Safety and Qt.
Recommended Architecture
Our recommendation for the application architecture using Qt Safe Renderer is that there would be a single thread in the renderer application. The system proxy process receives the system events and controls the Qt Safe Renderer process through the event queue.
Note: When you are developing a safety-critical application, you should avoid dynamic memory allocation as the memory can potentially get corrupted. Instead, you should follow the MISRA C++ coding standard that covers the dynamic memory allocation and other safety aspects.
Messaging Interface
Qt Safe Renderer takes care of rendering the safety-critical UI in its own process. Qt Safe Renderer uses its messaging interface to communicate via a system bus with the non-safe part of the UI and the underlying system. However, the system bus communication protection is not part of the Qt Safe Renderer functionality. When you integrate Qt Safe Renderer to your own system, you must take care of the system bus communication protection yourself.
A heartbeat signal from the main UI occurs periodically. It informs Qt Safe Renderer that the non-safe partition is running. If the heartbeat signal times out, Qt Safe Renderer assumes that the non-safe partition is no longer in a known good state. If the heartbeat signal stops, the application developer needs to decide how to handle the situation. Qt Safe Renderer keeps rendering the safety-critical UI elements even if the heartbeat signal has stopped.
The main UI can request to position the safety-critical UI elements. The non-safe partition may request to place the UI elements at a certain position on a target device. Qt Safe Renderer ignores illegal position requests and throws exceptions depending on how the sanity check of the layout data has failed. An adaptation of Qt Safe Renderer can catch and ignore the illegal layouts or send error messages about them.
See Integrating Qt Safe Renderer for detailed information about the messaging interface issues that you must consider when you integrate Qt Safe Renderer into your system.
The following Qt Safe Renderer classes are related to the messaging interface:
- SafeRenderer::StateManager
- SafeRenderer::QSafeEvent and its inherited classes
Design and Implementation Constraints
Qt Safe Renderer design and implementation have the following constraints:
- As recommended in table 3 in ISO 26262 Part 6, the module structure is as small and focused as possible.
- After initialization, dynamic memory allocation is not allowed.
- The safe rendering process has only one thread.
- Whenever possible, Qt Safe Renderer follows static configuration techniques instead of dynamic configuration techniques. Thus a compile-time configuration is preferred over a run-time configuration.
- Coding follows MISRA C++ Guidelines for critical systems.
Note: The MISRA C++ guidelines are followed in the classes that are included into the
SafeRenderernamespace. The example code that is part of the Qt Safe Renderer installation does not fully follow the MISRA C++ guidelines.
Qt Safe Renderer System Requirements
To use Qt Safe Renderer, your target device system must fulfill the following requirements:
- System must support partition between the safe and non-safe functionalities.
- There must be independent rendering of safety-related graphical output.
- It must be possible to concurrently render safe and non-safe graphical output.
Available under certain Qt licenses.
Find out more. | https://doc-snapshots.qt.io/qtsaferenderer/qtsr-architecture.html | CC-MAIN-2022-33 | en | refinedweb |
current position:Home>Vue error prone summary
Vue error prone summary
2022-04-29 18:07:11【Shu Rong】
Vue Error prone summary
echarts download
cnpm install [email protected] [email protected] --save
introduce
import * as echarts from 'echarts' Vue.prototype.$echarts=echarts
Use... On the page , Make sure to put mounted In the function
<template> <div> <div id="main1" style="width: 600px;height:400px;"></div> </div> </template> <script> export default { data() { return { } }, mounted() { // Based on the prepared dom, initialization echarts example let myChart = this.$echarts.init(document.getElementById("main1")) // Specify configuration items and data for the chart myChart.setOption({ title: { text: ' contact ', }, tooltip: { }, xAxis: { data: [' One ', ' Two ', ' 3、 ... and ', ' Four ', ' 5、 ... and ', ' 6、 ... and '] }, yAxis: { }, series: [{ name: ' The number of ', type: 'bar', data: [45, 46, 56, 34, 47, 48] }] }) }, } </script>
When setting the background of the picture, use
background: url(../assets/index_background.PNG) no-repeat; background-size:100% 100%;
background-image There is no effect
css Make good use of the layout display!!!
author[Shu R | https://en.qdmana.com/2022/119/202204291807083509.html | CC-MAIN-2022-33 | en | refinedweb |
Introduction
NumPy (Numerical Python) is an open-source library for the Python programming language. It is used for scientific computing and working with arrays.
Apart from its multidimensional array object, it also provides high-level functioning tools for working with arrays.
In this tutorial, you will learn how to install NumPy.
Prerequisites
- Access to a terminal window/command line
- A user account with sudo privileges
- Python installed on your system
Installing NumPy
You can follow the steps outlined below and use the commands on most Linux, Mac, or Windows systems. Any irregularities in commands are noted along with instructions on how to modify them to your needs.
Step 1: Check Python Version
Before you can install NumPy, you need to know which Python version you have. This programming language comes preinstalled on most operating systems (except Windows; you will need to install Python on Windows manually).
Most likely, you have Python 2 or Python 3 installed, or even both versions.
To check whether you have Python 2, run the command:
python -V
The output should give you a version number.
To see if you have Python 3 on your system, enter the following in the terminal window:
python3 -V
In the example below, you can see both versions of Python are present.
If these commands do not work on your system, take a look at this article on How To Check Python Version In Linux, Mac, & Windows.
Note: If you need help installing a newer version of Python, refer to one of our installation guides – How to Install Python on CentOS 8, How to Install Python 3.7 on Ubuntu, or How to Install Python 3 on Windows.
Step 2: Install Pip
The easiest way to install NumPy is by using Pip. Pip a package manager for installing and managing Python software packages.
Unlike Python, Pip does not come preinstalled on most operating systems. Therefore, you need to set up the package manager that corresponds to the version of Python you have. If you have both versions of Python, install both Pip versions as well.
The commands below use the
apt utility as we are installing on Ubuntu for the purposes of this article.
Install Pip (for Python 2) by running:
sudo apt install python-pip
If you need Pip for Python 3, use the command:
sudo apt install python3-pip
Important: Depending on the operating system you are using, follow the instructions in one of our Pip installation guides:
Finally, verify you have successfully installed Pip by typing
pip -V and/or
pip3 -V in the terminal window.
Step 3: Install NumPy
With Pip set up, you can use its command line for installing NumPy.
Install NumPy with Python 2 by typing:
pip install numpy
Pip downloads the NumPy package and notifies you it has been successfully installed.
To install NumPy with the package manager for Python 3, run:
pip3 install numpy
As this is a newer version of Python, the Numpy version also differs as you can see in the image below.
Note: The commands are the same for all operating systems except for Fedora. If you are working on this OS, the command to install NumPy with Python 3 is:
python3 -m pip install numpy.
Step 4: Verify NumPy Installation
Use the
show command to verify whether NumPy is now part of you Python packages:
pip show numpy
And for Pip3 type:
pip3 show numpy
The output should confirm you have NumPy, which version you are using, as well as where the package is stored.
Step 5: Import the NumPy Package
After installing NumPy you can import the package and set an alias for it.
To do so, move to the
python prompt by typing one of the following commands:
python
python3
Once you are in the
python or
python3 prompt you can import the new package and add an alias for it (in the example below it is
np):
import numpy as np
Upgrading NumPy
If you already have NumPy and want to upgrade to the latest version, for Pip2 use the command:
pip install --upgrade numpy
If using Pip3, run the following command:
pip3 install --upgrade numpy
Conclusion
By following this guide, you should have successfully installed NumPy on your system.
Check out our introduction tutorial on Python Pandas, an open-source Python library primarily used for data analysis, which is built on top of the NumPy package and is compatible with a wide array of existing modules. The collection of tools in the Pandas package is an essential resource for preparing, transforming, and aggregating data in Python.
For more Python package tutorials, check out our other KB articles such as Best Python IDEs and more! | https://phoenixnap.es/kb/install-numpy | CC-MAIN-2022-33 | en | refinedweb |
Introduction
If you work with a large datasets in json inside your python code, then you might want to try using 3rd party libraries like ujsonand orjson which are replacements to python’s json library.
As per their documentation
ujson (UltraJSON) is an ultra fast JSON encoder and decoder written in pure C with bindings for Python 3.7+.
orjson is a fast, correct JSON library for Python. It is the fastest python library for json encoding & decoding. It serializes dataclass, datetime, numpy, and UUID instances natively.
Benchmarking
I did a basic benchmark comparing json, ujson and orjson. The benchmarking results were interesting.
import time import json import orjson import ujson def benchmark(name, dumps, loads): start = time.time() for i in range(3000000): result = dumps(m) loads(result) print(name, time.time() - start) if __name__ == " __main__": m = { "timestamp": 1556283673.1523004, "task_uuid": "0ed1a1c3-050c-4fb9-9426-a7e72d0acfc7", "task_level": [1, 2, 1], "action_status": "started", "action_type": "main", "key": "value", "another_key": 123, "and_another": ["a", "b"], } benchmark("Python", json.dumps, json.loads) benchmark("ujson", ujson.dumps, ujson.loads) # orjson only outputs bytes, but often we need unicode: benchmark("orjson", lambda s: str(orjson.dumps(s), "utf-8"), orjson.loads) # OUTPUT: # Python 12.502133846282959 # ujson 4.428200960159302 # orjson 2.3136467933654785
ujson is 3 times faster than the standard json library
orjson is over 6 times faster than the standard json library
Conclusion
For most cases, you would want to go with python’s standard json library which removes dependencies on other libraries. On other hand you could try out ujsonwhich is simple replacement for python’s json library. If you want more speed and also want dataclass, datetime, numpy, and UUID instances and you are ready to deal with more complex code, then you can try your hands on orjson
Discussion (0) | https://practicaldev-herokuapp-com.global.ssl.fastly.net/dollardhingra/benchmarking-python-json-serializers-json-vs-ujson-vs-orjson-1o16 | CC-MAIN-2022-33 | en | refinedweb |
; which are not allowing me to authenticate properly. I have compiled, S3App, S3Authorized, S3Bucket, and S3Object, successfully. Please might someone shed some light on what I am doing wrong? I tried the following work around. I created an account at AWS. When doing so, I was assigned an Access Key ID and a Secret Access Key. I updated the code's original PUBLIC_KEY value by replacing it with the value of my AWS_Access_Key_ID and PRIVATE_KEY with my AWS_Secret_Access_Key value. The work around failed. I figured this was a long shot and would probably fail; because I was assuming the AWS_Secret_Access_Key is suppose to be used to create signatures for requests made to retrieve S3 content. However, I could have misunderstood the intent of an AWS_Secret_Access_Key and how to use it properly. I have attached all the java code. Cheers and thanks for reading, woodHack/* * java.util.ArrayList; import java.util.List; import org.restlet.data.Response; import org.restlet.resource.DomRepresentation; import org.w3c.dom.Node; /** * Amazon S3 client application. Returns a list of buckets. * * @author Jerome Louvel (cont...@noelios.com) */ public class S3App extends S3Authorized { public static void main(String... args) { for (S3Bucket bucket : new S3App().getBuckets()) { System.out.println(bucket.getName() + : + bucket.getUri()); } } public ListS3Bucket getBuckets() { ListS3Bucket result = new ArrayListS3Bucket(); // Fetch a resource: an XML document with our list of buckets Response response = authorizedGet(HOST); DomRepresentation document = response.getEntityAsDom(); // Use XPath to find the bucket names for (Node node : document.getNodes(//Bucket/Name)) { result.add(new S3Bucket(node.getTextContent())); } return result; } } /* * org.restlet.Client; import org.restlet.data.ChallengeResponse; import org.restlet.data.ChallengeScheme; import org.restlet.data.Method; import org.restlet.data.Protocol; import org.restlet.data.Request; import org.restlet.data.Response; import org.restlet.resource.Representation; /** * Amazon S3 client. Support class handling authorized requests. * * @author Jerome Louvel (cont...@noelios.com) */ public class S3Authorized {; public final static String HOST =;; private static Response handleAuthorized(Method method, String uri, Representation entity) { // Send an authenticated request Request request = new Request(method, HOST, entity); request.setChallengeResponse(new ChallengeResponse( ChallengeScheme.HTTP_AWS, PUBLIC_KEY, PRIVATE_KEY)); return new could use the 2.0 SVN snapshots, but an official release would provide a better impression. It would be great if you can provide a rough time line so I can estimate if I should switch back to 1.x or support both Restlet versions or wait for the next milestone. [1] Thanks in advance, Lars -- -- represent(Variant variant) method in the resource class always picks up JSON as the type.. Thanks public HelloWorldResource(Context context, Request request, Response response) { super(context, request, response); getVariants().add(new Variant(MediaType.APPLICATION_EXCEL)); getVariants().add(new Variant(MediaType.APPLICATION_JSON)); } Hi Sherif, .js is javascript .json is json :0) There is no need to add js or json to the MetadataService as it comes with a bunch of common ones already. Remove that line, and try (Notice the JSON) Jon Sherif wrote: Thanks Jonathan.. 1. Here’s what I did to support lets say “.js” as an extension to indicate JSON as the content type *); *this*.getTunnelService().setExtensionsTunnel(*true*); *this*.getTunnelService().setEncodingParameter(output); *this*.getMetadataService().addExtension(js, *new* Metadata(MediaType./APPLICATION_JSON/.getName(), MediaType./APPLICATION_JSON/.getDescription()), *true* ); *return* router; } } *public* *class* HelloWorldResource *extends* Resource { *public* HelloWorldResource(Context context, Request request, Response response) { *super*(context, request, response); // This representation has only one type of representation. getVariants().add(*new* Variant(MediaType./TEXT_PLAIN/)); getVariants().add(*new* Variant(MediaType./APPLICATION_JSON/)); } /** * Returns a full representation for a given variant. */ @Override *public* Representation represent(Variant variant) *throws* ResourceException { Representation representation = *null*; *if*(variant.getMediaType() == MediaType./APPLICATION_JSON/){ representation = *new* JsonRepresentation(Hello World); }*else* *if* ( variant.getMediaType() == MediaType./TEXT_PLAIN/){ representation = *new* StringRepresentation( hello, world, MediaType./TEXT_PLAIN/); } *return* representation; } } However when I call the service using the following URL the Variant type in the HelloWorldResource is of MediaType.TEXT_PLAIN Thanks for Your help *From:* Jonathan Hall (via Nabble) [mailto:ml-user+125526-1692215...@...] *Sent:* Friday, June 05, 2009 1:29 PM *To:* Sherif *Subject:* Re: Multiple content types Have a look at getTunnelService().setExtensionsTunnel(true); Jon Sherif wrote: I realize RESTLet supports multiple encodings based on the Accept Encoding headers. Does Restlet also have a way to allow encodings based on URI patter e.g. or something like that ? -- This email is a reply to your post @ You can reply by email or by visting the link above. View this message in context: RE: Multiple content types Sent from the Restlet Discuss mailing list archive at Nabble.com. -- taane...@aticonsulting.com On Mon, Jun 29, 2009 at 2:57 AM, Jerome Louvel jerome.lou...@noelios.comwrote: Hi Timothy, Were you able to make progress on this front? Best regards, Jerome Louvel -- Restlet ~ Founder and Lead developer ~ Noelios Technologies ~ Co-founder ~ *De :* Timothy Aanerud [mailto:taanerudATaticonsulting.comtata. -- 62 -- -- -- | https://www.mail-archive.com/search?l=discuss%40restlet.tigris.org&q=date%3A20090701&a=1&o=newest&f=1 | CC-MAIN-2022-33 | en | refinedweb |
Hmm that’s strange. I’ll have a look. Also, please know, that multibus fixes are in the works so you’ll soon be able to update.
These seem broken in 12.8 on Windows 10
Rail
Oh no not again… the AAX modifier key madness is really the single worst aspect about the AAX SDK. I’ll investigate.
So the modifier keys still seem to work for me in 12.8. You are talking about the focus issue, right?
If it’s the focus issue that you are talking about: are you sure that non-JUCE plug-ins can correctly register the modifier keys when clicking on them when they are not focused? JUCE is correctly calling
AAX_IViewContainer::GetModifiers but it simply returns zero on the first click.
No, I have a custom ComboBox in my plug-in and in the parent component:
void COutputComponent::comboBoxChanged (ComboBox* comboBoxThatHasChanged) { if (comboBoxThatHasChanged == m_pOutputMenu) { ModifierKeys mods = ModifierKeys::getCurrentModifiers(); : if (mods.isAltDown()) { // In PT 12.8 on Windows 10 I'm not getting here CPlayerAudioProcessor* pProcessor = m_pParent->getAudioProcessor(); if (pProcessor != nullptr) pProcessor->setAllOutputs (m_szOutput); } : } }
I debugged and on mouse move when you check the modifiers it’s not picking up the Alt key reliably… I’ll keep digging. (The VST works fine on the same system).
Thanks,
Rail
OK I’m really stumped on this one: in doesn’t seem to be specific to AAX. If you run the standalone version of the plug-in, I get the same result on Windows. The modifiers are not picked up correctly in mouseMove events.
In JUCE the modifiers only get updated when the system sends us key down and key up events. However, since some change in Windows 10, the key down event (
WM_KEYDOWN) for modifiers is only sent once the modifier is released (?!?). It is then immediately followed by a key up event. For some reason, when running the plug-in as a VST, everything seems to work correctly.
Has anybody seen this before and can point me to some workaround. It turns out that it’s also really hard to google.
Hi Fabian,
I’m just putting out another fire related to Waves plug-ins… I had to modify the JUCE VST scanner code to deal with a single (out-dated) WaveShell bundle crashing causing all the rest of the Waves plug-ins to be ignored… but that’s another issue and I’m almost done with the patch.
I’ll look into this later today.
Thanks for looking into it.
Rail
So I took the Plug-in demo and added a ComboBox to it and it’s detecting the Alt key and other mod combos I use okay in the comboBoxChanged() callback in Standalone.
I see the same behavior as you do where the system only send the plug-in the ALT key on key up… but if you click a mouse button while you have a modifier depressed… then it works… which is fine for my use.
I’ll now try and build the demo as an AAX and test it.
The answer to the Key Down issue may be answered using LowLevelKeyboardProc ?
Thanks,
Rail
So in the AAX using
ModifierKeys::getCurrentModifiers()
in the comboBoxChanged() callback doesn’t work… but if I check the mods in the actual ComboBox derived class’ mouseDown() and mouseUp() using the MouseEvent mods variable the mod state is correct… so I’ve just created a few boolean class variables to get the mods’ state(s) in the comboBoxChanged() and that’s working on all platforms.
Thanks,
Rail
So I did a comparison between my plug-in and Waves C6 and the stock PT EQ…
The non-JUCE plug-ins respond immediately to an Alt+click, where with my plug-in I have to Alt+click twice (once to get focus and then to reset).
Rail
I?
I don’t have any issue with the Alt modifier in mouseDown()… but you can use the AAX function GetModifiers()… I use it to get the Start modifier:
void EQNode::mouseDown (const MouseEvent& e) { bool bIsCtrlDown = e.mods.isCtrlDown(); bool bIsCommandDown = e.mods.isCommandDown(); #if JUCE_WINDOWS if (m_ViewContainer != nullptr) { uint32_t mods = 0; m_ViewContainer->GetModifiers (&mods); bIsCtrlDown = (mods & AAX_eModifiers_WINKEY) != 0; } #endif if (e.mods.isAltDown() && ! bIsCtrlDown && ! e.mods.isShiftDown() && ! bIsCommandDown) { resetToDefault(); return; } : }
It depends where you’re testing though… as I mentioned earlier – in a ComboBox derived class I had to do some kludge work.
Rail
Rail, Thanks a lot for the response. In the meantime I found that getting the modifiers in MouseMoved is definitely broken, while it does work in MouseDown and MouseUp. That’s why I sometimes got a quick correct value when reading the modifiers supplied to the mouse callbacks.
I think there is a bug in the juce code. In juce_win32_Windowing.cpp in the doMouseMove method. The modifiers are fetched from the AAX wrapper in line 2561 and written to ModifierKeys::currentModifiers, but then in the doMouseEvent call the old value is sent which doesn’t get the information from the AAX call.
So I switched to using ModifierKeys::currentModifiers directly inside the mouse callbacks, but it’s also not working in MouseMoved - at least this way I can retain the last value. Maybe ProTools does not update Modifiers unless click events happen.
ModifierKeys::getCurrentModifiersRealtime() appears to always use getAsyncKeyState() which means it does not work right inside an AAX plugin.
Rail, how do you get the m_ViewContainer inside your Component?
Well the code snippet is from a DSP AAX plugin… so I have more access directly to the API… but check out the JUCE AAX wrapper method: getWin32Modifiers()
Have you checked out: Win/PT modifier fixes in JUCE 4.1
Rail
Thanks for linking to the other thread I hadn’t seen yet. The fix presented there does help a bit, but things aren’t working 100% yet.
It seems that during mouse move, other events reset the modifier state. I see now that the AAX SDK’s GetModifier() call works correctly, but unfortunately the current AAX wrapper implementation in juce is incomplete and only works reliably for mouseDown and mouseUp events. My best guess is that some events still poll GetAsyncKeyState() and then reset the modifier state.
I’ll now try to get access to the AAX_IViewContainer* to call it directly in my client code, but it’s tricky as the juce wrappers abstracts things away and debugging in Pro Tools is no joy.
I have tried many things getting the modifiers to work right in MouseMove, but even to get things half-working requires massive changes to both the AAX Wrapper and juce_win32_windowing and now I’ve given up on it.
What makes fixing the issue tricky is the way AAX modifiers have been patched in on top of the existing code. The non-aax code expects modifiers to be system-global and uses static methods, while in AAX modifiers are per plugin editor and have to be queried from the AAX owner. Right now, modifiers are overwritten for mouseDown and mouseUp, but other spots overwrite the state with bad information because inside PT getAsyncKeyState() always returns non-pressed for the Alt key.
Hopefully in the future someone can pick this up and find a real solution, but I’ve spent more than a day on it and now just use a different key instead of Alt.
So here’s the thing… I just added the Pro Tools automation menu for a client’s Native plugin… and I’d guess about 70% of the time on Windows the Start modifier is detected… so I looked into doing a hack… which I got to work… but the results are that even the AAX GetModifiers() is unreliable…
I had to modify the JUCE JUCE_AAX_Modifier_Injector.h
namespace juce { #ifndef DOXYGEN struct ModifierKeyProvider { virtual ~ModifierKeyProvider() {} virtual int getWin32Modifiers() const = 0; virtual uint32 getWin32AAXModifiers() const = 0; }; struct ModifierKeyReceiver { virtual ~ModifierKeyReceiver() {} virtual void setModifierKeyProvider (ModifierKeyProvider*) = 0; virtual void removeModifierKeyProvider() = 0; virtual ModifierKeyProvider* getModifierKeyProvider() = 0; }; #endif } // namespace juce
In the AAX Wrapper after int getWin32Modifiers() add:
uint32 getWin32AAXModifiers() const override { uint32 aaxViewMods = 0; if (auto* viewContainer = GetViewContainer()) { const_cast<AAX_IViewContainer*> (viewContainer)->GetModifiers (&aaxViewMods); } return aaxViewMods; }
and in JUCE_Win32_Windowing add:
ModifierKeyProvider* getModifierKeyProvider() override { return modProvider; }
So my code:
#include <juce_audio_plugin_client/AAX/juce_AAX_Modifier_Injector.h> #include <AAX_Enums.h> void MySlider::mouseDown (const MouseEvent& e) { Slider::mouseDown (e); #if JUCE_WINDOWS #if JUCE_MODULE_AVAILABLE_juce_audio_plugin_client PluginHostType host; if (host.isProTools()) { ModifierKeyProvider* modProvider = nullptr; Component* pComponent = getParentComponent(); // The Editor if (pComponent != nullptr) pComponent = pComponent->getParentComponent(); // The ContentWrapperComponent if (pComponent != nullptr) { if (ModifierKeyReceiver* modReceiver = dynamic_cast<ModifierKeyReceiver*> (pComponent->getPeer())) modProvider = modReceiver->getModifierKeyProvider(); if (modProvider != nullptr) { uint32_t mods = modProvider->getWin32AAXModifiers(); bool bIsWinKeyDown = (mods & AAX_eModifiers_WINKEY) != 0; bool bIsControlKeyDown = (mods & AAX_eModifiers_Cntl) != 0; bool bIsAltKeyDown = (mods & AAX_eModifiers_Alt) != 0; if (bIsWinKeyDown) DBG ("WIN KEY DOWN"); if (bIsControlKeyDown) DBG ("CTRL KEY DOWN"); if (bIsAltKeyDown) DBG ("ALT KEY DOWN"); } } } #endif // JUCE_MODULE_AVAILABLE_juce_audio_plugin_client #endif // JUCE_WINDOWS : }
Shows about the same ability to detect the Automation keystrokes (CTRL+ALT+START) as before I did the hack
Hrmph
This will detect the ALT and CTRL 100% of the time though
Rail
Thanks for putting in the work I chose not to do. I haven’t tried your solution yet, but it looks very promising and it would be nice if the JUCE library could include it, so ctrl and alt would become reliable in AAX. I think the START/WINDOWS key is not a good key to use for anything in a plugin as Windows itself might interfere. I consider it reserved by Windows and not a modifier key. | https://forum.juce.com/t/aax-getmodifiers-12-5-win/17795/25 | CC-MAIN-2022-33 | en | refinedweb |
Today, in the fan exchange group, a classmate said he found it
RequestsAnd fixed it:
The corresponding pictures in the chat record are:
Seeing the screenshot of this classmate, I probably know what problems he encountered and why he mistakenly thought it was a requests bug.
To explain this problem, we need to understand one problem first, that is, the two display forms of JSON strings and
json.dumpsof
ensure_asciiParameters.
Suppose we have a dictionary in Python:
Info = {'name': 'Qingnan', 'age': 20}
When we want to convert it into JSON string, we may write code like this:
import json Info = {'name': 'Qingnan', 'age': 20} info_str = json.dumps(info) print(info_str)
The operation effect is shown in the figure below, and Chinese is changed into Unicode code:
We can also add a parameter
ensure_ascii=False, let Chinese display normally:
info_str = json.dumps(info, ensure_ascii=False)
The operation effect is shown in the figure below:
The classmate believes that due to
{"name": "\u9752\u5357", "age": 20}and
{"name": "Qingnan", "age": 20}From the perspective of string, it is obviously not equal. When requests sends data through post, it does not have this parameter by default
json.dumpsFor example, omitting this parameter is equivalent to
ensure_ascii=True:
So actually
RequestsWhen post contains Chinese data, it will convert Chinese into Unicode code and send it to the server, so the server can’t get the original Chinese information at all. Therefore, it will lead to error reporting.
But in fact, this is not the case. I often tell my classmates in the group that students who are reptiles should have some basic back-end common sense so as not to be misled by this phenomenon. In order to explain why the above student’s understanding is wrong and why this is not a request bug, let’s write a post service to see if there is any difference between our post data. In order to prove that this feature has nothing to do with the network framework, I use flash, fastapi and gin to demonstrate it.
First, let’s take a look at the requests test code. Here, data in JSON format is sent in three ways:
import requests import json body = { 'name': 'Qingnan', 'age': 20 } url = '' #Send directly using JSON = resp = requests.post(url, json=body).json() print(resp) headers = { 'Content-Type': 'application/json' } #The dictionary is serialized into JSON strings in advance, and Chinese is converted into Unicode, which is equivalent to the first method resp = requests.post(url, headers=headers, data=json.dumps(body)).json() print(resp) #The dictionary is serialized into JSON strings in advance, and Chinese is reserved resp = requests.post(url, headers=headers, data=json.dumps(body, ensure_ascii=False).encode()).json() print(resp)
This test code uses three methods to send post requests, of which the first method is the self-contained method of requests
json=Parameter. The parameter value is a dictionary. Requests will automatically convert it to a JSON string. In the latter two ways, we manually convert the dictionary into JSON string in advance, and then use
data=Parameters are sent to the server. These two methods need to be specified in headers
'Content-Type': 'application/json', the server knows that the JSON string is sent.
Let’s take a look at the back-end code written by flask:
from flask import Flask, request app = Flask(__name__) @app.route('/') def index(): return {'success': True} @app.route('/test_json', methods=["POST"]) def test_json(): body = request.json MSG = f 'received post data, {body ["name"] =}, {body ["age"] =}' print(msg) return {'success': True, 'msg': msg}
The operation effect is shown in the figure below:
It can be seen that no matter which post method is used, the back end can receive the correct information.
Let’s look at the fastapi version:
from fastapi import FastAPI from pydantic import BaseModel class Body(BaseModel): name: str age: int app = FastAPI() @app.get('/') def index(): return {'success': True} @app.post('/test_json') def test_json(body: Body): MSG = f 'received post data, {body. Name =}, {body. Age =}' print(msg) return {'success': True, 'msg': msg}
The operation effect is shown in the figure below. The data sent by three kinds of post can be correctly recognized by the back end:
Let’s take a look at the back end of the gin version:
package main import ( "fmt" "net/http" "github.com/gin-gonic/gin" ) type Body struct { Name string `json:"name"` Age int16 `json:"age"` } func main() { r := gin.Default() r.GET("/", func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{ "message": "running", }) }) r.POST("/test_json", func(c *gin.Context) { json := Body{} c.BindJSON(&json) msg := fmt. Sprintf ("received post data, name =% s, age =% d", JSON. Name, JSON. Age) fmt.Println(">>>", msg) c.JSON(http.StatusOK, gin.H{ "msg": fmt. Sprintf ("received post data, name =% s, age =% d", JSON. Name, JSON. Age), }) }) r.Run() }
The operation effect is as follows. The data of the three request methods are exactly the same:
From here, we can know that whether Chinese exists in the form of Unicode code or directly in the form of Chinese characters in the JSON string submitted by post, the back-end service can correctly parse it.
Why doesn’t it matter in which form Chinese is displayed in the JSON string? This is because, for a JSON string, the programming language converts it back into an object (called
Deserialization), itself can handle them correctly. Let’s look at the following figure:
ensure_asciiParameter only controls the display style of JSON
ensure_asciiby
TrueMake sure that there are only ASCII characters in the JSON string, so all characters that are not within 128 ASCII characters will be converted. And when
ensure_asciiby
FalseThese non ASCII characters are still displayed as they are. This is like a person with or without make-up. The essence will not change. When modern programming languages deserialize them, both forms can be correctly recognized.
Therefore, if you use modern web framework to write the back end, there should be no difference between the two JSON forms. Request default
json=Parameter, equivalent to
ensure_ascii=True, any modern web framework can correctly identify the content submitted by post.
Of course, if you use C, assembly or other languages to write back-end interfaces naked, it may be different. But for people with normal IQ, who would do this?
To sum up, the problem encountered by this student is not the bug of requests, but the problem of his back-end interface itself. Maybe the back-end uses some kind of retarded web framework. The information it receives from post is a JSON string without deserialization, and the back-end programmer uses regular expressions to extract data from the JSON string. Therefore, when it is found that there is no Chinese in the JSON string, it will report an error.
In addition to the problem of sending JSON through post, I once had a subordinate who, when sending post information using scripy, couldn’t write post code, had a whim, spliced the fields sent by post into the URL, and then requested by get. It was found that data could also be obtained, similar to:
Body = {'name': 'Qingnan', 'age': 20} url = '' requests.post(url, json=body).text requests. get(' Qingnan & age = 20 ') text
So the student came to a conclusion that he thought it was a general rule that all post requests could be transferred to get requests in this way.
But obviously, this conclusion is also incorrect. This only shows that the back-end programmer of this website can make this interface compatible with two ways of submitting data at the same time, which requires the back-end programmer to write additional code. By default, get and post are two completely different request methods, and they cannot be converted in this way.
If the student knows some simple back ends, he can immediately write a back-end program to verify his conjecture.
For another example, some websites may include another URL in the URL, for example:
If you don’t have basic back-end knowledge, you may not see what’s wrong with the above website. But if you have some basic back-end knowledge, you may ask a question: what is in the website
&db=admin, belongs to parameter of, with
url=Level; Still belong to? You will be confused, and so will the backend. That’s why we need URLEncode at this time. After all, the following two writing methods are completely different:
Finally, I will summarize with a sentence in the preface of my reptile book:
Reptile is a chore. If you only know reptile, you can’t learn reptile well.
| https://developpaper.com/why-should-crawler-engineers-have-some-basic-back-end-common-sense/ | CC-MAIN-2022-33 | en | refinedweb |
Compiler sanitizers¶
Sanitizers are tools that can detect bugs such as buffer overflows or accesses, dangling pointer or different types of undefined behavior.
The two compilers that mainly support sanitizing options are gcc and clang. These options are passed to the compiler as flags and, depending on if you are using clang or gcc, different sanitizers are supported.
Here we explain different options on how to model and use sanitizers with your Conan packages.
Adding custom settings¶
If you want to model the sanitizer options so that the package id is affected by them, you have to introduce new settings in the settings.yml file (see Customizing settings section for more information).
Sanitizer options should be modeled as sub-settings of the compiler. Depending on how you want to combine the sanitizers you have two choices.
Adding a list of commonly used values¶
If you have a fixed set of sanitizers or combinations of them that are the ones you usually set for your builds you can add the sanitizers as a list of values. An example for apple-clang would be like this:] sanitizer: [None, Address, Thread, Memory, UndefinedBehavior, AddressUndefinedBehavior]
Here you have modeled the use of
-fsanitize=address,
-fsanitize=thread,
-fsanitize=memory,
-fsanitize=undefined and the combination of
-fsanitize=address and
-fsanitize=undefined. Note that for example, for clang it is not possible to combine more than
one of the
-fsanitize=address,
-fsanitize=thread, and
-fsanitize=memory checkers in the
same program.
Adding thread sanitizer for a conan install, in this case, could be done by calling conan install .. -s compiler.sanitizer=Thread
Adding different values to combine¶
Another option would be to add the sanitizer values as multiple
True or
None fields so that
they can be freely combined later. An example of that for the previous sanitizer options would be as
follows:] address_sanitizer: [None, True] thread_sanitizer: [None, True] undefined_sanitizer: [None, True]
Then, you can add different sanitizers calling, for example, to conan install .. -s compiler.address_sanitizer=True -s compiler.undefined_sanitizer=True
A drawback of this approach is that not all the combinations will be valid or will make sense, but it is up to the consumer to use it correctly.
Passing the information to the compiler or build system¶
Here again, we have multiple choices to pass sanitizers information to the compiler or build system.
Using from custom profiles¶
It is possible to have different custom profiles defining the compiler sanitizer setting and environment variables to inject that information to the compiler, and then passing those profiles to Conan commands. An example of this would be a profile like:
[settings] os=Macos os_build=Macos arch=x86_64 arch_build=x86_64 compiler=apple-clang compiler.version=10.0 compiler.libcxx=libc++ build_type=Release compiler.sanitizer=Address [env] CXXFLAGS=-fsanitize=address CFLAGS=-fsanitize=address
Then calling to conan create . -pr address_sanitizer_profile would inject
-fsanitize=address to the build through the
CXXFLAGS environment variable.
Managing sanitizer settings with the build system¶
Another option is to make use of the information that is propagated to the conan generator. For example, if we are using CMake we could use the information from the CMakeLists.txt to append the flags to the compiler settings like this:
cmake_minimum_required(VERSION 3.2) project(SanitizerExample) set (CMAKE_CXX_STANDARD 11) include(${CMAKE_BINARY_DIR}/conanbuildinfo.cmake) conan_basic_setup() set(SANITIZER ${CONAN_SETTINGS_COMPILER_SANITIZER}) if(SANITIZER) if(SANITIZER MATCHES "(Address)") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fsanitize=address" ) endif() endif() add_executable(sanit_example src/main.cpp)
The sanitizer setting is propagated to CMake as the
CONAN_SETTINGS_COMPILER_SANITIZER variable
with a value equals to
"Address" and we can set the behavior in CMake depending on the value of
the variable.
Using conan Hooks to set compiler environment variables¶
Important
Take into account that the package ID doesn’t encode information about the environment, so different binaries due to different CXX_FLAGS would be considered by Conan as the same package.
If you are not interested in modelling the settings in the Conan package you can use a Hook to modify the environment variable and apply the sanitizer flags to the build. It could be something like:
def set_sanitize_address_flag(self): self._old_cxx_flags = os.environ.get("CXXFLAGS") os.environ["SOURCE_DATE_EPOCH"] = _old_flags + " -fsanitize=address" def reset_sanitize_address_flag(self): if self._old_cxx_flags is None: del os.environ["CXXFLAGS"] else: os.environ["CXXFLAGS"] = self._old_cxx_flags
And then calling those functions from a pre_build and a post_build hook: | https://docs.conan.io/en/1.25/howtos/sanitizers.html | CC-MAIN-2022-33 | en | refinedweb |
Always.
the library has never had a C++03 mode, and I am against adding one now. I want libc++ to move away from C++03, not towards it.
If (3) is present, we shouldn't pollute the global namespace, especially with a potentially bogus value. Ideally, this shouldn't be necessary at all, since overaligned new doesn't exist in C++03. But that would be a much more intrusive change to <new> and go beyond "try not to break c++03".
libc++ intentionally provides all the C++11 library functionality that it can, even when used from C++03 mode. So on the face of it, providing this name in C++03 mode seems appropriate.
However... the implementation currently used by libc++ doesn't work in that mode: the various compilers' <stddef.h>s will not provide ::max_align_t when included in C++03 mode. So either this fails to build (on NetBSD, which provides its own <stddef.h>, which I think is the issue that Joerg is reporting), or -- worse -- it silently uses the wrong definition for max_align_t by falling through to the long double fallback (which is what happens everywhere other than NetBSD). So I think we should do something here; the current approach is broken in (at least) C++03 mode.
But I think this is not the right fix. We should remove the long double fallback instead. We have no reason to think that this is correct in the cases where it's reachable (if any exist), and libc++ shouldn't be making arbitrary guesses about ABI decisions like this. Either we have the right ::max_align_t from <stddef.h> or we just can't provide one. And we should fix the defined(__NetBSD__) check to properly check for whatever conditions NetBSD defines max_align_t (maybe there's nothing better than (defined(__NetBSD__) && __cplusplus >= 201103L), but someone could look at their <stddef.h> to find out).
Ping?
Ping2?
On the assumption that we will never get a ::max_align_t in C++98 mode anyway (which will be the case if the <stdlib.h> is conforming), this looks like the best we can do to me.
Is there any ODR risk from this, or similar? Does libc++ support building in mixed C++98 / C++11 mode? If different TUs disagree on this alignment, we can end up allocating with the aligned allocator and deallocating with the unaligned allocator, which is not guaranteed to work.
We could always use the union approach if we don't know the default new alignment. But from the code below it looks like we might only ever use this if we have aligned allocation support, in which case we can just assume that the default new alignment is defined. So perhaps we can just hide the entire definition of __is_overaligned_for_new behind a #ifdef __STDCPP_DEFAULT_NEW_ALIGNMENT__ and never even consider max_align_t?
It is used both in <new> and <memory> and the use in the latter is currently unconditional AFAICT. I don't have a problem splitting the conditional to avoid the typedef. That would address the ODR concern?
max_align_t should be ABI stable. I would rather we copy/paste the clang definition into the libc++ sources so we can use it when it's not provided by the compiler.
Though this raises another can of worms because GCC and Clang don't agree on a size for max_align_t.
If we're going to go this route, we should expose the __libcpp_max_align_t definition in all dialects, and compare it's size and alignment to the real max_align_t when we have it.
max_align_t doesn't exist in C++03 mode, the included version is the nearest thing possible in portable C++. A visible difference happens if:
(1) The user requires C++03
(2) The code contains non-standard types with either explicit alignment or larger implicit alignment than the base types.
(3) STDCPP_DEFAULT_NEW_ALIGNMENT or alignof(max_align_t) is larger than the alignment of the union.
In that case, behavior changes as to which allocator/deallocator is used. If the explicit aligned version is not compatible and life-time crosses into c++11 mode, it could be a problem. But at that point I think we did all we could possible do to provide compatibility and the code is too far in implementation-defined land already.
Do not depend on max_align_t in C++03 mode in the test cases.
@ldionne Since this has the possibility of breaking existing users of std::max_align_t, can you test this against your c++03 codebases?
@joerg I still don't understand why you need this change. Why can't we provide the name in C++03 mode?
I'll repeat: libc++ does not provide a C++03 mode. Only a C++11 mode that tolerates C++03 compilers.
C++03 conformance is not a valid reason for this change.
Tests under test/libcxx can use the __libcpp_max_align_t name directly, instead of being disabled..
I should add that e.g. libstdc++ doesn't provide it either, so at least somewhat portable C++03 code can not depend on the presence anyway.
In D73245#1894420, @EricWF wrote:
@ldionne Since this has the possibility of breaking existing users of std::max_align_t, can you test this against your c++03 codebases?
I have no opinion about this patch, but I generally agree we shouldn't make efforts to provide C++03 conformance. It's a vain effort and we should be looking towards the future. On the other hand, this patch does seem to simplify the code a bit, in the sense that we now don't provide anything unless we have a conforming C++11 implementation, in which case we don't need to go through platform specific hoops anymore. I like that.
Regardless, I'm running this change on a code base to see whether it causes problems.
In D73245#1896786, @ldionne wrote:
In D73245#1894420, @EricWF wrote:
@ldionne Since this has the possibility of breaking existing users of std::max_align_t, can you test this against your c++03 codebases?
LGTM as far as that is concerned. (personal note: rdar://60008079)
Ping
I've already stated my disapproval of this patch. Libc++ has never and will never provide nor value C++03 conformance.
Moving backwards to C++03 is inconsistent with the libraries general direction..
If you would still like to proceed in this direction. Please remove me as a reviewer.
It's important these tests continue to pass in C++03..
In D73245#1918287, @ldionne wrote:.
Removing or breaking C++03 compatibility is actively harmful for that. Speaking as a system integrator, a STL implementation that can't deal in a reasonable way with the existing C++03 code base is useless. It's a nice ivory tower assumption that old code will just disappear if you wish for it enough, but it doesn't reflect well on the reality. Especially given the various ways can and does fail when compiled for C++11 or later. Having to switch between different STL implementations doesn't help anyone in the process of modernizing a code base, especially when interacting with code that needs large semi-intrusive changes to work in C++11 mode. As a most basic issue, it makes it much harder to separate issues with the STL implementation (i.e. depending on implementation-defined behavior) from semantic changes in the core language (i.e. noexcept dtors, auto) and mechanical changes (e.g. UDL).
Can you both please go back to look at the core of the issue? The current behavior of libc++ is at best an ODR violation on ALL platforms. This is not a problem specific to NetBSD at all, it has just been exposed as a different error on NetBSD. The documented behavior of libc++ is to provide C++03 compatibility as much as possible when it doesn't conflict with C++11 and the compiler (clang) supports the necessary language feature. max_align_t is not provided by clang in C++03 nor is it provided by GCC. Now there are different options for fixes, but it is very frustrating to me that the primary feedback so far is "Don't use C++03" and therefore not helpful at all. As I said before, libc++ cares about max_align_t exactly for one purpose: whether overaligned types need special allocators. Now C++03 normally can't depend on the implementation to do something useful in this case, simply because the environment doesn't have the necessary means. So it all boils down to what is the least intrusive and potentially most well testable mechanism. The core of the patch provides one answer for that. If the compiler supports telling us the default alignment for new, use it just like we would in C++11 mode. A constructive feedback would now be an answer to the question of whether we care about libc++ use with compilers that do not provide that macro for C++03 mode. I don't know how useful libc++ in C++03 mode is for any compiler except clang and as I wrote, we document the primary target being clang. As such the primary question is whether we care about compatibility with older versions of clang and modern libc++. If we don't, the change to <new> becomes much simpler as it can just bail out and the corresponding testing becomes easier as well, since it would only have to assert that max_align_t is aligned less strictly than the platform allocator. It would solve the core issue that we provide a max_align_t when we don't know what it should be and actively disagree with the max_align_t we provide for the other dialects.
So, IIUC what you're saying, __STDCPP_DEFAULT_NEW_ALIGNMENT__ is provided by recent Clangs in C++03 mode? I tested it and it does seem to be correct. (side note: I tend to think we should be more aggressive to remove old compiler support, since most people don't upgrade their stdlib without upgrading their compiler anyway).
So if we don't care about supporting old compilers that don't provide that macro, we could just get rid of this #elif, and such compilers would error out when trying to use max_align_t in the #else below. That appears reasonable to me.
We'd still leave the #if TEST_STD_VER >= 11 in the tests below, since in C++03 we wouldn't provide std::max_align_t, however testing that we use overaligned new in the same conditions in C++03 and C++11 becomes trivial, because it's the same code path.
Did I get what you meant correctly? If so, that sounds like a viable path forward to me, since we're simplifying the code. We're also improving on our C++03 conformance, which isn't considered good but is certainly not considered bad either.
Correct, it has been provided since clang 4.0 at least it seems. For testing, we have two cases, some that specifically check properties of max_align_t and those should be restricted to C++11 and newer. I think we should grow a new check that max_align_t <= STDCPP_DEFAULT_NEW_ALIGNMENT as sanity check, but that's slightly OT. Most of the existing cases to check for overalignment already use STDCPP_DEFAULT_NEW_ALIGNMENT anyway, so it would be a case-by-case check for those.
I'm fine with that direction if you're willing to update the patch. I'll review it.
Do I understand it correctly that instead of __libcpp_max_align_t (or (over)exposed max_align_t) we can rely entirely on __STDCPP_DEFAULT_NEW_ALIGNMENT__?
Yes, that is the plan IIUC..
I think the direction works, but I have questions about some thing I don't understand (mostly in the tests).
Why do we need this at all anymore? In C++11, can't we rely on the C Standard Library providing it ::max_align_t?
This test is only enabled in >= C++11, so I think std::max_align_t should always be provided. So why do we want that #if?
Since we now assume that __STDCPP_DEFAULT_NEW_ALIGNMENT__ is defined, can we remove that #if and keep the assertion?
Can you walk me through why the check for > 16 is required?
Sorry, left-over. Will be killed.
We know that the new alignment can be stricter than max_align_t and we want to test the overflow case here. So going for the strictest alignment is more sensible.
It's only required in C++03 mode. We still support C++11 and higher without it, e.g. for gcc.
If max_align_t is 256bit, we still only expect 128bit alignment (long double). This test is still checking more than it should, e.g. in principle a target could legitimately have no natural type larger than 64bit, but support 256bit vector types and set max_align_t accordingly. The condition is here because std::min in C++11 is not constexpr.
Naively, I would have expected the test to be:
#if TEST_STD_VER >= 11 // we know max_align_t is provided
static_assert(std::alignment_of<T1>::value == TEST_ALIGNOF(std::max_align_t), "");
#else
static_assert(std::alignment_of<T1>::value >= TEST_ALIGNOF(natural_alignment), "");
#endif
To make sure I understand, you're saying we can't do that because the std::alignment_of<T1>::value == TEST_ALIGNOF(std::max_align_t) test would sometimes fail if alignof(std::max_align_t) is larger than the natural alignment used by std::aligned_storage. This also highlights that there's a change in the value of alignof(std::max_align_t) with this change. Is that correct?
Yes, the test would have failed before when max_align_t > 16. There is no change of value in alignof(max_align_t), just seen by review.
ping2
Louis, did I answer your questions?
LGTM | https://reviews.llvm.org/D73245?id=245853 | CC-MAIN-2022-33 | en | refinedweb |
Events
It can often be useful to know when DataTables or one of its extensions has performed a particular operation, for example a page draw, so other dependent elements can be updated to take account of the change. To provide this ability, DataTables will fire custom DOM events which can be listened for, and then acted upon, using either the
on() method or jQuery's
on() method. DataTables's custom events work in exactly the same way as standard DOM events, and allow event driven actions, which is particularly useful for plug-ins.
For a full list of the events that DataTables and its extensions will trigger, please refer to the event reference documentation.
Listening for events
As noted above, you can use either the
on() or jQuery's
on() method to listen for events.
on() works in exactly the same way as
$().on(), with provision for namespaces and multiple events.
Please be aware that all DataTables events are triggered with the
dt namespace. This namespacing of events is to prevent clashes with custom events triggered by other Javascript libraries. As such, you should append
.dt to the name of the event(s) that you are listening for (when using
on() the namespace is automatically appended if required). Because of the way namespaces work in jQuery, you can use the
dt namespace and your own custom namespace(s) if you wish to use a namespace.
For example, to listen for the draw event in a DataTable:
var table = $('#example').DataTable(); table.on( 'draw', function () { alert( 'Table redrawn' ); } );
This could also be written as:
$('#example').on( 'draw.dt', function () { alert( 'Table redraw' ); } );
Note the use of the
dt namespace when using the jQuery
on() method, while the
on() method will automatically append the namespace for you.
Removing events
As with
$().on() DataTables events can be removed with
off() and
$().off(). It is important to remove events from objects which no longer exist (before they are destroyed) to allow the Javascript engine's garbage collector to release the memory allocated for the events and the objects it has attached to.
Further to this, a single event can be listened for with
one() or
$().one(), where the event handler will be removed immediately after the event has been triggered for the first time.
Bubbling
As with typical DOM events, the DataTables custom events bubble up through the document, so you can listen for events using the delegate form of
$().on() or on other elements which are higher up the DOM tree.
This can be useful, for example, to know when a new DataTable has been created, which can be listened for using the
init event thus:
$(document).on( 'init.dt', function ( e, settings ) { var api = new $.fn.dataTable.Api( settings ); console.log( 'New DataTable created:', api.table().node() ); } );
Similarly, this method could also be useful with the
xhr event which will let you know what JSON data was returned from the server from the last DataTables initiated Ajax query.
A full list of the events that DataTables and its extensions can trigger is available in the event reference documentation. | https://www.datatables.net/manual/events | CC-MAIN-2022-33 | en | refinedweb |
Deletes a class.
Workload Manager Library (libwlm.a)
#include <sys/wlm.h>
int wlm_delete_class ( wlmargs)
struct wlm_args *wlmargs;
The wlm_delete_class subroutine deletes an existing superclass or subclass. A superclass cannot be deleted if it still has subclasses other than Default and Shared defined.
The caller must have root authority to delete a superclass and must have administrator authority on a superclass to delete a subclass of the superclass.
The following fields of the wlm_args structure and the embedded
substructures need to be provided:
All the other fields can be left uninitialized for this call.
Upon successful completion, the wlm_delete_class subroutine returns a value of 0. If the wlm_delete_class subroutine is unsuccessful, a non-0 value is returned.
For a list of the possible error codes returned by the WLM API functions, see the description of the wlm.h header file.
The mkclass command, chclass command, rmclass command.
The wlm.h header file.
The wlm_change_class (wlm_change_class Subroutine) subroutine, wlm_create_class (wlm_create_class Subroutine) subroutine.
Workload Management in AIX 5L Version 5.1 System Management Concepts: Operating System and Devices. | http://ps-2.kev009.com/wisclibrary/aix51/usr/share/man/info/en_US/a_doc_lib/libs/basetrf2/wlm_delete_class.htm | CC-MAIN-2022-33 | en | refinedweb |
Introduction
As the most popular content management system globally, WordPress runs websites of various sizes, both in terms of the amount of content and web traffic. Deploying WordPress on Kubernetes is an efficient way to enable horizontal scaling of a website and successfully handle website traffic surges.
This tutorial explains two methods of deploying WordPress on Kubernetes - using Helm charts and creating your deployment from scratch.
Prerequisites
Deploying WordPress on Kubernetes with a Helm Chart
Helm charts come with pre-configured app installations that can be deployed with a few simple commands.
- Add the repository containing the WordPress Helm chart you want to deploy:
helm repo add [repo-name] [repo-address]
The system confirms the successful addition of the repository. The example uses the Bitnami chart.
2. Update local Helm repositories:
helm repo update
3. Install the chart using the helm install command.
helm install [release-name] [repo-address]
Wait for the chart to be deployed.
4. The WordPress service uses LoadBalancer as a way to expose the service. If you are using minikube, open another terminal window and type the following command to emulate the LoadBalancer:
minikube tunnel
5. When minikube displays the Running status, minimize the window and return to the previous one.
6. Check the readiness of the deployment by typing:
kubectl get all
The command lists and shows status of the pods, services, and deployments.
7. Once the pods and the deployment are ready, use the following command to export the
SERVICE_IP environment variable:
export SERVICE_IP=$(kubectl get svc --namespace default wp-test-wordpress --template "{{ range (index .status.loadBalancer.ingress 0) }}{{.}}{{ end }}")
8. Now use the echo command to display the IP address of the service:
echo "WordPress URL:"
9. Type the address into the address bar of your browser. The WordPress installation starts.
Deploying WordPress on Kubernetes with Persistent Volumes
When deploying WordPress using a custom configuration, you need to create a series of YAML files for WordPress and the database the app will be using. The example below uses MySQL, but you can also opt for MariaDB.
1. Use a text editor to create the YAML file to provision storage for the MySQL database.
nano mysql-storage.yaml
The file defines a persistent storage volume (PV) and claims that storage with the PersistentVolumeClaim (PVC). The example uses the following configuration:
apiVersion: v1 kind: PersistentVolume metadata: name: mysql-pv labels: type: local spec: storageClassName: manual capacity: storage: 10Gi accessModes: - ReadWriteOnce hostPath: path: "/mnt/data" --- apiVersion: v1 kind: PersistentVolumeClaim metadata: name: mysql-pv-claim labels: app: wordpress spec: storageClassName: manual accessModes: - ReadWriteOnce resources: requests: storage: 10Gi
Save the file and exit.
2. Create the MySQL deployment configuration YAML.
nano mysql-deployment.yaml
The deployment file contains the data related to the container image and the storage. The
claimName declaration at the bottom should correspond to the name of the PVC you created in Step 1.
apiVersion: apps/v1 kind: Deployment metadata: name: wordpress-mysql labels: app: wordpress spec: selector: matchLabels: app: wordpress tier: mysql strategy: type: Recreate template: metadata: labels: app: wordpress tier: mysql spec: containers: - image: mysql:5
Save the file and exit.
Note: Learn how to deploy a MySQL database instance on Kubernetes using persistent volumes.
3. Create the service configuration YAML for the database.
nano mysql-service.yaml
The file specifies the port that WordPress uses to connect to the service:
apiVersion: v1 kind: Service metadata: name: wordpress-mysql labels: app: wordpress spec: ports: - port: 3306 selector: app: wordpress tier: mysql clusterIP: None
Save the file and exit.
4. Now create the same YAML files for WordPress itself. Start with the storage allocation:
nano wordpress-storage.yaml
The example uses the following configuration:
apiVersion: v1 kind: PersistentVolume metadata: name: wp-pv labels: type: local spec: storageClassName: manual capacity: storage: 10Gi accessModes: - ReadWriteOnce hostPath: path: "/mnt/data" --- apiVersion: v1 kind: PersistentVolumeClaim metadata: name: wp-pv-claim labels: app: wordpress spec: storageClassName: manual accessModes: - ReadWriteOnce resources: requests: storage: 10Gi
Save the file and exit.
5. Create the deployment file:
nano wordpress-deployment.yaml
The file provides the Docker image and connects the WordPress deployment with the PVC:
apiVersion: apps/v1 kind: Deployment metadata: name: wordpress labels: app: wordpress spec: selector: matchLabels: app: wordpress tier: frontend strategy: type: Recreate template: metadata: labels: app: wordpress tier: frontend spec: containers: - image: wordpress
Save the file and exit.
6. Create the service YAML:
nano wordpress-service.yaml
The example uses LoadBalancer to expose the service:
apiVersion: v1 kind: Service metadata: name: wordpress labels: app: wordpress spec: ports: - port: 80 selector: app: wordpress tier: frontend type: LoadBalancer
Save the file and exit.
7. Create the kustomization.yaml file, which will be used to apply the configuration easily:
nano kustomization.yaml
The file contains two parts:
secretGeneratorproduces the Kubernetes secret that passes the login info to the containers.
resourcessection lists all the files that will participate in configuration. List the files you created in previous steps.
secretGenerator: - name: mysql-pass literals: - password=test123 resources: - mysql-storage.yaml - mysql-deployment.yaml - mysql-service.yaml - wordpress-storage.yaml - wordpress-deployment.yaml - wordpress-service.yaml
Save the file and exit.
8. Apply the files listed in kustomization.yaml with the following command:
kubectl apply -k ./
The system confirms the successful creation of the secret, services, PVs, PVCs, and deployments:
9. Check if the pods and the deployments are ready:
kubectl get all
10. If you use minikube, open another terminal window and start minikube tunnel to provide load balancing emulation:
minikube tunnel
Once the emulation is running, minimize the window and return to the previous one.
11. Type the following command to expose the service URL that you will use to access the deployed WordPress instance:
minikube service wordpress-service --url
The URL is displayed as the command output:
Note: If you do not use minikube, use the external IP address and the port of the WordPress service from the table in Step 9.
12. Copy the URL and paste it into your web browser. The WordPress installation starts.
Conclusion
After reading this tutorial, you will learn two methods for deploying a WordPress instance on Kubernetes. If you want to know more about managing WordPress, read 25 Performance and Optimization Tips to Speed Up Your WordPress. | https://phoenixnap.es/kb/kubernetes-wordpress | CC-MAIN-2022-33 | en | refinedweb |
I'm doing the assignment called ValidPassword.I finish most of the stuff but I stuck with one requirement.
It must start with an uppercase letter [1 point]
So if User Input is like
javastack1
the user output will be "invalid password" because the first letter is not a capital letter.
What method should I use to successfully make a requirement?
/**Hello Professor, This is my code*/import java.util.Scanner;public class validatePassword{ /** Main Method */ public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter a password: "); String password = input.nextLine(); System.out.println( (isValidPassword(password) ? "Valid " : "Invalid ") + "Password"); } /** Method isPasswordVaild tests whether a string is a valid password */ public static boolean isValidPassword(String password) { final int LValidPassword = 6; final int MNumberDigits = 1; boolean validPassword = isLengthValid(password, LValidPassword) && isOnlyLettersAndDigits(password) && hasNDigits(password, MNumberDigits); return validPassword; } /** Method isLengthValid tests whether a string is a valid length */ public static boolean isLengthValid(String password, int validLength) { return password.length() >= validLength; } /** Method isOnlyLettersAndDigits tests if a string contains only letters and digits */ public static boolean isOnlyLettersAndDigits(String password) { for (int i = 0; i < password.length(); i++) { if (!Character.isLetterOrDigit(password.charAt(i))) { return false; } } return true; } /** Method hasNDigits tests if a string contains at least n digits */ public static boolean hasNDigits(String password, int n) { int numberOfDigits = 0; for (int i = 0; i < password.length(); i++) { if (Character.isDigit(password.charAt(i))) { numberOfDigits++; } if (numberOfDigits >= n) { return true; } } return false; }}?
For Example :String = Visual BasiCoutput = V C
I have tried searching everywhere but found none, is it possible for vb.net to do this one? | http://www.convertstring.com/ja/StringFunction/ToUpperCase | CC-MAIN-2017-47 | en | refinedweb |
slow autocomplete for complex objects
since we are getting some console autocomplete improvements, might be worth asking again...
Certain objects, namely
requestsresponses take a LONG time to autocomplete, and autocomplete seems to have to start from scratch each character
>>> import requests >>> r=requests.get('')
subsequently, typing
r.takes like three seconds before another character can be typed. This is also bad in obj
Ideally, the autocomplete would be in a cancellable theead such that typing on the keyboard is responsive.
This may be related to another bug in recent versions of the beta: starting with
>>> r.iter_content()
with cursor at the end of the line, and backspacing two characters to delete the () results in a pause, then deletion of three characters. Basically, deleting a left parenthesis often results in two characters being removed. This happens often on complex objects like requests and objcinstance objects, but perhaps not on simpler ones.
>>> r.iter_conten
I have that on my radar.
- Webmaster4o
Yeah, I saw that. It doesn't bother me that much on a fast device tbh, but I definitely see the problem. Python 3 is generally a bit slower than Python 2 (not that much though, so I'm not sure if it's actually noticeable there).
Yeah, there's something about requests specifically that makes code completion slow, not completely sure what it is, but it's the same for Python 2, I think.
I have the suspicion that it's doing something funky in
__dir__()or something like that. The way the console's code completion works, there is a chance for it to trigger arbitrary code execution (which makes your/JonB's point all the more valid of course)
Just to provide users some more information and context on the subject.
The next build should actually improve the situation quite a bit (while not completely eliminating the problem). It may still take a few seconds for some objects until completions show up, but there shouldn't be a delay anymore when you continue to type or delete characters.
It'll basically just use a cache for this because the completions for
r.iter_...can simply be determined by filtering the previously-fetched completions for
r.. The cache obviously has to be cleared after each statement, so you may still see a delay when starting to type the next line, but it shouldn't be nearly as bad as it is now.
@omz In case you haven't figured it out already - this seems to be part of the issue:
Responseobjects have a property
apparrent_encoding, which internally calls
chardet.detectto guess which encoding the response data uses. Getting that property probably takes a while. (I assume Pythonista reads every attribute once to check whether it's callable, so it can add an opening paren at the end.)
Maybe the "callable check" could be done only for attributes present in the instance's
__dict__? I think those are guaranteed to be a normal dictionary lookup unless a custom
__getattribute__gets in the way.
@dgelessus That's interesting, I wasn't sure which attribute it was, but I suspected something similar. I think one problem with your proposed solution is that it wouldn't work for
objc_util, where all the ObjC methods are callable, but not present in
__dict__.
@omz The
__dict__thing is of course not perfect, as you said it won't detect "non-standard" attributes as callable even if they are. And it just occured to me that some objects may not have a
__dict__(instances of many built-in classes or user classes with
__slots__) so that's another issue.
Another option might be to have an optional user settable autocompletion delay when doing the long parsing of dir. caching will be nice though, i think my main complaint is the per character reparsing.
@JonB I don't think a delay would help very much if the completion itself isn't done asynchronously because it would just block a little later... It would certainly be better if the completion was actually asynchronous, but it's a little tricky to get this right... I'm actually uploading a new build right now (mostly because of the iOS 8 crashes), so you can see how much the cache helps in a couple of hours.
This version is definately an improvement. Objc autocomplete is quick, and i love the fuzzy suggestions for objc. I wonder if fuzzy suggestions for attributes starting with underscores should be ordered at the end though?
requests objects are still a bugaboo, since the first time still takes about 3-4 seconds on my ancient device.. strange though, dir runs in less than a millisec (and detect only runs once) so i don't get what is happening (settrace doesn't show any other code being run, though I think you've got jedi running in a separate interpreter now?). perhaps it is a recursion thing, making static analysis in jedi difficult. Gittle objects are also painfully slow, these are full of recursive and functional programming decorators galore.
@JonB The delay the first time is normal, it has to check whether every attribute is callable once, and then it caches that. There's no way around the first check without workarounds like I discussed above.
Also the interactive console's autocomplete doesn't use jedi, it does normal object inspection with
dir,
getattrand such.
- Webmaster4o
@dgelessus Well, it could be sped up if there is a recursion bug that could be fixed. If not, it could still be run asynchronously
i see... adding those ()'s requires actually getting the attribute (which technically could have side effects in a class with a very poor design)
Not sure how robust this is, but perhaps it would be worth checking what is in type(r) first? For dynamic properties which return callables, this wouldn't append the ()'s... but it avoids most side effects.
def getattribstrings(o): A=[] itstype=type(o) for a in dir(o): if hasattr(itstype,a): if callable(getattr(itstype,a)): A.append(a+'()') else: A.append(a) else: if callable(getattr(o,a)): A.append(a+'()') else: A.append(a) return A
For a Response object this runs in under 1msec and produces identical results to simply the code in the else. | https://forum.omz-software.com/topic/3093/slow-autocomplete-for-complex-objects | CC-MAIN-2017-47 | en | refinedweb |
-Advertisement
- Linux (109)
- Windows (105)
- Grouping and Descriptive Categories (96)
- Mac (74)
- Modern (57)
- Android (26)
- BSD (25)
Audio & Video Software
- Sound/Audio
- Video
- Hot topics in Audio & Video Softwarecddb differential equations vst ogre delphi iso mount mpd algorithmic music composition h264 encoder cdex delphi image processing
SoundComp
A compiler library for a language integrating all that is needed for completely defining whole sound/music compilations. From very basic stuff as defining oscillators etc in all their parameters up to note events and more.7 weekly downloads
LCDex - A Linux CDEX Clone
A Ripper and encoder frontend for Linux. Requires sndlibfile and lame.so to work.7 weekly downloads
Computational Rough Paths
CoRoPa stands for Computational Rough Paths. The aim of CoRoPa is to provide a software framework for various ideas related to Rough Path Theory, including rough differential equations and the digital description of serial data streamsVAPTools Library
jvaptools provides a library and examples for rapid vst-audio-plugin development with Java, based on Steinbergs VST interface and the sourceforge project jVSTwRapper.4.3 weekly downloads
Paranormal
An extremely customizable (pseudo-programmable) audio visualization library2 weekly downloads
TISOLib
TISOLib is an OpenSource library for Delphi to provide Image- exploring, editing, building, converting, creating or burning functions.2 weekly downloads
Akkords Calculator
A program that builds the sounds of the chord from its name. The chord building rules are applied with the respect to the requirements of music theory. The user interface is based on the WT library (c++ web toolkit).1 weekly downloads
Ezia Engine
This is a game engine that helps game developer to produce game easier.It is writen in C++ and all of the functions are fixed into classes as the engine is designed in the method of Object-Oriented.1 weekly downloads
H264 Lite Encoder
That is an video encoder that implements h264 encoding. Main goal is to provide lite Java h264 implementation for Applets and Client development.1.1 weekly downloads
jicyshout
Java library to better support http-based streaming MP3 clients by working around shortcomings of Java Media Framework (JMF) reference implementation. Streams MP3 media and metadata from icecast, shoutcast, and nanocaster (Live365) servers.
Alambic
Alambic is a music player. The goal is to implement a lot of nice features (dynamic playlist, OSD, lyrcis...) on a Windows platform using .NET Framework 3.0 and WPF.
Amadeus
A tool to organize multimedia files (but not limited only to), in a customizable way. The organization is based in virtual directories, and can be written to disk, if wanted. Amadeus is written entirely in Java, and build on Eclipse RCP..
AudioDrome
AudioDrome is a "namespace" of classes C++ Each class implements a primitive "DSP". Some composite classes are available, that complex DSPs realize. AudioDrome is addressed to the developers that intend to realize applications Audio-Based.
Broadcast audio production tools library
libbaptools - broadcast audio production tools
CDDBNet
A library that implements the CDDB protocol to access freedb and cddb servers.It is implemented in C#.
CapisuiteConvToDir
CapisuiteConv is an application for the popular ISDN telecommunication suite capisuite to automate the conversion from the voicebox files to mp3 files in a directory of your choice (maybe a smb share...).
Carbon Tag Editor
just another MP3 Tag Editor...
Cocoa Granite
Cocoa Granite is an OpenGL abstraction layer framework for Mac OS X. The framework's main purpose is to provide Cocoa developers with clean Objective C interfaces for optimized OpenGL functionality. | https://sourceforge.net/directory/audio-video/developmentstatus:prealpha/license:lgpl/ | CC-MAIN-2017-47 | en | refinedweb |
I have been working on a scenario where a WCF service hosted on IIS 7, communicates to the SharePoint 2010 server object model for performing List operations. Although SharePoint 2010 has provided in-built WCF services for working with List etc, but one my students who is working as a SharePoint 2010 developer, was having the following idea: In the diagram, I have tried to explain the type of the application he wants to develop. The application scenario of the diagram is as shown below:
The requirement behind creating a WCF service here is that the client application need not to be directly connected to the SharePoint 2010 Services. Instead an end-user carrying his laptop, will use a Desktop application to perform SharePoint List updates using WCF service. To develop such a scenario, I have used Windows 7 Enterprise N 64 bit OS with IIS 7.5. I have SharePoint 2010 installed on the same machine. Here I am assuming that you are using SharePoint 2010 and know how to create a Web Site collection and List etc. For the above scenario, I have a Web Site collection which contains the ‘SalesInfo’ List as shown below. In the application we will develop, I have used the following classes:Step 1: Open VS2010 and create a blank solution, name it as ‘SPS_2010_List_Custom_WCF’. In this solution add a new WCF service application (targeting to .NET 3.5), name it as ‘WCF_SPS_2010_List_Service’. In this project, add a reference to the ‘Microsoft.SharePoint.dll’. This component is available in the following path:C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\ISAPI\Step 2: Rename IService1.cs to IService.cs and rename Service1.svc to Service.svc. Write the below code in IService.cs:Step 3: Make sure that Service.svc markup is as below: <%@ ServiceHost Service="WCF_SPS_2010_List_Service.Service" Language="C#" Debug="true" CodeBehind="Service.svc.cs" %>Step 4: Open web.config file and set the EndPoint to BasicHttpBinding as below: Step 5: Open the Service.svc.cs and write the following code: The above code makes use of the SharePoint 2010 Server object model. It opens the SharePoint 2010 site and program sagainst the List with the name ‘SalesInfo’. Please read the comments carefully for the ‘CreateSalesRecord()’ method. Step 6: Debug the above WCF service targeting the ‘x64’ platform because SharePoint 2010 requires 64-bit support to execute. Step 7: Publish the WCF service on IIS 7.5 and make sure that the ApplicationPool under which the applicaton is published, targets to .Net 2.0 (this also supports .NET 3.5). Also configure the Identity of the ApplicationPool to ‘LocalSystem’ as shown below: Step 8: Now publish the WCF Service by creating Application under this app pool. Step 9: In the same solution, add a new WPF application, name it as ‘WPF_ClientWCF_SPS’. In this application, add the service reference of the WCF service. Name the namespace as ‘MyRef’. Step 10: Add 3 TextBoxes, 3 TextBlocks and a Button on the MainWindow.xaml as shown below: Step 11: In the ‘Save Product’ button click event, write the following code. This code makes a proxy object of the WCF service and makes a call to the CreateSalesRecord() method by passing the SharePoint 2010 site Url and the SalesInfo object to it. Step 12: Run the application, Enter data in the TextBoxes and click on the ‘Save Product’ button, the result will be as shown below: You can check the newly added entry in the List by refreshing the SharePoint 2010 site, as shown below: The Need for SPUserToken.SystemAccount Open the Service.svc.cs file and change the following code from: toNow publish the WCF service on IIS and Update the WCF service reference in the client application, put breakpoints on the ‘Save Product’ button click and the ‘CreateSalesRecord()’ and run the application. For debugging the WCF Service hosted on IIS, attach the w3wp.exe process. During debugging, the following exception will be displayed: “Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))” Here the code will crash because the user object received from the client to the WCF service, will not be able to authorize itself against the SharePoint 2010 Server Object Model. Conclusion: We have seen how to use a custom WCF service to isolate the core SharePoint 2010 services from the direct access of the remote client application. The WCF Service acts as a successful interface between the remote user client and SharePoint 2010. The entire source code of this article can be downloaded over here | http://www.dotnetcurry.com/showarticle.aspx?ID=760 | CC-MAIN-2015-18 | en | refinedweb |
Asked by:
Deploy Updates from Task Sequence SCCM 2012 Sp1 R2
Hi,
In LAB I have SCCM 2012 Sp1 R2 installed on Server 2012 R2.
In Task Sequence I have selected ALL AVAILABLE Updates, but when TS run, no updates are being installed.
However, I have run the Sync many time and its OK, I can see that updated are being populated into the Updates node of SCCM 2012 Sp1 R2.
Question is what we shall do in order to install updates?
On forum I found the following command , but needs to know why we need that, why updates not installed automatically:
WMIC /namespace:\\root\ccm path sms_client CALL TriggerSchedule "{00000000-0000-0000-0000-000000000113}" /NOINTERACTIVE
N.A.Malik
Question
All replies
- Have youdownloaded and deployed the updates to the client. In order to deploy updates in a TS they should be allready deployed to the computer. Otherwise no updates will be deployed.
- Proposed as answer by Joyce LMicrosoft contingent staff, Moderator Tuesday, November 05, 2013 2:58 AM
WMIC /namespace:\\root\ccm path sms_client CALL TriggerSchedule "{00000000-0000-0000-0000-000000000113}" /NOINTERACTIVE
This is basically not needed. It just triggers a software updates scan if you want to run the "install software updates" step a second time (otherwise the scan result would be taken from cache).
There has to be a deployment for a software update group as dekac99 already mentioned.
Torsten Meringer |
2245? What updates have you added to that package? It must be huge.
The amount of updates in a package is not relevant at all. Packages are just used to download patch binaries. A software update group defines what has to be installed on a client.
BTW: deploying all (2245) updates to 'all systems' is not the best idea - even for testing purposes. The max amount of updates per group is 1000.
Torsten Meringer |
Ok, thanks for reply. I was upset to see that updates are not being installed that's why I downloaded updates for all products and for all vendors.
Here is step by step what I did so you can better assist me:
1. Created an ADR and select Windows 8 /Windows 8.1 as product. Date Revised was set to 1 week.
Added product like Bing, Skype, Windows Live , Forfront etc.
2. Select create new package.
3. Once package created , I disabled this ADR and created a new one , this time I used Package that created previously.
ALL SYSTEM was the target collection.
I can see updates in the package, and I can see that TS shows (Installing updates, 4 of 4).
In short TS install only 4 updates, what about the rest of updates.
What I am doing wrong?
N.A.Malik | https://social.technet.microsoft.com/Forums/en-US/9eb1174b-fabf-4e4c-8359-58ebc795d461/deploy-updates-from-task-sequence-sccm-2012-sp1-r2?forum=configmanagerosd | CC-MAIN-2015-18 | en | refinedweb |
From: "Jeremy Quinn" <jeremy@media.demon.co.uk>
> At 07:43 +0200 15/09/00, Nicola Ken Barozzi wrote:
> >Why not use the fixed DTD that is used now in Cocoon2 for notifications?
> >It's kinda standard ;-)
> >And all will have to go to C2 anyway.
> >Maybe I'm just plain dumb, but shouldn't all taglibs throw the same error
> >DTD? (IMHO)
>
> +1 on that!
>
> >If you agree I will make a small taglib that can be used by other taglibs
> >4 this.
>
> What I need for FP is to check whether any other tags had an error, so I
> can decide whether to serialise the DOM they are writing or not.
>
> I am adding errors to a Hashtable to do this, though it would be great if
> there was a general mechanism to share errors between all TagLibs on a
> page. They just add errors keyed to their own namespace.
>
> Wotcha reckon?
Hmmm, I haden't thought of intra-taglib error handling... I thought that when
an error occurs, it is notified to the user via standard DTD... or to the sitemap
(C2). I cannot imagine the use, because the need hasn't touched me yet, but
my fifth sense and 3/4 ;-) tells me I'm missing something important...
Could you please elaborate more on this, I'd be grateful.
Thanks :-)
nicola_ken
BTW, may it be because my body temperature exeeds 38,5 Celsius? :-(
I must be sick to think of these thing while... I'm sick ;-) | http://mail-archives.apache.org/mod_mbox/cocoon-dev/200009.mbox/%3C019501c01ff9$d12bcbc0$98022397@ARES%3E | CC-MAIN-2015-18 | en | refinedweb |
06 September 2006 14:09 [Source: ICIS news]
HOUSTON (ICIS news)--Bank of America (BoA) said on Wednesday that Dow's plans to close an Alberta, Canada chlor-alkali plant will support prices and extend peak-like margins for the product in North America.
"With operating rates near 92%, we view the chlor-alkali market as steady and attractive with chlorine tighter than caustic for now. Provided natural gas remains near $6/m BTU, we would anticipate flattish pricing with attractive profitability through year-end followed by only modest erosion over the next 1-2 years as the cycle moves past peak," the bank said.
BoA said Dow's decision last week to close 450,000 tonne/year of chlorine capacity (3% of North American industry capacity) at ?xml:namespace>
The bank said chlorine producers are unlikely to get the full $25/ton (€17/tonne) price increase they have proposed for the fourth quarter due lower water treatment and polyvinyl chloride demand and lower prices for natural gas feedstock.
BoA said the Dow capacity reductions are most | http://www.icis.com/Articles/2006/09/06/1089365/dow-closure-to-help-chlor-alkali-margins-boa.html | CC-MAIN-2015-18 | en | refinedweb |
KinoSearch::Highlight::Highlighter - Create and highlight excerpts.
The KinoSearch code base has been assimilated by the Apache Lucy project. The "KinoSearch" namespace has been deprecated, but development continues under our new name at our new home:
my $highlighter = KinoSe = KinoSe KinoSearch::Search::Compiler object derived from
query and
searcher.
Accessor.
Accessor.
KinoSearch::Highlight::Highlighter isa KinoSearch::Object::Obj.
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. | http://search.cpan.org/~creamyg/KinoSearch-0.315/lib/KinoSearch/Highlight/Highlighter.pod | CC-MAIN-2015-18 | en | refinedweb |
could someone help me with this im trying to make a program that displays five dice rolls of two dice where each die is a number from 1 to 6, and shows the total. when run, the program should look like this:
2 4= 6
1 1= 2
6 6= 12
4 3= 7
5 2= 7
Ok i got the first part i think but when i run it, it comes up with the same output everytime. also it has to be in some kind of loop. I dont want it to be the same output every time its like the randomizer isnt working. hears what i have so far:
/*Random Numbers
3/25/03 */
#include <iostream.h>
#include <math.h> //Randomizer
int main()
{
int die
for (int roll= 1; roll<= 5; roll++)
double die=1+random(6)
cout<<die<<endl;
return(0);
} | http://cboard.cprogramming.com/cplusplus-programming/36703-cplusplus-asignment-printable-thread.html | CC-MAIN-2015-18 | en | refinedweb |
Regular expression to compare numbers
chandrajeet padhy
Greenhorn
Joined: Jul 26, 2004
Posts: 21
posted
Jan 26, 2007 08:55:00
0
I have a method
compare(Object value,
String
searchTxt);
The value can either be a Number, Date, String.
The searchTxt can have values to compare Strings, Dates, Numbers. It also can have logical comparison operators like =, !=, >, <, >=, <= eg.
compare(numValue, "> 1000 <= 2000)
compare(dateValue, "> 2006/12/12 <= 2007/01/25)
compare(stringValue, "> abc <= xyz )
Can I have some regular expression to control this comparision and make my life little easier. Because spliting the string and checking for all possible options can be a tedious job.
Peace n Regards
chandrajeet padhy
Greenhorn
Joined: Jul 26, 2004
Posts: 21
posted
Jan 26, 2007 13:22:00
0
The searchTxt can have values like
"> 1000 <= 2000"
"> 2006/12/12 <= 2007/01/25"
"> abc <= xyz"
But I can check for the instanceof for the "value" and know that the searchTxt contains logical opearators plus (only Number or only Date or only String).
The real requirement is to comare the "value" according to the search string.
Say for eg:
if the method compare is invoked as compare(200, ">=100<500") it should return true
if the method compare is invoked as compare("xyz", ">=abc<xxx") it should return false
and so on...>
Stan James
(instanceof Sidekick)
Ranch Hand
Joined: Jan 29, 2003
Posts: 8791
posted
Jan 26, 2007 13:27:00
0
I think you're stuck with splitting the string into tokens and processing each token. You're lucky in that your syntax is really simple
operator value [ operator value ... ]
And you're right, the code to
test
the object type, then test each token can be annoyingly boring and repetitive. I'd be tempted to build a swarm of little tiny classes - only a few lines each - to execute the operations.
Map operations = getOperationsFor( inputobject class name ) boolean ret = true while more tokens operator = next token value = next token operation = operations.get( operator ) ret = ret AND operation.compare( inputobject, value ) end while
An operation might look like:
class DateGT { compare( object input, String value ) { Date d1 = (Date)input; Date d2 = makeDateFrom(value); return d1.compareTo(d2) > 0; } }
Did that make sense? I bet you could build this with not one "if" test. Could be lost o fun.
A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Stefan Wagner
Ranch Hand
Joined: Jun 02, 2003
Posts: 1923
I like...
posted
Jan 26, 2007 13:57:00
0
Perhaps if you transform:
compare (x, "op1 val1 op2 val2")
to
x op1 val1 && x op2 val2
and invoke a scripting engine like beanshell, to evaluate the expression?
chandrajeet padhy
Greenhorn
Joined: Jul 26, 2004
Posts: 21
posted
Jan 26, 2007 14:20:00
0
Hi James,
Can you give an example in
java
please
Jim Yingst
Wanderer
Sheriff
Joined: Jan 30, 2000
Posts: 18671
posted
Jan 26, 2007 15:39:00
0
[chandrajeet padhy ]:
I have a method
compare(Object value, String searchTxt);
From what you say later, I think it might make a lot more sense to instead make three methods:
compare(String value, String searchTxt) compare(Number value, String searchTxt) compare(Date value, String searchTxt)
And if you
must
, you can have an Object version:
compare(Object value, String searchTxt) { if (value instanceof String) return compare((String) value, searchText); if (value instanceof Number) return compare((Number) value, searchText); if (value instanceof Date) return compare((Date) value, searchText); throw new IllegalArgumentException("Can't compare class " + value.getClass()); }
Within each of the other three methods, you will know whether you're dealing with a String, Number or Date, making the code in each individual method simpler.
"I'm not back." - Bill Harding,
Twister
Ilja Preuss
author
Sheriff
Joined: Jul 11, 2001
Posts: 14112
posted
Jan 26, 2007 16:35:00
0
Do those searchTxt objects *need* to be Strings? Where are they coming
chandrajeet padhy
Greenhorn
Joined: Jul 26, 2004
Posts: 21
posted
Jan 26, 2007 16:55:00
0
Hi Jim Yingst,
I dont have difficulty in identifying Date, Number or String.
My problem is actually inside the compare method. How can I?
As I said The searchText is a tuff thing. And James got it right. But I need a java based solution.
Stan James
(instanceof Sidekick)
Ranch Hand
Joined: Jan 29, 2003
Posts: 8791
posted
Jan 28, 2007 14:49:00
0
See if you can translate my babble into Java ... one line at a time should do it. We try to give really good hints here, but not complete solutions. If you take the effort to make some almost working code, we'll help you move it along. So jump in ... it's a lot more fun if you make it work yourself.
chandrajeet padhy
Greenhorn
Joined: Jul 26, 2004
Posts: 21
posted
Jan 29, 2007 13:21:00
0
I made it work this way. Any suggestions for improvement is welcomed.
if(element instanceof Number){ return ValueComparator.compare((Number) element, parts ); } else if(element instanceof Calendar){ return ValueComparator.compare(((Calendar) element).getTime(), parts ); }else if(element instanceof String){ return ValueComparator.compare((String) element, parts ); }
ValueComparator looks as:-
public class ValueComparator { static HashMap<String, Operation> oprations; private static String LOGICAL_OPERATORS = new String("&, |"); public static boolean compare(Number element, String[] parts){ Operation operation; boolean ret = true; int i=0; String operator, value; while(i<parts.length){ operator = parts[i]; // if(LOGICAL_OPERATORS.contains(operator)){ // i++; // continue; // } value = parts[i+1]; operation = oprations.get( operator.trim() ); if(operation != null) ret = ret && operation.compare( element, new Double(value) ); i+=2; } return ret; } private static SimpleDateFormat dateFormatter = new SimpleDateFormat(); public static boolean compare(Date element, String[] parts){ //to be implemented return false; } public static boolean compare(String element, String[] parts){ //to be implemented return false; } static{ oprations = new HashMap<String, Operation>(); oprations.put( ">", new GreaterThan()); oprations.put( "<", new LessThan()); oprations.put( "=", new EqualsTo()); oprations.put( "!=", new NotEQ()); oprations.put( ">=", new GreaterThanEQ()); oprations.put( "<=", new LessThanEQ()); } }
And then different operations as per:
public interface Operation { public boolean compare( Number gridElement, Number inputValue ); public boolean compare( Date gridElement, Date inputValue ); public boolean compare( String gridElement, String inputValue ); }
Thanks
Stan James
(instanceof Sidekick)
Ranch Hand
Joined: Jan 29, 2003
Posts: 8791
posted
Jan 29, 2007 18:13:00
0
Kool. I bet you can generalize a bit more yet. Just playing thought experiments here - you can decide if it's worth trying. What if the interface for Operation was still two objects?
public boolean compare( Object gridElement, Object inputValue );
Then the Operation would have to get the two arguments into the proper format itself. That seems like a good place to create a date or a number. An abstract DateOperation could do the date manipulation and call an abstract compare( Date, Date ) method.
Your map of operations might include the type:
operations.put( "Date.>", new DateGreaterThan()); operations.put( "Number.>", new NumberGreaterThan());
That would multiply the number of operations to types*operators. Ick. Maybe we could cut back to one operator class per type:
oprations.put( "Date.>", new DateOperation(false, false, true));
where the arguments tell what to return if the standard compareTo() returns <0, 0 or >0.
Any of that sound fun?
chandrajeet padhy
Greenhorn
Joined: Jul 26, 2004
Posts: 21
posted
Jan 31, 2007 07:36:00
0
Oh yea. I thought of that to have only one method compare(obj, obj) in the Operation interface. But, that will lead upto creating types*operators number of classes like DateGT, DateLT, DateGEQ, DateLEQ, NumberGT, NumberLT...so on.
I just kept it simiplified to have only few Operation impls to handle all data types. Great going! Thanks again.
I agree. Here's the link:
subject: Regular expression to compare numbers
Similar Threads
Struts validation regular expressions
Mask - regular expressions
extract html tags from....
Testing Input From User
java regular expressions..
All times are in JavaRanch time: GMT-6 in summer, GMT-7 in winter
JForum
|
Paul Wheaton | http://www.coderanch.com/t/328917/java/java/Regular-expression-compare-numbers | CC-MAIN-2015-18 | en | refinedweb |
This article is based on Portlets in Action, to be published June:
Inter-Portlet Communication
Introduction
Inter-portlet communication using PortletSession is one of the most widely used techniques since Portlet 1.0. Data stored in APPLICATION_SCOPE of PortletSession can be shared with servlets/portlets that form part of the same portlet application.
Say, we had a book catalog portlet. Because all portlets belonging to a portlet application are defined in the same portlet deployment descriptor, the first thing we need to do is define Book Catalog and Recently Added Book portlets in the same portlet.xml file. portlets belonging to a portlet application must be packaged in the same WAR file; therefore, we must create a single WAR containing the Book Catalog and Recently Added Book portlets.
CODE REFERENCE
I recommend that you import ch11_ipc_session eclipse project from the source code that accompanies portlets in Action to view the code listings presented in this section.
Defining multiple portlets in portlet deployment descriptor
You can define multiple portlets in portlet.xml by adding a <portlet> element for each portlet that belongs to the portlet application. Listing 1 shows a portlet.xml file that defines the Book Catalog and Recently Added Book portlets.
Listing 1 Portlet deployment descriptor—multiple portlets
<portlet-app....> <portlet> <portlet-name>recentBook</portlet-name> #1 <portlet-class> #2 chapter11.code.listing.base. #2 [CA]RecentlyAddedBookPortlet #2 </portlet-class> #2 <expiration-cache>0</expiration-cache> #3 <cache-scope>private</cache-scope> <resource-bundle> #4 content.Language-ext #4 </resource-bundle> #4 <portlet-info> <title>Recently Added Book</title> </portlet-info> </portlet> <portlet> <portlet-name>bookCatalog</portlet-name> #5 <portlet-class> #6 chapter11.code.listing.base.BookCatalogPortlet #6 </portlet-class> #6 .... <expiration-cache>60</expiration-cache> <cache-scope>private</cache-scope> .... <resource-bundle> #7 content.Language-ext #7 </resource-bundle> #7 <portlet-info> <title>Book Catalog</title> </portlet-info> .... </portlet> .... </portlet-app> #1 Name of Recently Added Book portlet #2 Portlet class #3 Expiration cache set to 0 #4 Resource bundle for the portlet #5 Name of Book Catalog portlet #6 Portlet class #7 Resource bundle for the portlet
At #1, the name of the Recently Added Book portlet is defined. At #2, the fully qualified class name of the Recently Added Book portlet is specified. At #3, <expiration-cache> specifies the expiration timestamp for the cached content as 0, which means that the content generated by the Recently Added Book portlet is always considered expired by the portlet container. At #4, the <resource-bundle> element defines the resource bundle used by the Recently Added Book portlet. At #5, the name of the Book Catalog portlet is defined. At #6, the fully qualified class name of the Book Catalog portlet is specified. At #7, the resource bundle used by the Book Catalog portlet is specified.
NOTE
Listing 1 shows that the Book Catalog and Recently Added Book portlets use the same resource bundle for labels/messages, which is not unusual.
In a portlet deployment descriptor, each <portlet> element contains configuration information specific to the portlet. The configuration information specified as the sub-element of the <portlet-app> element applies to the portlet application, that is, to all portlets that form part of the portlet application. For instance, the <container-runtime-option> sub-element of the <portlet-app> element applies to all portlets defined in the portlet deployment descriptor.
NOTE
portlets packaged in the same portlet application are usually closely related to each other in their functionality and mostly share a common code base.
Now that we have defined portlets in portlet.xml file, let’s look at how the Book Catalog portlet communicates with the Recently Added Book portlet using PortletSession.
Storing and receiving information from PortletSession
When a user adds a new book using the Book Catalog portlet, the Recently Added Book portlet is supposed to display the information about the newly added book. As the Recently Added Book portlet is not the target of user action, the Book Catalog portlet is responsible for communicating to the Recently Added Book portlet that a new book has been added and that it needs to regenerate its content to reflect the newly added book.
What information to communicate
We know how to pass information from the Book Catalog to the Recently Added Book portlet (which is by using PortletSession) but we don’t know what information we should pass. While developing portlets, you need to carefully choose what information you want to pass because that will affect the content generation logic of the target portlet.
NOTE
In the context of inter-portlet communication, we’ll use the term sender portlet to refer to the portlet responsible for initiating communication and receiver portlet to refer to the portlet, which is at the receiving end of the communication. Sender portlet(s) are the target of user actions and receiver portlet(s) are portlets that should update their content based on the action taken by the user on the sender portlet(s). For instance, in our sample scenario, the Book Catalog is the sender portlet and the Recently Added Book is the receiver portlet. In some inter-portlet communication scenarios, the sender may also act as the receiver and vice versa.
Let’s look at possible candidate information that can be sent to the Recently Added Book portlet:
- Complete information about the newly added book—the portlet doesn’t need to hit the catalog data store as the complete information is available in PortletSession.
- The newly added book’s ISBN number—the portlet will retrieve the book’s details from the catalog using the ISBN number available in PortletSession.
- A flag indicating that a new book was added to the catalog—the portlet uses this flag as an indicator that it needs to re-execute the logic to find the recently added book. In this case, the portlet will hit the catalog data store to find the newly added book.
You can send any of these pieces of information to the Recently Added Book portlet, but there are trade-offs for each choice. If you send complete information via PortletSession, you are overloading your session. If you are only sending the ISBN number, you get a performance trade-off because the portlet will have to make a round-trip to the catalog data store.
From the receiver portlet’s perspective, the communicated information can be classified as shown in table 1.
In most scenarios, the partial information approach is used because the receiver portlet usually needs to process the communicated information to generate its content.
TIP
You should avoid putting information in PortletSession during the render phase. When an action method is invoked in response to a user action on the sender portlet, you should only set the session attributes. The sequence of the render method invocations for portlets in a portal page is undefined. Therefore, if you put information in PortletSession in the render method, the other portlet(s) may not be able to read it because their render methods were already invoked by the time the information was put in PortletSession.
In inter-portlet communication scenarios, it is equally important to consider situations in which the communicated information is not available or was not delivered to the receiver portlet—the No information case defined earlier. The receiver portlet should show meaningful content even if the communicated information hasn’t been delivered or is unavailable. For instance, if the Recently Added Book portlet is completely dependent on the ISBN number stored in PortletSession for generating its content, it will not show any book details until the user adds a new book to the catalog. This gives the impression that no book has ever been added to the catalog and the catalog should be empty.
NOTE
Because we are not using a database for the examples in this article, the Book Catalog is stored as a ServletContext attribute named bookCatalog by BookCatalogContextListener (a servlet context listener). Refer to the web.xml file and the BookCatalogContextListener class in ch11_ipc_session source folder that accompanies Portlets in Action.
Caching and inter-portlet communication
In inter-portlet communication scenarios, content caching in the receiver portlet can be a spoilsport. This is how: if the receiver portlet caches the content based on the expiration-based or validation-based caching strategy, the content of the receiver portlet is not updated until the content expires or becomes invalid. So, even if you pass information via PortletSession to the receiver portlet, it will not result in updated portlet content until the cached content expires and the receiver portlet’s render method is invoked.
In our sample inter-portlet communication scenario, the Book Catalog portlet communicates the ISBN number of the newly added book to the Recently Added Book portlet via PortletSession. The content generation logic of the Recently Added Book portlet is responsible for showing meaningful content if the ISBN number of the newly added book is not available in PortletSession.
Listing 2 shows the addBook method of the BookCatalogPortlet class, which adds the ISBN number of the newly added book to PortletSession.
Listing 2 BookCatalogPortlet class—addBook method
@ProcessAction(name = "addBookAction") public void addBook(ActionRequest request, #1 ActionResponse response)throws.... { #1 .... if (errorMap.isEmpty()) { #2 bookService.addBook(new Book(category, name, #3 author, Long.valueOf(isbnNumber))); #3 request.getPortletSession().setAttribute #4 ("recentBookIsbn", isbnNumber, #4 PortletSession.APPLICATION_SCOPE); #4 .... } }
At #1, the addBook method of the BookCatalogPortlet class is responsible for adding a book to the catalog. At #2, the addBook method checks if errorMap is empty. errorMap is a HashMap, which contains validation errors occurred during the validation of the user-defined book information. If errorMap is empty (that is, no validation errors occurred), the book information is saved in the catalog by calling the addBook method of BookService, at #3. At #4, the ISBN number of the newly added book is set in the APPLICATION_SCOPE of PortletSession with name recentBookIsbn.
The ISBN number information stored in the PortletSession is now accessible to Recently Added Book portlet. Listing 3 below shows how the RecentlyAddedBookPortlet class retrieves the ISBN number from PortletSession and uses it to generate its content. If the ISBN number is found in the session, then it sorts books available in the catalog to find the recently added book.
Listing 3 RecentlyAddedBookPortlet class
public class RecentlyAddedBookPortlet extends GenericPortlet { @RenderMode(name="view") public void showRecentBook(RenderRequest request, #1 RenderResponse response)throws ....{ #1 String isbnNumber = (String)request. #2 getPortletSession().getAttribute("recentBookIsbn", #2 PortletSession.APPLICATION_SCOPE); #2 .... if(isbnNumber != null) { if(bookService.isRecentBook (Long.valueOf(isbnNumber))) { book = bookService.getBook(Long. #3 valueOf(isbnNumber)); #3 } else { book = bookService.getRecentBook(); #4 } } else { book = bookService.getRecentBook(); #5 } request.setAttribute("book", book); #6 getPortletContext().getRequestDispatcher( #7 response.encodeURL(Constants.PATH_TO_JSP_PAGE + #7 "recentPortletHome.jsp")).include(....); #7 } } #1 Render method for VIEW mode #2 Retrieve ISBN number from PortletSession #3 Retrieve book details using ISBN number #4 Retrieve recent book from catalog #5 Retrieve recent book from catalog #6 Generate portlet content using JSP page
At #1, showRecentBook defines the render method for the VIEW portlet mode. At #2, showRecentBook method retrieves the recentBookIsbn session attribute from APPLICATION_SCOPE. The recentBookIsbn attribute contains the ISBN number of the recently added book set by the Book Catalog portlet (refer to listing 2). At #3, if the ISBN number stored in the recentBookIsbn session attribute represents a recently added book in the catalog, the getBook method of BookService is called to obtain the details of the book whose ISBN number matches the value of the recentBookIsbn session attribute. At #4, if the ISBN number stored in the recentBookIsbn session attribute doesn’t represent a recently added book in the catalog, getRecentBook method of BookService is used to retrieve the recently added book from the catalog. At #5, if the recentBookIsbn session attribute is not found, the getRecentBook method of BookService is used to retrieve the recently added book from the catalog. At #6, the Book object returned by the getBook/getRecentBook method is set as a request attribute for use by the JSP page responsible for rendering content. At #7, a request is dispatched to the recentPortletHome.jsp page of the Recently Added Book portlet to show the details of the recently added book.
Listing 3 shows that the RecentlyAddedBookPortlet class does a lot of work to ensure that the content is meaningful in the context of user action. For instance, if it doesn’t find the recentBookIsbn session attribute or if it finds the ISBN number referenced by the recentBookIsbn session attribute doesn’t represent a recent book in the catalog then it executes a complex logic within the getRecentBook method to fetch the newly added book.
CODE REFERENCE
The getRecentBook method of BookService is responsible for fetching fresh catalog data and sorting it based on a sequence number assigned to each book in the catalog. The book with the highest sequence number is considered as the recently added book in the catalog.
We’ve just seen in listings 2 and 3 how PortletSession is used by the Book Catalog and Recently Added Book portlets to implement inter-portlet communication. Pretty neat, huh? Now we are ready to look at how to build, deploy, and test inter-portlet communication between the Book Catalog and Recently Added Book portlets.
Inter-portlet communication in action
Earlier we saw how to write portlets that communicate using PortletSession. Now, we’ll see how our Book Catalog and Recently Added Book portlets communicate when deployed in a web portal.
Let’s look at the steps that we need to take to test communication between our sample portlets.
Build and deploy portlet application WAR file
The steps to build and deploy portlet application containing multiple portlets are the same as for the portlet application containing a single portlet.
Create portal pages
Because we want to test inter-portlet communication in situations when communicating portlets are located on different portal pages, you should create two portal pages named Book Catalog and Recent Book.
Communicating portlets on the same portal page
To test inter-portlet communication, add the Book Catalog and Recently Added Book portlets to the Book Catalog portal page, as shown in figure 1.
Figure 1 shows communicating portlets on the same portal page. To test the communication between the sample portlets, add a new book to the catalog. You’ll discover that the Recently Added Book portlet updates its content to reflect the new book.
Communicating portlets on different portal pages
To test the communication between the sample portlets when they are located on different portal pages, add the Book Catalog portlet to the Book Catalog portal page and the Recently Added Book portlet to Recent Book. Now, add a new book to the catalog and check if the Recently Added Book portlet content reflects the details of the newly added book. You’ll find that the Recently Added Book portlet does show information about the newly added book.
So, now you’ve seen just how easy it is to get your portlets talking to each other, whether they’re on the same portal page or different ones. Next, we’ll take a look at the pros and cons of using PortletSession for inter-portlet communication.
Advantages and disadvantages of using PortletSession
Even though PortletSession was a preferred way to achieve inter-portlet communication in Portlet 1.0 days, it still has many advantages in Portlet 2.0 world.
Table 2 describes the advantages and disadvantages of using PortletSession as the means for communication between portlets.
Table 2 describes the pros and cons of using PortletSession for inter-portlet communication, which you should consider before deciding the approach that you want to use for communication between portlets.
NOTE
Some portal servers provide additional features to support the sharing session attributes between the portlets in different portlet applications. For instance, you can share the APPLICATION_SCOPE session attributes with portlets in other portlet applications using the session.shared.attributes property in the portal-ext.properties file. Note that such features are portal specific in nature and will result in portability issues.
Summary
In this article, we discussed how PortletSession, public render parameters, and portlet events can be used by portlets to coordinate with other portlets in the web portal. It is hardly possible to create a web portal with portlets that work in silos; therefore, it is important to carefully choose the inter-portlet mechanism that fits your web portal requirements. You may use three inter-portlet communication approaches in your web portal depending on the communication needs of the portlets. One of the biggest advantages of having portlets that communicate with each other is that such communication enriches the users’ experience of the web portal. Another advantage is that, at any given time, portlets reflect the content that is relevant in the context of user actions.
Speak Your Mind | http://www.javabeat.net/portletsession-based-inter-portlet-communication/ | CC-MAIN-2015-18 | en | refinedweb |
I have a program with these four files as part of it.
point.h
point.cpppoint.cppCode:#ifndef POINT_H #define POINT_H #ifndef CIRCC_H #define CIRCC_H #include "circ.h" #endif class point { public: // Constructors // Methods protected: // More methods and variables }; #endif
circ.hcirc.hCode:#include "point.h" // Methods
circ.cppcirc.cppCode:#ifndef CIRC_H #define CIRC_H #ifndef POINTC_H #define POINTC_H #include "point.h" #endif class circ:public point { public: // Constructors // Methods and Variables protected: // More variables }; #endif
I get the errorsI get the errorsCode:#include "circ.h" // Methods
- c:\users\john\documents\visual studio 2005\projects\ogl3\ogl3\point.h(19) : error C2061: syntax error : identifier 'circ'
and
- c:\users\john\documents\visual studio 2005\projects\ogl3\ogl3\circ.h(10) : error C2504: 'point' : base class undefined
as well as some other errors similar to this. I think it probably has something to do with the fact that both the circ and point classes need to include each other, but unfortunately I don't know how to fix this problem.
Exact instructions on how to resolve this problem are the most important thing here,
but I also think the problem comes because I don't really have a good idea of what exactly including files does and how exactly all the files are parsed. I just know that if a file needs to use a certain class or method, you have to include its header file, but debugging problems with it is really difficult for me, so some explanations as to what the linker and compiler are actually doing would be nice. | http://cboard.cprogramming.com/cplusplus-programming/138938-file-inclusion-problems.html | CC-MAIN-2015-18 | en | refinedweb |
Conv3D¶
- class paddle.nn. Conv3D ( in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, padding_mode='zeros', weight_attr=None, bias_attr=None, data_format='NCDHW' ) [source]
Convlution3d Layer The convolution3d layer calculates the output based on the input, filter and strides, paddings, dilations, groups parameters. Input(Input) and Output(Output) are multidimensional tensors with a shape of \([N, C, D, H, W]\) . Where N is batch size, C is the number of channels, D is the depth of the feature, H is the height of the feature, and W is the width of the feature. Convlution3D is similar with Convlution2D but adds one dimension(depth). 1-D tensor with shape [M].
\(\\sigma\): Activation function.
\(Out\): Output value, the shape of \(Out\) and \(X\) may be different.
- Parameters
in_channels (int) – The number of input channels in the input image.
out_channels (int) – The number of output channels produced by the convolution.
kernel_size (int|list|tuple, optional) – The size of the convolving kernel.
stride (int|list|tuple, optional) – The stride size. If stride is a list/tuple, it must contain three integers, (stride_D, stride_H, stride_W). Otherwise, the stride_D = stride_H = stride_W = stride. The default value is 1.
padding (int|str|tuple|list, optional) – The padding size. Padding coule be in one of the following forms. 1. a string in [‘valid’, ‘same’]. 2. an int, which means each spartial dimension(depth, height, width) is zero paded by size of padding 3. a list[int] or tuple[int] whose length is the number of spartial dimensions, which contains the amount of padding on each side for each spartial dimension. It has the form [pad_d1, pad_d2, …]. 4. a list[int] or tuple[int] whose length is 2 * number of spartial dimensions. It has the form [pad_before, pad_after, pad_before, pad_after, …] for all spartial dimensions. three integers, (dilation_D, dilation_H, dilation_W). Otherwise, the dilation_D = dilation_H = dilation_W = dilation. The default value is 1.
groups (int, optional) – The groups number of the Conv3D Layer.. The default value is 1.
padding_mode (str, optional) –
'zeros',
'reflect',
'replicate'or
'circular'. Default:
'zeros'.
weight_attr (ParamAttr, optional) – The parameter attribute for learnable parameters/weights of conv3d. If it is set to None or one attribute of ParamAttr, conv3d will create ParamAttr as param_attr. If it is set to None, the parameter is initialized with \(Normal(0.0, std)\), and the \(std\) is \((\frac{2.0 }{filter\_elem\_num})^{0.5}\). The default value is None.
bias_attr (ParamAttr|bool, optional) – The parameter attribute for the bias of conv3d. If it is set to False, no bias will be added to the output units. If it is set to None or one attribute of ParamAttr, conv3d will create ParamAttr as bias_attr. If the Initializer of the bias_attr is not set, the bias is initialized zero. The default value is None.
data_format (str, optional) – Data format that specifies the layout of input. It can be “NCDHW” or “NDHWC”. Default: “NCDHW”.
Attribute:
weight (Parameter): the learnable weights of filters of this layer.
bias (Parameter): the learnable bias of this layer.
Shape:
x: \((N, C_{in}, D_{in}, H_{in}, W_{in})\)
weight: \((C_{out}, C_{in}, K_{d}, K_{h}, K_{w})\)
bias: \((C_{out})\)
output: \((N, C_{out}, D_{out}, H_{out}, W_{out})\)
Where\[ \begin{align}\begin{aligned}D_{out}&= \frac{(D_{in} + 2 * paddings[0] - (dilations[0] * (kernel\_size[0] - 1) + 1))}{strides[0]} + 1\\H_{out}&= \frac{(H_{in} + 2 * paddings[1] - (dilations[1] * (kernel\_size[1] - 1) + 1))}{strides[1]} + 1\\W_{out}&= \frac{(W_{in} + 2 * paddings[2] - (dilations[2] * (kernel\_size[2] - 1) + 1))}{strides[2]} + 1\end{aligned}\end{align} \]
- Raises
ValueError – If the shapes of input, filter_size, stride, padding and groups mismatch.
Examples
import paddle import paddle.nn as nn paddle.disable_static() x_var = paddle.uniform((2, 4, 8, 8, 8), dtype='float32', min=-1., max=1.) conv = nn.Conv3D(4, 6, (3, 3, 3)) y_var = conv(x_var) y_np = y_var.numpy() print(y_np.shape) # (2, 6, 6, 6, 6) | https://www.paddlepaddle.org.cn/documentation/docs/en/api/paddle/nn/Conv3D_en.html | CC-MAIN-2022-05 | en | refinedweb |
Since Groovy 1.7.1 we can use the
sum() method on an array of objects. We already could use it for collections and iterators, but this has been extended to array of objects. The
sum() can take a closure as an argument. The result of the closure is used to add the values together. Finally we can use an initial value for the sum.
def n = 0..5 as Integer[] assert n instanceof Integer[] assert 0 + 1 + 2 + 3 + 4 + 5 == n.sum() assert 10 + 0 + 1 + 2 + 3 + 4 + 5 == n.sum(10) assert 0 + 10 + 20 + 30 + 40 + 50 == n.sum { it * 10 } assert 10 + 0 + 10 + 20 + 30 + 40 + 50 == n.sum(10, { it * 10 }) | https://blog.mrhaki.com/2010/04/groovy-goodness-sum-values-in-object.html | CC-MAIN-2022-05 | en | refinedweb |
As a PHP developer, you may use the Test-Driven Development (TDD) technique to develop your software by writing tests. Typically, TDD will divide each task of the development into individual units. A test is then written to ensure that the unit behaves as expected.
Every project that uses Test-Driven Development follows three simple steps repeatedly:
- Write a test for the next bit of functionality you want to add.
- Write the functional code until the test passes.
- Refactor both new and old code to make it well structured.
Continue cycling through these three steps, one test at a time, building up the functionality of the system. Testing will help you to refactor, which allows you to improve your design over time and makes some design problems more obvious.
The tests that contain small individual components are called unit tests. While unit tests can be carried out independently, if you test some of the components when they are integrated with other components, you are doing integration testing. The third kind of testing is test stubs. Test stubs allow you to test your code without having to make real calls to a database.
Why TDD Works
Nowadays, as you may use modern PHP IDE syntax, feedback is not a big deal. One of the important aspects of your development is making sure that the code does what you expect it to do. As software is complicated (different components integrated with each other), it would be difficult for all of our expectations to come true. Especially at the end of the project, due to your development, the project will become more complex, and thus more difficult to debug and test.
TDD verifies that the code does what you expect it to do. If something goes wrong, there are only a few lines of code to recheck. Mistakes are easy to find and fix. In TDD, the test focuses on the behavior, not the implementation. TDD provides proven code that has been tested, designed, and coded.
PHPUnit & Laravel
PHPUnit is the de-facto standard for unit testing PHP. It’s essentially a framework for writing tests and providing the tools that you will need to run tests and analyze the results. PHPUnit derives its structure and functionality from Kent Beck’s SUnit.
There are several different assertions that can help you test the results of all sorts of calls in your applications. Sometimes you have to be a bit more creative to test a more complex piece of functionality, but the assertions provided by PHPUnit cover the majority of cases you would want to test. Here is a list of some of the more common ones you will find yourself using in your tests:
- AssertTrue: Check the input to verify it equals true.
- AssertFalse: Check the input to verify it equals false value.
- AssertEquals: Check the result against another input for a match.
- AssertArrayHasKey(): Reports an error if array does not have the key.
- AssertGreaterThan: Check the result to see if it’s larger than a value.
- AssertContains: Check that the input contains a certain value.
- AssertType: Check that a variable is of a certain type.
- AssertNull: Check that a variable is null.
- AssertFileExists: Verify that a file exists.
- AssertRegExp: Check the input against a regular expression.
By default, PHPUnit 4.0 is installed in Laravel, and you may run the following command to update it:
composer global require "phpunit/phpunit=5.0.*"
The
phpunit.xml file in the Laravel root directory will let you do some configurations. In this case, if you want to override the default configuration you can edit the file:
./tests/ app/
As you see in the code above, I have added the sample (not used in the article) database configuration.
What Is Doctrine ORM?
Doctrine is an ORM which implements the data mapper pattern and allows you to make a clean separation of the application’s business rules from the persistence layer of the database. To set up Doctrine, there is a bridge to allow for matching with Laravel 5’s existing configuration. To install Doctrine 2 within our Laravel project, we run the following command:
composer require laravel-doctrine/orm
As usual, the package should be added to the
app/config.php, as the service provider:
LaravelDoctrine\ORM\DoctrineServiceProvider::class,
The alias should also be configured:
'EntityManager' => LaravelDoctrine\ORM\Facades\EntityManager::class
Finally, we publish the package configuration with:
php artisan vendor:publish --tag="config"
How to Test Doctrine Repositories
Before anything else, you should know about fixtures. Fixtures are used to load a controlled set of data into a database, which we need for testing. Fortunately, Doctrine 2 has a library to help you write fixtures for the Doctrine ORM.
To install the fixtures bundle in our Laravel App, we need to run the following command:
composer require --dev doctrine/doctrine-fixtures-bundle
Let’s create our fixture in
tests/Fixtures.php:
namespace Test; use Doctrine\Common\Persistence\ObjectManager; use Doctrine\Common\DataFixtures\FixtureInterface; use app\Entity\Post; class Fixtures implements FixtureInterface { /** * Load the Post fixtures * @param ObjectManager $manager * @return void */ public function load(ObjectManager $manager) { $Post = new Post(['title'=>'hello world','body'=>'this is body']); $manager->persist($Post); $manager->flush(); } }
As you see, your fixture class should implement the
FixtureInterface and should have the
load(ObjectManager $manager) method. Doctrine2 fixtures are PHP classes where you can create objects and persist them to the database. To autoload our fixtures in Laravel, we need to modify
composer.json in our Laravel root:
... "autoload-dev": { "classmap": [ "tests/TestCase.php", "tests/Fixtures.php" //added here ] }, ...
Then run:
composer dump-autoload
Let’s create our test file in the tests directory
DoctrineTest.php.
namespace Test; use App; use App\Entity\Post; use Doctrine\Common\DataFixtures\Executor\ORMExecutor; use Doctrine\Common\DataFixtures\Purger\ORMPurger; use Doctrine\Common\DataFixtures\Loader; use App\Repository\PostRepo; class doctrineTest extends TestCase { private $em; private $repository; private $loader; public function setUp() { parent::setUp(); $this->em = App::make('Doctrine\ORM\EntityManagerInterface'); $this->repository = new PostRepo($this->em); $this->executor = new ORMExecutor($this->em, new ORMPurger); $this->loader = new Loader; $this->loader->addFixture(new Fixtures); } /** @test */ public function post() { $purger = new ORMPurger(); $executor = new ORMExecutor($this->em, $purger); $executor->execute($this->loader->getFixtures()); $user = $this->repository->PostOfTitle('hello world'); $this->em->clear(); $this->assertInstanceOf('App\Entity\Post', $user); } }
In the
setUp() method, I instantiate the
ORMExecutor and the Loader. We also load the
Fixtures class we just implemented.
Do not forget that the
/** @test */ annotation is very important, and without this the phpunit will return a
No tests found in class error.
To begin testing in our project root, just run the command:
sudo phpunit
The result would be:
PHPUnit 4.6.6 by Sebastian Bergmann and contributors. Configuration read from /var/www/html/laravel/phpunit.xml. Time: 17.06 seconds, Memory: 16.00M OK (1 test, 1 assertion)
If you want to share objects between fixtures, it is possible to easily add a reference to that object by name and later reference it to form a relation. Here is an example:
namespace Test; use Doctrine\Common\Persistence\ObjectManager; use Doctrine\Common\DataFixtures\FixtureInterface; use app\Entity\Post; class PostFixtures implements FixtureInterface { /** * Load the User fixtures * * @param ObjectManager $manager * @return void */ public function load(ObjectManager $manager) { $postOne = new Post(['title'=>'hello','body'=>'this is body']); $postTwo = new Post(['title'=>'hello there ','body'=>'this is body two']); $manager->persist($postOne); $manager->persist($postTwo); $manager->flush(); // store reference to admin role for User relation to Role $this->addReference('new-post',$postOne); } }
and the Comment fixture:
namespace Test; use Doctrine\Common\Persistence\ObjectManager; use Doctrine\Common\DataFixtures\FixtureInterface; use app\Entity\Post; class CommentFixtures implements FixtureInterface { /** * Load the User fixtures * * @param ObjectManager $manager * @return void */ public function load(ObjectManager $manager) { $comment = new Comment(['title'=>'hello','email'=>'alirezarahmani@live.com','text'=>'nice post']); $comment->setPost($this->getReference('new-post')); // load the stored reference $manager->persist($comment); $manager->flush(); // store reference to new post for Comment relation to post $this->addReference('new-post',$postOne); } }
With two methods of
getReference() and
setReference(), you can share object(s) between fixtures.
If ordering of fixtures is important to you, you can easily order them with the
getOrder method in your fixtures as follows:
public function getOrder() { return 5; // number in which order to load fixtures }
Notice the ordering is relevant to the Loader class.
One of the important things about fixtures is their ability to resolve dependency problems. The only thing you need to add is a method in your fixture as I did below:
public function getDependencies() { return array('Test\CommentFixtures'); // fixture classes fixture is dependent on }
Conclusion
This is just a description of Test-Driven Development with Laravel 5 and PHPUnit. When testing repositories, it’s inevitable that you are going to hit the database. In this case, Doctrine fixtures are important.
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.Update me weekly | https://code.tutsplus.com/tutorials/test-driven-development-with-laravel-doctrine--cms-25563?ec_unit=translation-info-language | CC-MAIN-2022-05 | en | refinedweb |
FrameLayout Layout
FrameLayout It's the simplest of the five layouts .FrameLayout The elements in the layout overlap according to the order . utilize FrameLayout Characteristics of overlapping layout elements , We can generally hide and display some layers , And the ability to place another small icon on an image .
Look at the code :
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android=""
android:layout_width="fill_parent"
android: <!-- Base map --> <LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android: <ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:
</LinearLayout> <!-- This view will overlay on the top of the graph above --> <LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android: <ImageView
android:id="@+id/imageView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:layout_marginTop="100dp"
android: </LinearLayout> <!-- Invisible view -->
<ImageView
android:id="@+id/imageView3"
android:visibility="gone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android: </FrameLayout>
effect : The first picture is at the bottom , The second picture is above , The third picture is gone Hide the .
Android Development 24:FrameLayout More articles on layout
- Android Development 06: Layout - Linear layout LinearLayout
LinearLayout Organize views into rows or columns . Subviews can be arranged vertically or horizontally . Linear layout is a very common layout . Look at an example of layout : <LinearLayout xmlns:android=& ...
- Android app Development -05-Android xml Layout details
Android app Development -05-Android xml Layout details Although there is Ink knife , Mohist These graphical development tools do Android Interface design , But we can't do without learning to be Android native app, Study xml Layout is still necessary ...
- .Net Programmers learn Android development quickly - Layout and click event writing
Focus on today's headlines - Be a siege lion of the whole stack , Learning code also requires reading , Love the whole stack , Love life more . Provide technical and life guidance for programmers . This series of courses Committed to veteran programmers can quickly get started learning Android Development . Systematically and comprehensively from a .Net Step by step from the perspective of programmers ...
- Android Development : Preliminary understanding of the layout file layout
After understanding the directory structure of the project , After the role of the main document . After understanding the definition and use of each constant file , The next big play must be the layout file layout. Sure enough , About online “ Android layout file layout” Various introductions of . analysis . In depth analysis , And so on ...
- Android Development _ Learn more ViewPager Control
One . summary ViewPager yes android Expansion pack, v4 package (android.support.v4.view.ViewPager) Class in , This class allows users to switch the current view. ViewPager characteristic : ...
- Learn Android Development [4] - Use implicit Intent Start SMS 、 Contacts 、 Camera applications
Learn about Android development in the last article [3] - Use RecyclerView In the display list, I learned that when displaying the list RecyclerView Use , This record is how to use implicit Intent Call the functions of other applications , Like texting . ...
- Android Development Notes —— About open source projects SlidingMenu Introduction to the use of ( Imitation QQ5.0 Sideslip menu )
I remember writing about this sideslip effect at the end of last year , At that time, it was using custom HorizontalScrollView To achieve , The effect is as follows : Interested friends can see this document < Android Development Notes —— Customize HorizontalScro ...
- Android Development Notes ——Fragment+FragmentTabHost Components ( Realize the bottom menu of sina Weibo )
I remember writing about it before 2 This article is about the implementation of the bottom menu , Because it's out of date TabHost class , Although it can also achieve the effect we want , But as learning , Still need to know about this new class FragmentTabHost Before 2 Links to articles : Ann ...
- Android Development Notes ——TabHost Components ( Two )( Realize bottom menu navigation )
The above article < Android Development Review Notes ——TabHost Components ( One )( Realize bottom menu navigation )> Using customization is mentioned in View(ImageView+TextView) To set the style of a bottom menu Here's a more spiritual one ...
Random recommendation
- font-size:100% What's the role
h1,h2,h3,h4,h5,h6 {font-size:100%;font-weight:normal;} input,select,textarea,samp {font-size:100%;} ...
- IIS Express Allow external access ( External debugging )
Visual Studio coordination IIS Express by Web Development provides powerful debugging capabilities , In this paper, IIS Express How to access other devices in LAN in debug mode , For testing . 1. open IIS Expr ...
- BigDecimal Tool class processing precision calculation
/** * Created by My_coder on 2017-07-27. * Addition, subtraction, multiplication and division calculation tool class */ public class BigDecimalUtil { private BigDec ...
- To survive in the cracks - In the world of nothing php Virtual host environment using smtp Send E-mail ( Two )
To survive in the cracks Preface : In the last essay , With 163 Personal email as the sending email address , When the email address is QQ In the mailbox , It's very likely to be thrown directly into the mail bin , To solve this problem , Apply for registration of enterprise email , Can reduce the number of emails sent as spam ...
- FPM Four : use OVP Do the query and jump to the details
The previous query UIBB To configure , It can be reused directly here , Of the query feeder class It's automatically reused . 1. For inquiry feeder class Add interface , Continue to inherit form The interface of . 2. Implement each method one by one , Even if it doesn't work ...
- python Universal decorator , Decorator with parameters ,
# Use decorators to decorate functions with return values # def func(functionName): # print('---func-1----') # def func_in(): # print(" ...
- DC3 Find suffix array board
#include<bits/stdc++.h> #define LL long long #define fi first #define se second #define mk mak ...
- error: cannot lock ref 'refs/remotes/origin/master': unable to resolve reference 'refs/remotes/origin/master': reference broken...
Previously, I added a branch to my project , And then I did something , For example, synchronize the local branches to the remote warehouse , Then branch merge is done in the remote warehouse , as well as Pull request Operation, etc. , later , In the local warehouse git fetc ...
- AFNetworking Simple use
AFNetworking Download address : AFNetworking Is very simple to use , Create a class , Call a method to achieve ...
- Django introduction ( Two )
This section mainly introduces django Medium model,template Templates . model yes django Self contained orm frame , Now let's build a blog website , Let's see how it's used . 1. New application blog python man ... | https://chenhaoxiang.cn/2021/06/20210604190458543C.html | CC-MAIN-2022-05 | en | refinedweb |
This is the second part of a two-part series of blog posts that show an end-to-end MLOps framework on Databricks, which is based on Notebooks. In the first post, we presented a complete CI/CD framework on Databricks with notebooks. The approach is based on the Azure DevOps ecosystem for the Continuous Integration (CI) part and Repos API for the Continuous Delivery (CD). This post extends the presented CI/CD framework with machine learning providing a complete ML Ops solution.
The post is structured as follows:
- Introduction of the ML Ops methodology.
- Using notebooks in the development and deployment lifecycle.
- A detailed example that includes code snippets and showcases a complete pipeline with an ML-specific testing suite, version control and development, staging, and production environments.
Why do we need MLOps?
Artificial intelligence and machine learning are some of the biggest phenomena in the past two decades, changing and shaping our everyday life. This automated decision-making comes, however, with its own set of challenges and risks, and there is no free lunch here. Productionizing ML is difficult as it is not only underlying software changes that affect the output but even more, so a good quality model is powered by high-quality data.
Furthermore, versioning of data, code and models becomes even more difficult if an organization tries to apply it at a massive scale to really become an AI-first company. Putting a single machine learning model to use comes with completely different costs and risks than having thousands of models iterated and improved frequently. Therefore, a holistic approach is needed across the entire product lifecycle, from an early prototype to every single release, repeatedly testing multiple aspects of the end result and highlighting any issues prior to end-customer exposure. Only that practice lets teams and companies scale their operations and deliver high-quality autonomous systems. This development practice for data products powered by ML is called MLOps.
What is MLOps?
DevOps practices are a common IT toolbox and a philosophy that enables fast, iterative release processes for software in a reliable and performant manner. This de-facto standard for software engineering becomes much more challenging in Machine Learning projects, where there are new dimensions of complexity – data and derived model artifacts, that need to be accounted for. The changes in data, popularly known as drift, which may affect the models and model-related outputs, yield the birth of new terminology: MLOps.
In a nutshell, MLOps extends and profoundly inherits practices from DevOps, adding new tools and methodology that allow for the CI/CD process on the system, where not only code but also data changes. Thus the suite of tools needed addresses typical software development techniques but also adds similar programmatic and automated rigor to the underlying data.
Therefore, hand in hand with the growing adaptation of AI and ML across businesses and organizations, there is a growing need for best-in-class MLOps practices and monitoring. This essential functionality provides organizations with the necessary tools, safety nets, and confidence in automation solutions enabling them to scale and drive value. The Databricks platform comes equipped with all the necessary solutions as a managed service, allowing companies to automate and use ready technologies focusing on high-level business challenges.
Why is it hard to implement MLOps using notebooks?
While notebooks have gained tremendous popularity over the past decade and have become synonymous with data science, there are still a few challenges faced by machine learning practitioners working in agile development. Most of the machine learning projects have their roots in notebooks, where one can easily explore, visualize and understand the data. Most of the coding starts in a notebook where data scientists can promptly experiment, brainstorm, build and implement a modeling approach in a collaborative and flexible manner. While historically, most of the hardening and production code had to be rewritten and reimplemented in IDEs, over the last few years, we have observed a sharp rise in using notebooks for production workloads. That is usually feasible whenever the code base has small and manageable interdependencies and mostly consumes libraries. In that case, teams can minimize and simplify the implementation time while keeping the code base transparent, robust, and agile in notebooks. One of the key reasons for that dramatic shift has been the growing wealth of CI/CD tools now at our disposal. Machine learning, however, adds another dimension of complexity to the CI/CD pipelines delivered in notebooks with multiple dependencies between modules/notebooks.
Continuous delivery and monitoring of ML projects
In the previous paragraph, we depicted a framework for testing our codebase, as well as testing and quality assurance of newly trained ML models — MLOps. Now we can discuss how we use these tools to implement our ML project using the following principles:
- The model interface is unified. Establishing a common structure of each model, similarly to packages like scikit-learn with common .fit() and .predict() methods, is essential for the reusability of the framework for various ML techniques that can be easily interchanged. That allows us to start with potentially simpler baseline ML models in an end-to-end fashion and iterate with other ML algorithms without changing the pipeline code.
- Model training must be decoupled from evaluation and scoring and implemented as independent pipelines/notebooks. The decoupling principle makes the code base modular and allows us, again, to compare various ML architectures/frameworks with each other. This is an important part of MLOps, where we can easily evaluate various ML models and test the predictive power prior to promotion. Furthermore, the trained model persisted in MLflow can be easily reused in other jobs and frameworks, without dependency on the training/environment setup, e.g., deployed as a REST API service.
- Model scoring must be able to always rely on a model repository to get the latest approved version of our model. This, in conjunction j with the MLOps framework, where only tested and well-performing models are promoted, ensures the right, high-quality model version is being deployed in a fully-automated fashion to our production environment while keeping the training pipeline proposing new models regularly using new data inputs.
We can fulfill the requirements defined earlier by using the architecture depicted in the following illustration:
As depicted above, the training pipeline (you can review the code here) trains models and logs them to MLflow. We can have multiple training pipelines for different model architectures or different model types. All models trained by these pipelines can be logged to MLflow and used for scoring using a unified MLflow interface. The evaluation pipeline (you can review the code here) can then be run after every training pipeline and be used at the outset to compare all these new models against one another. In this way, the candidate models can be evaluated against the current production model too. An example of the ideal evaluation pipeline, implemented using MLFlow, is discussed below.
Let’s implement model comparison and selection!
We will need a couple of building blocks to implement the full functionality, which we will place into individual functions. The first one will allow us to get all the newly trained models from our MLflow training pipelines. To do this, we will leverage the MLflow-experiment data source that allows us to use Apache Spark™ to query MLflow experiment data. Having MLflow experiment data available as a Spark dataframe makes the job really easy:
def get_candidate_models(self): spark_df = self.spark.read.format ("mlflow-experiment").load(str(self.experimentID)) pdf = spark_df.where("tags.candidate='true'") .select("run_id").toPandas() return pdf['run_id'].values
To compare models, we will need to come up with some metrics first. This is usually case specific and should be aligned to business requirements. The functions shown below load the model using run_id from the MLflow experiment and calculate the predictions using the latest available data. For a more robust evaluation, we apply bootstrapping and derive multiple metrics for samples drawn, with repetition from the original evaluation set. Then it calculates the ROC AUC metric for each randomly drawn set that will be used to compare the models. If the candidate model outperforms the current version on at least 90% of samples, it is then promoted to production. In an actual project, this metric must be selected carefully.
def evaluate_model(self, run_id, X, Y): model = mlflow.sklearn.load_model(f'runs:/{run_id}/model') predictions = model.predict(X) n = 100 sampled_scores = [] score = 0.5 rng = np.random.RandomState() for i in range(n): # sampling with replacement on the prediction indices indices = rng.randint(0, len(predictions), len(predictions)) if len(np.unique(Y.iloc[indices])) < 2: sampled_scores.append(score) continue score = roc_auc_score(Y.iloc[indices], predictions[indices]) sampled_scores.append(score) return np.array(sampled_scores)
The function below evaluates multiple models supplied as run_ids list and calculates multiple metrics for each of them. This allows us to find the model with the best metric:
def get_best_model(self, run_ids, X, Y): best_roc = -1 best_run_id = None for run_id in run_ids: roc = self.evaluate_model(run_id, X, Y) if np.mean(roc > best_roc) > 0.9: best_roc = roc best_run_id = run_id return best_roc, best_run_id
Now let’s put all these building blocks together and see how we can evaluate all new models and compare the best new model with the ones in production. After determining the best newly trained model, we will leverage the MLflow API to load all production model versions and compare them using the same function that we have used to compare newly trained models.
After that, we can compare the metrics of the best production model and the new one and decide whether or not to put the latest model to production. In the case of a positive decision, we can leverage MLflow Model Registry API to register our best newly-trained model as a registered model and promote it to a production state.
cand_run_ids = self.get_candidate_models() best_cand_roc, best_cand_run_id = self.get_best_model (cand_run_ids, X_test, Y_test) print('Best ROC (candidate models): ', np.mean(best_cand_roc)) try: versions = mlflow_client.get_latest_versions(self.model_name, stages=['Production']) prod_run_ids = [v.run_id for v in versions] best_prod_roc, best_prod_run_id = self.get_best_model(prod_run_ids, X_test, Y_test) except RestException: best_prod_roc = -1 print('ROC (production models): ', np.mean(best_prod_roc)) if np.mean(best_cand_roc >= best_prod_roc) > 0.9: # deploy new model model_version = mlflow.register_model(f"runs:/{best_cand_run_id}/model", self.model_name) time.sleep(5) mlflow_client.transition_model_version_stage(name=self.model_name, version=model_version.version, stage="Production") print('Deployed version: ', model_version.version) # remove candidate tags for run_id in cand_run_ids: mlflow_client.set_tag(run_id, 'candidate', 'false')
Summary
In this blog post, we presented an end-to-end approach for MLOps on Databricks using notebook-based projects. This machine learning workflow is based on the Repos API functionality that not only lets the data teams structure and version control their projects in a more practical way but also greatly simplifies the implementation and execution of the CI/CD tools. We showcased an architecture where all operational environments are fully isolated, ensuring a high degree of security for production workloads powered by ML. An exemplary workflow was discussed that spans all steps in the model lifecycle with a strong focus on an automated testing suite. These quality checks may not only cover typical software development steps (unit, integration, etc.) but also focus on the automated evaluation of any new iteration of the retrained model. The CI/CD pipelines are powered by a framework of choice and integrate with the Databricks Lakehouse platform smoothly, triggering.
References:
- Github repository with implemented example project:
-
- Continuous Delivery for Machine Learning, Martin Fowler,,
- Overview of MLOps,
- Part 1: Implementing CI/CD on Databricks Using Databricks Notebooks and Azure DevOps,
- Introducing Azure DevOps, | https://databricks.com/blog/2022/01/05/implementing-mlops-on-databricks-using-databricks-notebooks-and-azure-devops-part-2.html | CC-MAIN-2022-05 | en | refinedweb |
Performance tips
Indexing Unreal Engine code
You can start typing or navigating through your Unreal Engine project seconds after you open it because by default, indexing of the engine code (which constitutes the major part of a project) is performed in the background after non-engine code is parsed.
You can configure how the engine code is indexed on the Alt+R, O) : you can disable the background indexing in case you want to have all engine code indexed before you start, or if you notice any performance degradation, you can disable the indexing altogether by clearing the Index Unreal Engine source files.page of ReSharper options (
When the indexing is enabled, you will have a number of features. For example, use any symbols from the engine and ReSharper will automatically add missing #includes, or find usages of engine classes — for example,
TArray<T>— in the engine's code and study how they are used there.
If the indexing is disabled, ReSharper will still index header file names, which is very fast but it will let you have code completion for includes, for example,
#include <unreal/SomeClassFromUnreal.h>. Once you include a header, its code will be indexed automatically, so you will have code completion and analysis for symbols from the included header.
UnrealHeaderTool inspections
ReSharper runs UnrealHeaderTool only on the file that is currently open, and the process is optimized to have a minimal impact on overall performance. You can still disable the UnrealHeaderTool integration via the Enable UnrealHeaderTool inspections option on the page of ReSharper options (Alt+R, O) . | https://www.jetbrains.com/help/resharper/Unreal_Engine__Performance.html | CC-MAIN-2022-05 | en | refinedweb |
Changes document for Module::Util 1.09 - Thu Jan 10 2013 - Added module_name_parts 1.08 - Mon May 28 2012 - Added an explicit =encoding directive to avoid pod errors 1.07 - Tue Apr 7 2009 - No changes since 1.06 1.06 - Mon Mar 16 2009 - Attempted to get tests working with perl 5.6 (RT 44173) - Suppressed warnings generated by File::Find (RT 40924) 1.05 - Fri Nov 7 2008 - Bugfix RT 40632 1.04 - Sat Jun 28 2008 - Removed dependency on File::Find::Rule 1.03 - Tue Oct 24 2006 - Added -V switch to pm_which, to display versions - Made find_in_namespace return unique module names 1.02 - Thu Oct 12 2006 - Fixed version numbers in this file. - Added a work around for a potential bug in find_in_namespace on windows when resolving paths against relative directories in the include path 1.01 - Wed Apr 28 2006 - Added --version switch to pm_which - Fixed a bug in pm_which's -I switch (extra paths were ignored) - Fixed a bug with pm_which's -p switch - Changed Module::Util's SYNOPSIS a little 1.00 - Thu Nov 10 2005 - Initial revision | https://metacpan.org/dist/Module-Util/changes | CC-MAIN-2022-05 | en | refinedweb |
Safe-TypeORMSafe-TypeORM
npm install --save safe-typeorm
The
safe-typeorm is a helper library for typeorm, enhancing safety in the compilation level.
- When writing SQL query,
- Errors would be detected in the compilation level
- Auto Completion would be provided
- Type Hint would be supported
- You can implement App-join very conveniently
- When SELECTing for JSON conversion
- When INSERTing records
- Sequence of tables would be automatically sorted by analyzing dependencies
- The performance would be automatically tuned
DemonstrationDemonstration
ORM Model ClassesORM Model Classes
For demonstration, I've taken ORM model classes from the Test Automation Program of this
safe-typeorm. The ORM model classes in the Test Automation Program represents a BBS (built-in bullet system) and its ERD (Entity Relationship Diagram) is like upper image.
Also, below is the list of ORM model classes used in the Test Automation Program. If you want to see the detailed code of the ORM model classes, click the below link. Traveling the ORM model classes, you would understand how to define the ORM model classes and their relationships through this
safe-typeorm.
- src/test/models
- Sections
BbsCategory: To demonstrate the recursive 1: N relationship
BbsGroup
- Articles
BbsArticle: To demonstrate lots of relationships
BbsReviewArticle: To demonstrate super & sub type definition
BbsQuestionArticle
BbsAnswerArticle
BbsArticleTag: To demonstrate
JsonSelectBuilder.Output.Mapper
BbsArticleContent: To demonstrate M: N relationship
BbsArticleContentFilePair: To resolve the M: N relatioship
BbsComment: To demonstrate M: N relationship
BbsCommentFilePair: To resolve the M: N relatioship
- Miscellaneous
Safe Query BuilderSafe Query Builder
In
safe-typeorm, you can write SQL query much safely and conveniently.
If you take a mistake when writing an SQL query, the error would be occured in the compilation level. Therefore, you don't need to suffer by runtime error by mistaken SQL query. Also, if you're writing wrong SQL query, the IDE (like VSCode) will warn you with the red underlined emphasizing, to tell you there can be an SQL error.
Also,
safe-typeorm supports type hinting with auto-completion when you're writing the SQL query. Therefore, you can write SQL query much faster than before. Of course, the fast-written SQL query would be ensured its safety by the compiler and IDE.
export async function test_safe_query_builder(): Promise<void> { const group: BbsGroup = await BbsGroup.findOneOrFail(); const category: BbsCategory = await BbsCategory.findOneOrFail(); const stmt: orm.SelectQueryBuilder<BbsQuestionArticle> = safe .createJoinQueryBuilder(BbsQuestionArticle, question => { question.innerJoin("base", article => { article.innerJoin("group"); article.innerJoin("category"); article.innerJoin("__mv_last").innerJoin("content"); }); question.leftJoin("answer") .leftJoin("base", "AA") .leftJoin("__mv_last", "AL") .leftJoin("content", "AC"); }) .andWhere(...BbsArticle.getWhereArguments("group", group)) .andWhere(...BbsCategory.getWhereArguments("code", "!=", category.code)) .select([ BbsArticle.getColumn("id"), BbsGroup.getColumn("name", "group"), BbsCategory.getColumn("name", "category"), BbsArticle.getColumn("writer"), BbsArticleContent.getColumn("title"), BbsArticle.getColumn("created_at"), BbsArticleContent.getColumn("created_at", "updated_at"), BbsArticle.getColumn("AA.writer", "answer_writer"), BbsArticleContent.getColumn("AA.title", "answer_title"), BbsArticle.getColumn("AA.created_at", "answer_created_at"), ]); stmt; }
App Join BuilderApp Join Builder
With the
AppJoinBuilder class, you can implement application level joining very easily.
Also, grammer of the
AppJoinBuilder is exactly same with the
JoinQueryBuilder. Therefore, you can swap
JoinQueryBuilder and
AppJoinBuilder very simply without any cost. Thus, you can just select one of them suitable for your case.
export async function test_app_join_builder(): Promise<void> { const builder: safe.AppJoinBuilder<BbsReviewArticle> = safe .createAppJoinBuilder(BbsReviewArticle, review => { review.join("base", article => { article.join("group"); article.join("category"); article.join("contents", content => { content.join("reviewContent"); content.join("files"); }); article.join("comments").join("files"); }); }); }
Furthermore, you've determined to using only the
AppJoinBuilder, you can configure it much safely. With the
AppJoinBuilder.initialize() method, you've configure all of the relationship accessors, and it prevents any type of ommission by your mistake.
export async function test_app_join_builder_initialize(): Promise<void> { const builder = safe.AppJoinBuilder.initialize(BbsGroup, { articles: safe.AppJoinBuilder.initialize(BbsArticle, { group: undefined, review: safe.AppJoinBuilder.initialize(BbsReviewArticle, { base: undefined, }), category: safe.AppJoinBuilder.initialize(BbsCategory, { articles: undefined, children: undefined, parent: "recursive" }), contents: safe.AppJoinBuilder.initialize(BbsArticleContent, { article: undefined, files: "join" }), comments: safe.AppJoinBuilder.initialize(BbsComment, { article: undefined, files: "join" }), tags: "join", __mv_last: undefined, question: undefined, answer: undefined, }) }); }
JSON Select BuilderJSON Select Builder
In
safe-typeorm, when you want to load DB records and convert them to a JSON data, you don't need to write any
SELECT or
JOIN query. You also do not need to consider any performance tuning. Just write down the
ORM -> JSON conversion plan, then
safe-typeorm will do everything.
The
JsonSelectBuilder is the class doing everything. It will analyze your JSON conversion plan, and compose the JSON conversion method automatically with the exact JSON type what you want. Furthermore, the
JsonSelectBuilder finds the best (applicataion level) joining plan by itself, when being constructed.
Below code is an example converting ORM model class instances to JSON data with the
JsonSelectBuilder. As you can see, there's no special script in the below code, but only the conversion plan is. As I've mentioned,
JsonSelectBuilder will construct the exact JSON type by analyzing your conversion plan. Also, the performance tuning would be done automatically.
Therefore, just enjoy the
JsonSelectBuilder without any worry.
export async function test_json_select_builder(models: BbsGroup[]): Promise<void> { const builder = BbsGroup.createJsonSelectBuilder ({ articles: BbsArticle.createJsonSelectBuilder ({ group: safe.DEFAULT, // ID ONLY category: BbsCategory.createJsonSelectBuilder ({ parent: "recursive" as const, // RECURSIVE JOIN }), tags: BbsArticleTag.createJsonSelectBuilder ( {}, tag => tag.value // OUTPUT CONVERSION BY MAPPING ), contents: BbsArticleContent.createJsonSelectBuilder ({ files: "join" as const }), }) }); // GET JSON DATA FROM THE BUILDER const raw = await builder.getMany(models); // THE RETURN TYPE IS ALWAYS EXACT // THEREFORE, TYPEOF "RAW" AND "I-BBS-GROUP" ARE EXACTLY SAME const regular: IBbsGroup[] = raw; const inverse: typeof raw = regular; }
Insert CollectionInsert Collection
When you want to execute
INSERT query for lots of records of plural tables, you've to consider dependency relationships. Also, you may construct extended SQL query manually by yourself, if you're interested in the performance tuning.
However, with the
InsertCollection class provided by this
safe-typeorm, you don't need to consider any dependcy relationship. You also do not need to consider any performance tuning. The
InsertCollection will analyze the dependency relationships and orders the insertion sequence automatically. Also, the
InsertCollection utilizes the extended insertion query for the optimizing performance.
import safe from "safe-typeorm"; import std from "tstl"; export async function archive ( comments: BbsComment[], questions: BbsQuestionArticle[], reviews: BbsArticleReview[], groups: BbsGroup[], files: AttachmentFile[], answers: BbsAnswerArticle[], categories: BbsCategory[], comments: BbsComment[], articles: BbsArticle[], contents: BbsArticleContent[], tags: BbsArticleTag[], ): Promise<void> { // PREPARE A NEW COLLECTION const collection: safe.InsertCollection = new safe.InsertCollection(); // PUSH TABLE RECORDS TO THE COLLECTION WITH RANDOM SHULFFLING const massive = [ comments, questions, reviews, groups, files, answers, comments, articles, contents, tags ]; std.ranges.shuffle(massive); for (const records of massive) collection.push(records); // PUSH INDIVIDUAL RECORDS for (const category of categories) collection.push(category); // EXECUTE THE INSERT QUERY await collection.execute(); }
AppendixAppendix
TypeORMTypeORM
I've awaited next version of the
typeorm for many years, and I can't wait no more.
So I've decided to implement the next version by myself. I'd wanted to contribute to this
typeorm after the next version implementation has been completed, but it was not possible by critical change on the relationship definition like
Has.OneToMany or
Belongs.ManyToOne. Therefore, I've published the next version as a helper library of the
typeorm.
I dedicate this
safe-typeorm to the
typeorm. If developers of the
typeorm accept the critical change on the relationship definition, it would be the next version of the
typeorm. Otherwise they reject, this
safe-typeorm would be left as a helper library like now.
NestiaNestia
nestia is another library what I've developed, automatic SDK generator for the NestJS backend server. With those
safe-typeorm and nestia, you can reduce lots of costs and time for developing the backend server.
When you're developing a backend server using the
NestJS, you don't need any extra dedication, for delivering the Rest API to the client developers, like writing the
swagger comments. You just run the nestia up, then nestia would generate the SDK automatically, by analyzing your controller classes in the compliation and runtime level.
With the automatically generated SDK through the nestia, client developer also does not need any extra work, like reading
swagger and writing the duplicated interaction code. Client developer only needs to import the SDK and calls matched function with the
await symbol.
import api from "@samchon/bbs-api"; import { IBbsArticle } from "@samchon/bbs-api/lib/structures/bbs/IBbsArticle"; import { IPage } from "@samchon/bbs-api/lib/structures/common/IPage"; export async function test_article_read(connection: api.IConnection): Promise<void> { // LIST UP ARTICLE SUMMARIES const index: IPage<IBbsArticle.ISummary> = await api.functional.bbs.articles.index ( connection, "free", { limit: 100, page: 1 } ); // READ AN ARTICLE DETAILY const article: IBbsArticle = await api.functional.bbs.articles.at ( connection, "free", index.data[0].id ); console.log(article.title, aritlce.body, article.files); }
ArchidrawArchidraw
I have special thanks to the Archidraw, where I'm working for.
The Archidraw is a great IT company developing 3D interior editor and lots of solutions based on the 3D assets. Also, the Archidraw is the first company who had adopted
safe-typeorm on their commercial backend project, even
safe-typeorm was in the alpha level. | https://www.npmjs.com/package/safe-typeorm | CC-MAIN-2022-05 | en | refinedweb |
Hello All,
I am currently trying to get gnuradio-core running on an Intel
MacBook. I had a go at installing gnuradio-core today, and after much
hacking managed to get close (but not quite all the way).
Here is a brief summary of my progress (hopefully this will be useful
to someone!).
I am using a MacBook 2 GHz Intel Core Duo running Mac OS X 10.4.6 and
using gcc 4.0.1 to build.
I started off with Jon’s excellent web page:
As much as possible, I tried to use Darwin ports packages rather than
install source from scratch (convenience rather than anything else).
I found I could install the following pre-requisites from Darwin
Ports: subversion, autonconf, automake, libtool, pkgconfig, swig,
boost, boost-jam, and cppunit.
Python24 died as did Numeric and FFTW. FFTW was an issue with the
latest version 3.1.1 and gcc 4.0.1. There was a workaround, but it
was a bit kludgy and involved disabling all optimizations during the
compilation. I submitted a bug report to Darwin Ports and the FFTW
folks, so hopefully they’ll look into it. I still need to look into
why the Python package didn’t work.
I installed the following packages from source tarballs: fftw3.0.1,
numeric, and python24. FFTW I installed using the --enable-float and
–disable-fma configure options. There were no problems compiling
version 3.0.1.
My goal was to get gnuradio-core installed, so I stopped there as far
as pre-requisites. Next I was on to compiling and installing GNU
Radio Core.
I checked out the source, and went through the usual bootstrap,
configure, compile cycle.
There were a few gotchas here:
As Jan had pointed out in an earlier post “.align 16” doesn’t work
too well
on the Intel Macs, so I converted to “.align 4” for all of the source
files
in src/lib/filter.
There was a write permissions error for “Makefile.gen” and
“general_generated_i” so I chmoded these files to allow user write.
After all of this, compilation went through to almost the last stage,
when I got the message at the bottom of the email. I’m going to leave
it at this for now. Any ideas/insights are most welcome!
I have put together some scripts to automate most of the installation
steps. I’d be happy to pass them on to anyone who would find them
useful. I am also happy to test out anyone else’s installation scripts.
Cheers,
Dave.
g++ -DHAVE_CONFIG_H -I. -I. -I…/… -g -O2 -Wall -Woverloaded-
virtual -c bug_work_around_6.cc -MT bug_work_around_6.lo -MD -MP -
MF .deps/bug_work_around_6.TPlo -fno-common -DPIC -o .libs/
bug_work_around_6.o
bug_work_around_6.cc:3: warning: ‘gr_bug_work_around_6’ defined but
not used
/bin/sh …/…/libtool --mode=link g++ -g -O2 -Wall -Woverloaded-
virtual -o libgnuradio-core.la -rpath /Users/dl99/Documents/
projects/svpn/build/gr/lib -version-info 0:0:0 bug_work_around_6.lo
filter/libfilter.la g72x/libccitt.la general/libgeneral.la io/
libio.la missing/libmissing.la omnithread/libomnithread.la reed-
solomon/librs.la runtime/libruntime.la -L/Users/dl99/Documents/
projects/svpn-cm/build-scripts/…/…/svpn/build/extern/lib -lfftw3f -lm
g++ -dynamiclib -single_module -flat_namespace -undefined suppress -
o .libs/libgnuradio-core.0 .libs/bug_work_around_6.o -all_load
filter/.libs/libfilter.a g72x/.libs/libccitt.a general/.libs/
libgeneral.a io/.libs/libio.a missing/.libs/libmissing.a
omnithread/.libs/libomnithread.a reed-solomon/.libs/librs.a
runtime/.libs/libruntime.a -L/Users/dl99/Documents/projects/svpn-cm/
build-scripts/…/…/svpn/build/extern/lib /Users/dl99/Documents/
projects/svpn-cm/build-scripts/…/…/svpn/build/extern/lib/
libfftw3f.a -L/Users/dl99/Documents/projects/svpn/build/gr/lib -L/opt/
local/lib -lm -install_name /Users/dl99/Documents/projects/svpn/
build/gr/lib/libgnuradio-core.0 -Wl,-compatibility_version -Wl,1 -Wl,-
current_version -Wl,1.0
ld: warning -L: directory name (/Users/dl99/Documents/projects/svpn/
build/gr/lib) does not exist
ld: multiple definitions of symbol ___divdi3
/usr/lib/gcc/i686-apple-darwin8/4.0.1/libgcc.a(_divdi3.o) private
external definition of ___divdi3 in section (__TEXT,__text)
/usr/lib/gcc/i686-apple-darwin8/4.0.1/…/…/…/libgcc_s.10.4.dylib
(_divdi3_s.o) definition of ___divdi3
ld: multiple definitions of symbol ___udivdi3
/usr/lib/gcc/i686-apple-darwin8/4.0.1/libgcc.a(_udivdi3.o) private
external definition of ___udivdi3 in section (__TEXT,__text)
/usr/lib/gcc/i686-apple-darwin8/4.0.1/…/…/…/libgcc_s.10.4.dylib
(_udivdi3_s.o) definition of ___udiv
/usr/bin/libtool: internal link edit command failed
make[4]: *** [libgnuradio-core.la] Error 1
make[3]: *** [all-recursive] Error 1
make[2]: *** [all-recursive] Error 1
make[1]: *** [all-recursive] Error 1
make: *** [all] Error 2 | https://www.ruby-forum.com/t/re-intel-mac-gnu-radio-install-update-soon/62247 | CC-MAIN-2022-05 | en | refinedweb |
Week 01 Tutorial Questions
Class introduction (for everyone, starting with the tutor):
- Please turn on your camera for the introduction, and for all your COMP1521 tut-labs,
if you can and you are comfortable with this.
We understand everyone can be having a difficult day, week or year so
having your webcam on is optional in online COMP1521 tut-labs,
unless you have a cute pet in which case it's required, but you only need show the pet.
- What is your preferred name (what should we call you?)
- What other courses are you doing this term
- What parts of C from COMP1511/COMP1911 were the hardest to understand?
- Do you know any good resources to help students who have forgotten their C? For example:
- Consider the following C program skeleton:
int a; char b[100]; int fun1() { int c, d; ... } double e; int fun2() { int f; static int ff; ... fun1(); ... } int g; int main(void) { char h[10]; int i; ... fun2() ... }
Now consider what happens during the execution of this program and answer the following:
Which variables are accessible from within
main()?
Which variables are accessible from within
fun2()?
Which variables are accessible from within
fun1()?
Which variables are removed when
fun1()returns?
Which variables are removed when
fun2()returns?
How long does the variable
fexist during program execution?
How long does the variable
gexist during program execution?
- Explain the differences between the properties of the variables
s1and
s2in the following program fragment:
#include <stdio.h> char *s1 = "abc"; int main(void) { char *s2 = "def"; // ... }
Where is each variable located in memory? Where are the strings located?
- C's sizeof operator is a prefix unary operator (precedes its 1 operand) - what are examples of other C unary operators?
- Why is C's sizeof operator different to other C unary & binary operators?
- Discuss errors in this code:
struct node *a = NULL: struct node *b = malloc(sizeof b); struct node *c = malloc(sizeof struct node); struct node *d = malloc(8); c = a; d.data = 42; c->data = 42;
- What is a pointer? How do pointers relate to other variables?
Consider the following small C program:
#include <stdio.h> int main(void) { int n[4] = { 42, 23, 11, 7 }; int *p; p = &n[0]; printf("%p\n", p); // prints 0x7fff00000000 printf("%lu\n", sizeof (int)); // prints 4 // what do these statements print ? n[0]++; printf("%d\n", *p); p++; printf("%p\n", p); printf("%d\n", *p); return 0; }
Assume the variable
nhas address
0x7fff00000000.
Assume
sizeof (int) == 4.
What does the program print?
Consider the following pair of variables
int x; // a variable located at address 1000 with initial value 0 int *p; // a variable located at address 2000 with initial value 0
If each of the following statements is executed in turn, starting from the above state, show the value of both variables after each statement:
p = &x;
x = 5;
*p = 3;
x = (int)p;
x = (int)&p;
p = NULL;
*p = 1;
If any of the statements would trigger an error, state what the error would be.
Consider the following C program:
#include <stdio.h> int main(void) { int nums[] = {3, 1, 4, 1, 5, 9, 2, 6, 5, 3}; for (int i = 0; i < 10; i++) { printf("%d\n", nums[i]); } return 0; }
This program uses a
for loopto print each element in the array
Rewrite this program using a recursive function
- What is a struct? What are the differences between structs and arrays?
Define a struct that might store information about a pet.
The information should include the pet's name, type of animal, age and weight.
Create a variable of this type and assign information to it to represent an axolotl named "Fluffy" of age 7 that weighs 300grams.
- Write a function that increases the age of fluffy by one and then increases its weight by the fraction of its age that has increased. The function is defined like this:
void age_fluffy(struct pet *my_pet);
e.g.: If fluffy goes from age 7 to age 8, it should end up weighing 8/7 times the amount it weighed before. You can store the weight as an int and ignore any fractions.
Show how this function can be called by passing the address of a struct variable to the function.
- Write a main function that takes command line input that fills out the fields of the pet struct. Remember that command line arguments are given to our main function as an array of strings, which means we'll need something to convert strings to numbers.
- Consider the following C program:What will happen when the above program is compiled and executed?
#include <stdio.h> int main(void) { char str[10]; str[0] = 'H'; str[1] = 'i'; printf("%s", str); return 0; }
- How do you correct the program.
For each of the following commands, describe what kind of output would be produced:
gcc -E x.c
gcc -S x.c
gcc -c x.c
gcc x.c
Use the following simple C code as an example:
#include <stdio.h> #define N 10 int main(void) { char str[N] = { 'H', 'i', '\0' }; printf("%s\n", str); return 0; }
Consider the following (working) C code to trim whitespace from both ends of a string:
// COMP1521 21T2 GDB debugging example #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <assert.h> void trim(char *str); char **tokenise(char *str, char *sep); void freeTokens(char **toks); int main(int argc, char **argv) { if (argc != 2) exit(1); char *string = strdup(argv[1]); printf("Input: \"%s\"\n", string); trim(string); printf("Trimmed: \"%s\"\n", string); char **tokens = tokenise(string, " "); for (int i = 0; tokens[i] != NULL; i++) printf("tok[%d] = \"%s\"\n", i, tokens[i]); freeTokens(tokens); return 0; } // trim: remove leading/trailing spaces from a string void trim(char *str) { int first, last; first = 0; while (isspace(str[first])) first++; last = strlen(str)-1; while (isspace(str[last])) last--; int i, j = 0; for (i = first; i <= last; i++) str[j++] = str[i]; str[j] = '\0'; } // tokenise: split a string around a set of separators // create an array of separate strings // final array element contains NULL char **tokenise(char *str, char *sep) { // temp copy of string, because strtok() mangles it char *tmp; // count tokens tmp = strdup(str); int n = 0; strtok(tmp, sep); n++; while (strtok(NULL, sep) != NULL) n++; free(tmp); // allocate array for argv strings char **strings = malloc((n+1)*sizeof(char *)); assert(strings != NULL); // now tokenise and fill array tmp = strdup(str); char *next; int i = 0; next = strtok(tmp, sep); strings[i++] = strdup(next); while ((next = strtok(NULL,sep)) != NULL) strings[i++] = strdup(next); strings[i] = NULL; free(tmp); return strings; } // freeTokens: free memory associated with array of tokens void freeTokens(char **toks) { for (int i = 0; toks[i] != NULL; i++) free(toks[i]); free(toks); }
You can grab a copy of this code as trim.c.
The part that you are required to write (i.e., would not be part of the supplied code) is highlighted in the code.
Change the code to make it incorrect. Run the code, to see what errors it produces, using this command:
gcc -std=gnu99 -Wall -Werror -g -o trim trim.c ./trim " a string "
Then use GDB to identify the location where the code "goes wrong".
Revision questions
The following questions are primarily intended for revision, either this week or later in session.
Your tutor may still choose to cover some of these questions, time permitting. | https://cgi.cse.unsw.edu.au/~cs1521/21T3/tut/01/questions | CC-MAIN-2022-05 | en | refinedweb |
use strict; use warnings; package Text::Wrap; use warnings::register; BEGIN { require Exporter; *import = \&Exporter::import } our @EXPORT = qw( wrap fill ); our @EXPORT_OK = qw( $columns $break $huge ); our $ (to break before spaces or colons) or a pre-compiled regexp such as C<qr/[\s']/> (to break before spaces or apostrophes). The default is simply C<'\s'>; that is, words are terminated by spaces. (This means, among other things, that trailing punctuation such as full stops or commas stay with the word they are "attached" to.) Setting C<$Text::Wrap::break> to a regular expression that doesn't eat any characters (perhaps just a forward look-ahead assertion) will cause warnings. Beginner note: In example 2, above C<$columns> is imported into the local namespace, and set locally. In example 3, C<$Text::Wrap::columns> is set in its own namespace without importing it. C<Text::Wrap::wrap()> starts its work by expanding all the tabs in its input into spaces. The last thing it does it to turn spaces back into tabs. If you do not want tabs in your results, set C<$Text::Wrap::unexpand> to a false value. Likewise if you do not want to use 8-character tabstops, set C<$Text::Wrap::tabstop> to the number of characters you do want for your tabstops. If you want to separate your lines with something other than C<\n> then set C<$Text::Wrap::separator> to your preference. This replaces all newlines with C<$Text::Wrap::separator>. If you just want to preserve existing newlines but add new breaks with something else, set C<$Text::Wrap::separator2> instead. When words that are longer than C<$columns> are encountered, they are broken up. C<wrap()> adds a C<"\n"> at column C<$columns>. This behavior can be overridden by setting C<$huge> to 'die' or to 'overflow'. When set to 'die', large words will cause C<die()> to be called. When set to 'overflow', large words will be left intact. Historical notes: 'die' used to be the default value of C<$huge>. Now, 'wrap' is the default value. =head1 EXAMPLES" =head1 SEE ALSO For correct handling of East Asian half- and full-width characters, see L<Text::WrapI18N>. For more detailed controls: L<Text::Format>. =head1 AUTHOR David Muir Sharnoff <cpan@dave.sharnoff.org> with help from Tim Pierce and many many others. =head1 LICENSE. | https://web-stage.metacpan.org/release/ARISTOTLE/Text-Tabs+Wrap-2021.0814/source/lib.modern/Text/Wrap.pm | CC-MAIN-2022-05 | en | refinedweb |
StaticInjectorError(Platform: core)[QuestionsComponent -> QuestionServiceProxy]:
NullInjectorError: No provider for QuestionServiceProxy!.
I searched over the internet about possible fixes and everyone was saying that you need to import the component which was already imported as
import { QuestionServiceProxy, QuestionDto, PagedResultDtoOfQuestionDto } from '@shared/service-proxies/service-proxies';
The service-proxies also had QuestionServiceProxy which made it ver confusing that why I was getting the error. What I missed is the service.proxy.module.ts where I need to also include it using @NgModule as shown below :
@NgModule({ providers: [ ApiServiceProxies.RoleServiceProxy, ApiServiceProxies.SessionServiceProxy, ApiServiceProxies.TenantServiceProxy, ApiServiceProxies.UserServiceProxy, ApiServiceProxies.QuestionServiceProxy, ApiServiceProxies.TokenAuthServiceProxy, ApiServiceProxies.AccountServiceProxy, ApiServiceProxies.ConfigurationServiceProxy, { provide: HTTP_INTERCEPTORS, useClass: AbpHttpInterceptor, multi: true } ] }) export class ServiceProxyModule { }
Thus it fixed the issue. | https://www.codingdefined.com/2018/10/how-i-solved-nullinjectorerror-no.html | CC-MAIN-2020-05 | en | refinedweb |
The code for this homework can be found here. The file you will edit and submit for this homework is
r2d2_hw4.py.
This assignment will focus on natural language processing (NLP). NLP is a vibrant subfield of artificial intelligence. One of the goals of NLP is to allow computers to understand commands spoken in human language. This enables technologies like Amazon Alexa, Apple’s Siri or Google’s Assistant.
Instead of issuing a command to your droid in Python like
droid.roll(speed=0.5, heading=0, duration=2)
we are going to implement an NLP system that will allow you to say
"Drive straight ahead for 2 seconds at half speed"
Our NLP system will have three main components:
We’re going to begin this assignment by brainstorming different commands that we might like to give to our robot. We’ll take several factors into account:
The type of actions that our R2D2s can perform are dictated by its Python API. You can see a list of the commands in the API like this:
from client import DroidClient droid = DroidClient() droid.scan() droid.connect_to_droid('D2-55A2') # Replace D2-55A2 with your droid's ID help(droid)
Let’s put the API commands that
help lists into different groups. We’ll also list natural language commands that might be associated with each group. For the first part of this assignment, you will brainstrom 10 unique language commands for each group. You will submit your sentences along with your code.
enter_drive_mode(self) roll(self, speed, angle, time) turn(self, angle, **kwargs) update_position_vector(self, speed, angle, time) roll_time(self, speed, angle, time, **kwargs) roll_continuous(self, speed, angle, **kwargs) restart_continuous_roll(self) stop_roll(self, **kwargs)
driving_sentences = [ "Go forward for 2 feet, then turn right.", "North is at heading 50 degrees.", "Go North.", "Go East.", "Go South-by-southeast", "Run away!", "Turn to heading 30 degrees.", "Reset your heading to 0", "Turn to face North.", "Start rolling forward.", "Increase your speed by 50%.", "Turn to your right.", "Stop.", "Set speed to be 0.", "Set speed to be 20%", "Turn around", ]
set_back_LED_color(self, r, g, b) set_front_LED_color(self, r, g, b) set_holo_projector_intensity(self, intensity) set_logic_display_intensity(self, intensity)
light_sentences = [ "Change the intensity on the holoemitter to maximum.", "Turn off the holoemitter.", "Blink your logic display.", "Change the back LED to green.", "Turn your back light green.", "Dim your lights holoemitter.", "Turn off all your lights.", "Lights out.", "Set the RGB values on your lights to be 255,0,0.", "Add 100 to the red value of your front LED.", "Increase the blue value of your back LED by 50%.", "Display the following colors for 2 seconds each: red, orange, yellow, green, blue, purple.", "Change the color on both LEDs to be green.", ]
rotate_head(self, angle)
head_sentences = [ "Turn your head to face forward.", "Look behind you.", ]
angle = 0 awake = False back_LED_color = (0, 0, 0) battery(self) connected_to_droid = False continuous_roll_timer = None drive_mode = False drive_mode_angle = None drive_mode_shift = None drive_mode_spreed = None front_LED_color = (0, 0, 0) holo_projector_intensity = 0 logic_display_intensity = 0 stance = 2 waddling = False
state_sentences = [ "What color is your front light?", "Tell me what color your front light is set to.", "Is your logic display on?", "What is your stance?" "What is your orientation?", "What direction are you facing?", "Are you standing on 2 feet or 3?", "What is your current heading?", "How much battery do you have left?", "What is your battery status?", "Are you driving right now?", "How fast are you going?", "What is your current speed?", "Is your back light red?", "Are you awake?", ]
connect_to_R2D2(self) connect_to_R2Q5(self) disconnect(self) scan(self) exit(self)
connection_sentences = [ "Connect D2-55A2 to the server", "Are there any other droids nearby?", "Disconnect.", "Disconnect from the server.", ]
set_stance(self, stance, **kwargs) set_waddle(self, waddle)
stance_sentences = [ "Set your stance to be biped.", "Put down your third wheel.", "Stand on your tiptoes.",]
animate(self, i, wait=3) play_sound(self, soundID, wait=4)
animation_sentences = [ "Fall over", "Scream", "Make some noise", "Laugh", "Play an alarm",]
The following grid navigation commands are from the Droid navigation assignment, not the provided API. We will support grid navigation commands too.
Graph(vertics, edges) A_star(G, start, goal) path2move(path)
grid_sentences = [ "You are on a 4 by 5 grid.", "Each square is 1 foot large.", "You are at position (0,0).", "Go to position (3,3).", "There is an obstacle at position 2,1.", "There is a chair at position 3,3", "Go to the left of the chair.", "It’s not possible to go from 2,2 to 2,3.", ]
For each of the 8 categories of commands please create 10 unique sentences on how you might tell the robot to execute one or more of the actions in that category. You can add add your sentence lists to the code by adding them as arrays called
my_driving_sentences,
my_light_sentences,
my_head_sentences,
my_state_sentences,
my_connection_sentences,
my_stance_sentences,
my_animation_sentences, and
my_grid_sentences.
One of the amazing thing about language is that there are many different ways of communicating the same intent. For example, if we wanted to have our R2D2 start waddling, we could say
"waddle", "totter", "todder", "teater", "wobble", "start to waddle" "start waddling", "begin waddling", "set your stance to waddle", "try to stand on your tiptoes", "move up and down on your toes", "rock from side to side on your toes", "imitate a duck's walk", "walk like a duck"
Similarly, if we wanted it to stop, we could prefix the command above with a bunch of ways of saying stop:
"stop your waddle", "end your waddle", "don't waddle anymore", "stop waddling", "cease waddling", "stop standing on your toes", "stand still" "stop acting like a duck", "don't walk like a duck", "stop teetering like that" "put your feet flat on the ground"
The goal of this part of the assignment is to enumerate as many ways of saying a command as you can think of (minimum of 10 per command group). We will use these to train an intent detection module.
In this section, we will take in a new sentence that we have never seen before and try to classify what type of command the user wants to have the the robot execute. To do so, we will measure the similarity of the user’s new sentence with each of our training sentences. We know what command group each of our training sentences belongs to, so we will find the nearest command sentences to the new sentence, and use their labels as the label of the new sentence. This is called $k$-nearest neighbor classification. The label that we will assign will be
driving,
light,
head,
state,
connection,
stance,
animation, or
grid.
To calculate how similar two sentences are, we are going to leverage word embeddings that we dicussed in lecture (and that are described in the Vector Semantics and Embeddings chapter of the Jurafsky and Martin textbook). We will use pre-trained word2vec embeddings, and use the Magnitude python package to work with these embeddings. Then, we will use the embeddings for the words in a sentence to create sentence embeddings.
[5 points] Write a tokenization function
tokenize(text) which takes as input a string of text and returns a list of tokens derived from that text. Here, we define a token to be a contiguous sequence of non-whitespace characters. We will remove punctuation marks and convert the text to lowercase. Hint: Use the built-in constant
string.punctuation, found in the
string module, and/or python’s regex library,
re.
>>> tokenize(" This is an example. ") ['this', 'is', 'an', 'example' ]
>>> tokenize("'Medium-rare,' she said.") ['medium', 'rare', 'she', 'said']
[5 points] Implement the cosine similarity fuction to compute how similar two vectors are. Here is the mathmatical definition of the different parts of the cosine function. The dot product between two vectors and is:
The vector length of a vector is defined as:
The cosine of the angles between and is:
Here represents the angle between and .
Implement a cosine similarity function
cosineSimilarity(vector1, vector2), where
vector1 and
vector2 are numpy arrays. Your function should return the cosine of the angles between them. You are welcome to use any of the built-in numpy functions. If you don’t have numpy installed on your computer already, you should run
pip install numpy.
Here are some examples of what your method should output:
import numpy as np
>>> cosineSimilarity(np.array([2, 0]), np.array([0, 1])) 0.0 >>> cosineSimilarity(np.array([1, 1]), np.array([1, 1])) 0.9999999999999998. # It's actually 1.0, but this is close enough. >>> cosineSimilarity(np.array([10, 1]), np.array([1, 10])) 0.19801980198019803 >>> v1 = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) >>> v2 = np.array([9, 8, 7, 6, 5, 4, 3, 2, 1, 0]) >>> cosineSimilarity(v1, v2) 0.4210526315789473
pip3 install pymagnitude
Next, you’ll need to download a pre-trained set of word embeddings. We’ll get a set trained with Google’s word2vec algorithm, which we discussed in class. You can download them by clicking on this link or by using this command in your terminal:
wget
Warning: the file is very large (5GB). If you’d like to experiment with another set of word vectors that is smaller, you can download these GloVE embeddings which are only 1.4GB.
After the file downloads, you can access the vectors like this:
from pymagnitude import * path = '/Users/ccb/Downloads/' # Change this to where you downloaded the file. vectors = Magnitude(path + "GoogleNews-vectors-negative300.magnitude") v = vectors.query("cat") # vector representing the word 'cat' w = vectors.query("dog") # vector representing the word 'dog' # calculate the cosine similarity with your implementation sim = cosineSimilarity(v, w) print(sim)
If you implemented the cosine similarity function properly, and if you loaded the vectors from the
GoogleNews-vectors-negative300.magnitude file, you should get 0.76094574. If you loaded the vectors from the
glove.6B.300d.magnitude file you should get 0.6816747.
[0 points] In the
WordEmbeddings class, write an initialization method
__init__(self, file_path) that creates a
Magnitude object from the path specified by the input, and stores it internally for future use.
[10 points] Implement the function
calcSentenceEmbeddingBaseline(self, sentence) in the
WordEmbeddings class that takes in a sentence and returns a vector embedding for that sentence, using the
Magnitude object stored in your initialization method. If the sentence has no words, you should return a vector of all zeros with the same number of dimensions as a word in the Magnitude vectors.
For
calcSentenceEmbeddingBaseline(self, sentence) you should return a component-wise addition of all of the vectors. All the word vectors will be equal in length. You will return a sentence vector that is also that length. The first component of your sentence vector will be the addition of the the first component of each of the words. Easy right?
Here’s an example of the output you would get
>>> X = WordEmbeddings("/Users/ccb/Downloads/GoogleNews-vectors-negative300.magnitude") # Change this to where you downloaded the file. >>> svec1 = X.calcSentenceEmbeddingBaseline("drive forward") >>> svec2 = X.calcSentenceEmbeddingBaseline("roll ahead") >>> svec3 = X.calcSentenceEmbeddingBaseline("set your lights to purple") >>> svec4 = X.calcSentenceEmbeddingBaseline("turn your lights to be blue") >>> cosineSimilarity(svec1, svec2) 0.4255210604304939 >>> cosineSimilarity(svec1, svec3) 0.20958250895677447 >>> cosineSimilarity(svec1, svec4) 0.30474097280886364 >>> cosineSimilarity(svec2, svec3) 0.24962558300148688 >>> cosineSimilarity(svec2, svec4) 0.27946534951158214 >>> cosineSimilarity(svec3, svec4) 0.8081137933660256
The baseline sentence embedding method assumes that all the words in the sentence have the same importance.
[10 points] We have provided a txt file of training sentences for the R2D2s in a file named r2d2TrainingSentences.txt, as well as a function,
loadTrainingSentences(file_path), which reads the file and returns a dictionary with keys
[category] which map to a list of the sentences belonging to that category.
>>> trainingSentences = loadTrainingSentences("data/r2d2TrainingSentences.txt") >>> trainingSentences['animation'] ['make a gesture', 'speak', 'Play sound number 3.', 'Stop dancing.', 'set off your alarm', ... ]
In the
WordEmbeddings class, write a function
sentenceToEmbeddings(self, commandTypeToSentences) that converts every sentence in the dictionary returned by
loadTrainingSentences(file_path) to an embedding. You should return a tuple of two elements. The first element is an m by n numpy array, where m is the number of sentences and n is the length of the vector embedding. Row i of the array should contain the embedding for sentence i. The second element is a dictionary mapping from the index of the sentence to a tuple where the first element is the original sentence, and the second element is a category, such as “driving”. The order of the indices does not matter, but the indices of the matrix and the dictionary should match i.e., sentence j should have an embedding in the jth row of the matrix, and should have itself and its category mapped onto by key j in the dictionary.
>>> trainingSentences = loadTrainingSentences("data/r2d2TrainingSentences.txt") >>> X = WordEmbeddings("/Users/ccb/Downloads/GoogleNews-vectors-negative300.magnitude") # Change this to where you downloaded the file. >>> sentenceEmbeddings, indexToSentence = X.sentenceToEmbeddings(trainingSentences) >>> sentenceEmbeddings[14:] array([[ 0.08058001, 0.21676847, -0.06604716, ..., -0.03767369, 0.15602297, -0.07835222], [ 0.0350151 , 0.07319701, 0.0894349 , ..., -0.0442058 , -0.0910254 , 0.00273301], [-0.04938643, 0.2280895 , 0.24541894, ..., -0.16277108, 0.00430368, -0.45862231], ..., [ 0.25111231, 0.33453143, 0.18835592, ..., -0.05870331, -0.02659047, -0.47405607], [ 0.20804575, 0.07450815, 0.21608222, ..., 0.09974989, 0.38724095, -0.41757214], [ 0.1263006 , -0.2014823 , 0.17403649, ..., -0.01363612, -0.1347626 , 0.0201975 ]]) >>> indexToSentence[239] ('Turn to heading 50 degrees.', 'driving')
[10 points] Now, given an arbitrary input sentence, and an m by n matrix of sentence embeddings, write a function
closestSentence(self, sentence, sentenceEmbeddings) that returns the index of the closest sentence to the input. This should be the row vector which is closest to the sentence vector of the input. Depending on the indices of your implementation of
sentenceToEmbeddings(self, commandTypeToSentences), the following output may vary.
>>> sentenceEmbeddings, _ = X.sentenceToEmbeddings(loadTrainingSentences("data/r2d2TrainingSentences.txt")) >>> X.closestSentence("Lights on.", sentenceEmbeddings) 301
[25 points] Now, given an arbitrary input sentence, and a file path to r2d2 commands, write a function
getCategory(self, sentence, file_path) that returns the category that that sentence should belong to. You should also map sentences that don’t really fit into any of the categories to a new category, “no”, and return “no” if the input sentence does not really fit into any of the categories.
Simply finding the closest sentence and outputting that category may not be enough for this function. We suggest trying out a k-nearest neighbors approach, and scoring the neighbors in some way to find which category is the best fit. You can write new helper functions to help out. Also, which kind of words appear in almost all sentences and so are not a good way to distinguish between sentence meanings?
>>> X.getCategory("Turn your lights green.", "data/r2d2TrainingSentences.txt") 'light' >>> X.getCategory("Drive forward for two feet.", "data/r2d2TrainingSentences.txt") 'driving' >>> X.getCategory("Do not laugh at me.", "data/r2d2TrainingSentences.txt") 'no'
Your implementation for this function can be as free as you want. We will test your function on a test set of sentences. Our training set will be ` r2d2TrainingSentences.txt
, and our test set will be similar to the development set called r2d2DevelopmentSentences.txt` which we have provided for testing your implementation locally (however, there will be differences, so try not to overfit!). Your accuracy will be compared to scores which we believe are relatively achievable. Anything greater than or equal to a 90% accuracy on the test set will receive a 100%, and anything lower than a 80% accuracy will receive no partial credit. To encourage friendly competition, we have also set up a leaderboard so that you can see how well you are doing against peers.
When testing this function, we will be passing the same
file_path over and over again to
getCategory. We do not want our function to have to calculate the sentence embeddings of sentences in
file_path repeatedly. Thus, modify
getCategory so that we do not have to perform repeat operations when passing in the same
file_path (you can change the
__init__ function as well). We will test this by setting strict runtime bounds for our
getCategory and
accuracy tests.
[5 points] To help you with your implementation of
getCategory, we require that you fill out the code stub for
accuracy(self, training_file_path, dev_file_path). This function should test your implementation of
getCategory faithfully using paths to training and development sets as input. Don’t worry about the efficiency of this function! Located in the
data folder is a development set
r2d2DevelopmentSentences.txt which we have provided for testing your implementation of
getCategory locally.
>>> X.accuracy("data/r2d2TrainingSentences.txt", "data/r2d2DevelopmentSentences.txt") 0.9041095890410958
Note Before you submit, you need to indicate which Magnitude file you decide to use for your
getCategory function. If you decide on using the Google Word2Vec vectors, change the
magnitudeFile variable at the beginning of Section 2 to
"google". If you decide that you like the GloVE vectors better, change the
magnitudeFile variable to
"glove". Doing so is very important, as this may change how accurate your
getCategory function is.
Now that we have a good idea which categories our commands belong to, we have to find a way to convert these commands to actions. This can be done via slot-filling, which fills slots in the natural language command corresponding to important values. For example, given the slots NAME, RESTAURANT, TIME and HAS_RESERVED, and a command to a chat-bot such as “John wants to go to Olive Garden”, the chat-bot should fill out the slots with values: {NAME: John, RESTAURANT: Olive Garden, TIME: N/A, HAS_RESERVED: False}, and then it can decide to either execute the command or ask for more information given the slot-values.
[15 points] Using regex or word2vec vectors, populate the functions
lightParser(self, command) and
drivingParser(self, command) in the
WordEmbeddings class to perform slot-filling for the predefined slots, given string input
command. We will test these functions and give you full credit if you get above a 50% accuracy. These functions do not have to be perfect, but the better these functions are, the better your R2D2 will respond to your commands.
For
lightParser, the
lights slot refers to which lights the command refers to. It is a list with a combination of the strings
"front",
"back",
"holoEmit", and
"logDisp", corresponding to whether you believe the command refers to the front light, back light, holoemitter, or logic display, respectively. The order of these values does not matter. If the command wants to increase an RGB value, set the
add slot to true. If it wants to decrease an RGB value, set the
sub slot to true. The
on and
off fields correspond to whether the lights should be turned on or off (if the command is just changing the color of one of the RGB lights, these slots should not be changed), and should also respond to words like “maximum.”
For
drivingParser,
add and
sub correspond to whether the command wants you to increase/decrease the speed. This should be similar to the add and sub slots from the above
lightParser, except here you should also make sure these slots respond to words such as
faster and
slower. The
directions slot corresponds to an ordered list of all direction relevant words. Values in the directions list can only be one of
"go",
"turn",
"by", all cardinal directions (
"north",
"southwest", etc.), and relative directions (out of
"forward",
"back",
"left", and
"right"). Cardinal combinations found in the command, such as “South-by-southeast”, should be parsed to the
directions slot as
[..., "south", "by", "southeast",...]. The
"go" value in this list should also respond to word like
"drive" and
"roll", but be careful when using Word Embeddings here. ( What other value in the directions slot can be confused with
"go" if using cosine similarity? Is regex a better idea here? )
All string values should be lower-case.
Your functions should work like so:
>>> X.lightParser("Set your lights to maximum") {'lights': [], 'add': False, 'sub': False, 'on': True, 'off': False} >>> X.lightParser("Increase the red RGB value of your front light by 50.") {'lights': ['front'], 'add': True, 'sub': False, 'on': False, 'off': False} >>> X.lightParser("Turn your holoemitter on.") {'lights': ['holoEmit'], 'add': False, 'sub': False, 'on': True, 'off': False}
>>> X.drivingParser("Make your speed faster.") {'add': True, 'sub': False, 'directions': []} >>> X.drivingParser("Decrease your speed by 50%.") {'add': False, 'sub': True, 'directions': ["by"]} >>> X.drivingParser("Drive north-by-northwest.") {'add': False, 'sub': False, 'directions': ['go', 'north', 'by', 'northwest']} >>> X.drivingParser("Go forward for 2 seconds, then turn right.") {'add': False, 'sub': False, 'directions': ['go', 'forward', 'turn', 'right']}
Now that you are finished with the intent detection and slot filling sections, you can now use the code you have written to talk to your R2D2. Perform the R2D2 server setup instructions found in previous R2D2 homeworks, and move all your files over to your
sphero-project/src directory. Then, change the ID in line 15 of
robot_com.py to the ID of your robot, the path on line 16 of r2d2_commands.py to the path of your Magnitude file of choice (from this new directory), and on the command line run
python3 robot_com.py.
Try out commands like:
"Change your lights to red, periwinkle, azure, green, and magenta."
Have fun! Try not to be too mean to your robot :). ( Do not add sentences to the training data if you have not already finished the above sections, as this may change the local behavior of
getCategory. If you find sentences here that are parsed wrongly, feel free to add them to your example sentences as well! )
For More Extra Extra Credit Integrate Google Cloud Platform speech-to-text module so that you can command your robot using voice!
To run audio IO, you will need to install portaudio and pyaudio:
brew install portaudio pip3 install pyaudio
Next, you need to sign up for a Google Cloud Platform (GCP) account. When you register a new account, you’ll get 300 dollars of free credits. You have to enter your credit card information to sign up, but you will not be billed unless you exceed the 300 dollars limit, so make sure you keep your account information secure! (You may need to use a non-upenn Google account for this part.)
To enable the speech-to-text API, type ‘speech’ in the search bar, and select “Cloud Speech-to-Text API” from the drop-down menu. Click to enable the API, then click on the “Create Credentials” button. Select the “Cloud Speech-to-Text API” (you do not need the App Engine API), and when setting up roles, make yourself the role administrator. Then, you should be able to get a service account key file (this is going to be in .json format). Rename it
credentials.json and put it under the
sphero-project/src folder.
You may also need to install and set up Google Cloud SDK locally. To do this, follow the instructions located in the Quickstart documentation here. Make sure to follow all steps until you are finished with the
Initialize the SDK section. If during initialization you are asked which project to choose, choose the project that contains the API for speech-to-text.
Then, just install the Python client for the Google API, using:
pip3 install google-cloud-speech
Now, you should be able to run voice IO on your robot. As before, change the robot serial ID with your own in audio_io.py. Setup the R2D2 server as in previous homeworks, cd into the
sphero-project/src folder in another Terminal and type:
python3 audio_io.py
Note Depending on how you set up the SDK, you may need to run the following on the command line:
export GOOGLE_APPLICATION_CREDENTIALS="/[Path to sphero-project/src]/credentials.json"
before you can run audio_io.py.
Notes:
If you want to try audio IO, please try command line IO first.
If you are able to successfully run audio_io.py, say your command (using voice!) and see if text appears in the Terminal. To end the session, simply say any sentence containing one of the following keywords: “exit”, “quit”, “bye” or “goodbye”.
To receive extra credit for this portion, please come into office hours and show off your project to us! | http://artificial-intelligence-class.org/r2d2_assignments/hw4/homework4.html | CC-MAIN-2020-05 | en | refinedweb |
How to reuse cmake install for package() method¶
It is possible that your project’s CMakeLists.txt has already defined some functionality that extracts the artifacts (headers, libraries, binaries) from the build and source folder to a predetermined place.
The conan
package() method does exactly that: it defines which files
have to be copied from the build folder to the package folder.
If you want to reuse that functionality, you can do it with cmake.
Invoke cmake with
CMAKE_INSTALL_PREFIX using the
package_folder variable.
If the
cmake install target correctly copies all the required libraries, headers, etc. to the
package_folder,
then the
package() method is not required.
def build(self): cmake = CMake(self) cmake.configure() cmake.build() cmake.install() # equivalent to # args += ['-DCMAKE_INSTALL_PREFIX="%s"' % self.package_folder] # self.run('cmake "%s/src" %s %s' # % (self.source_folder, cmake.command_line, ' '.join( args ) ) ) # self.run("cmake --build . --target install %s" % cmake.build_config) def package(self): # nothing to do here now
The
package_info() method is still necessary, as there is no possible way to
automatically extract the information of the necessary libraries, defines and flags for different
build configurations from the cmake install. | https://docs.conan.io/en/1.4/howtos/cmake_install.html | CC-MAIN-2020-05 | en | refinedweb |
Class VarTypeAccess
A possibly qualified name that refers to a variable from inside a type.
This can occur as
- part of the operand to a
typeoftype, or
- as the first operand to a predicate type
For example, it may occur as the
E in these examples:
var x : typeof E function f(...) : E is T {} function f(...) : asserts E {}
In the latter two cases, this may also refer to the pseudo-variable
this.
Import path
import javascript | https://help.semmle.com/qldoc/javascript/semmle/javascript/TypeScript.qll/type.TypeScript$VarTypeAccess.html | CC-MAIN-2020-05 | en | refinedweb |
package Bat::Interpreter::Delegate::Executor::System; use utf8; use Moo; use namespace::autoclean; with 'Bat::Interpreter::Role::Executor'; our $VERSION = '0.020'; # VERSION sub execute_command { my $self = shift(); my $command = shift(); return system($command); } sub execute_for_command { my $self = shift(); my $command = shift(); my $output = `$command`; chomp $output; return $output; } 1; __END__ =pod =encoding utf-8 =head1 NAME Bat::Interpreter::Delegate::Executor::System =head1 VERSION version 0.020 =head1 SYNOPSIS use Bat::Interpreter; use Bat::Interpreter::Delegate::Executor::System; my $system_executor = Bat::Interpreter::Delegate::Executor::System->new; my $interpreter = Bat::Interpreter->new(executor => $system_executor); $interpreter->run('my.cmd'); =head1 DESCRIPTION Every command gets through system. So if you are in Linux using bash, bash will try to execute the command. This executor is as dumb and simple as it can, be cautious. =head1 NAME Bat::Interpreter::Delegate::Executor::PartialDryRunner - Executor for executing commands via perl system =head1 METHODS =head2 execute_command Execute general commands. This executor use perl system =head2 execute_for_command Execute commands for use in FOR expressions. This is usually used to capture output and implement some logic inside the bat/cmd file. This executor executes this commands via perl subshell: `` | https://metacpan.org/release/Bat-Interpreter/source/lib/Bat/Interpreter/Delegate/Executor/System.pm | CC-MAIN-2020-05 | en | refinedweb |
While browsing the Java tutorials, I discovered that there was one in particular, tic tac toe, that got viewed the most. When seeing that it was an older tutorial, and that it was only at the intermediate level, I decided I would make my own revised version. So, here we are. This tutorial is on how to make a tic tac toe game using the Java programming language developed by Sun Microsystems. This tutorial is designed to be as in detail and explanatory as possible. I hope you all enjoy what I have spent the last few days working on.
What you will find in this tutorial
Since this tutorial is on how to make a tic tac toe game, obviously first off we are going to be making a tic tac toe game. While telling you how to make it, I am going to try my best to explain what I’m doing, and why I am doing it. At the end of this tutorial I will also show you how to make a basic dynamic AI for single player game play. This is the game you will be creating:
What you should know beforehand
Before I start, I hope that you all know how to use Java, and are fairly adept at the language. If you are not so great, but do know a decent amount, I am going to try and explain my process as detailed as possible. I highly recommend using an IDE, as the game will be spread over multiple classes, and using an IDE helps the process of development tremendously.
Getting started
Okay, let’s get started. First off, if you are using an IDE, make a new project and call it whatever you please. Inside the new project, make sure you make the package game. If you are not using an IDE, make a new folder wherever you are going to be making your game at, and call the folder game. This will be our package (area to contain and organize sources/classes), and all of our source files are going to be going into this package.
Making the game
Now we are going to add our source files to our game package. Since this is a multi source game, I am going to tell you what methods and fields to add to each file, so that all we have to do is add the “filling” later on.
Lets start with our main file, TicTacToe.java . If you are on an IDE, just create a class inside the package game, and call it TicTacToe. If you are not using an IDE, inside the folder game, create the file TicTacToe.java . Now that we have our file, it’s time to add the structures. Lets start by packaging the file under “game”. You will do this like so:
package game;
Next, lets make the class final. We are going to do this because it prevents unruly players from sub-classing our game so that they can modify it. We also want to add a main method, as we want this class to be able to execute on it’s own. Inside the main method we are going to have the game create another one of itself, so that the rest of the class does not have to be static. I am doing this because it makes life for us a bit easier, and it doesn’t effect security of our game, as it cannot be subclassed, and we are going to make as many variables final as possible, so that they cannot be modified during runtime (by hackware and the likes). We will do this like so:
package game; public final class TicTacToe { // Other methods excluded. If you didn’t know, this is a comment. Do NOT type this, as it does not have any purpose other than informing the reader of the source about something. public static void main(String[] args){ } }
Great! Now our game can be executed. Before we continue with our fields and methods, etc, I think it best if we also create the other classes. The classes you need to make are:
- ClickHandler.java - This will handle all the clicks received by the game screen.
- Holder.java - This will be our Enum type that specifies X, O, and GAME, which are all states that a Tile may hold at any given time.
- Tile.java - This is what our map will be made up of. These are held by either X, O, or GAME (Meaning the tile is not yet claimed by either X or O, and can still be claimed by either player).
- TilePainter.java - This will display, or paint, all of the Tiles currently on the field, and what their holder is.
package game; // Import the required classes so that they can be used for later import java.awt.event.MouseEvent; import java.awt.event.MouseListener; public final class ClickHandler implements MouseListener { // Implementing MouseListener so that our class can be used to check for clicks on our game. private final TicTacToe game; // Make final instance of TicTacToe for use by our class, but do not instantiate that, as we want to use the one provided in the constructor. public ClickHandler(TicTacToe game) { // Constructor this.game = game; // Set the game inside ClickHandler to the game provided by the contructor parameter game. } public void mouseReleased(MouseEvent e) { // Mouse released event. Inside this is what happens when the mouse is released over our game. game.attemptClaim(e.getX() - 3, e.getY() - 26); // Subtracts fromt the values to eliminate interference from the frame border. game.getGameframe().repaint(); // Make sure that changes made here are shown right away. } // The rest is just required by MouseListener. Pay it no mind. @Override public void mouseClicked(MouseEvent e) { } @Override public void mousePressed(MouseEvent e) { } @Override public void mouseEntered(MouseEvent e) { } @Override public void mouseExited(MouseEvent e) { } }
Greate! Now lets add our Enum type that tells us who controls what. If you do not not what an enum is, don't worry. It's a class (or collection of classes) that replace lists of variables, and specify them under one namespace. They are also final, and thus will never change. For our enum type, Holder, I am just going to give you the source, and explain it in comments. This is what it looks like:
package game; import java.awt.Color; // Import the Color class, so that our Enum type can return the color of its type. public enum Holder { X, O, GAME, ANY; // All the enums that will be under the Holder namespace. public String getText() { // Get the text to display on the Tile switch (this) { case X: return "X"; case O: return "O"; default: return " "; } } public Holder getOpposite() { // Get the opposite of this Enum. If it was X, then the opposite is O, and likewise. switch (this) { case X: return O; case O: return X; default: return GAME; } } public Color getColor() { // Get the background color to color the Tile. switch (this) { case X: return Color.LIGHT_GRAY; case O: return Color.DARK_GRAY; default: return Color.WHITE; } } public Color getTextColor() { // Get the color to make the text of the Tile. switch (this) { case X: return Color.BLACK; case O: return Color.WHITE; default: return Color.MAGENTA; } } }
Alright. Next is Tile class, one of the most important in our game. We want it to be final, and contain all the required values for displaying the Tile. It looks like this:
package game; import java.awt.Graphics; // Import the abstract class Graphics. Used for displaying this Tile. public final class Tile { private final int x, y, width, height; // The x, y, width, and height of this class. Can be final, as we are going to reuse the same Tiles, and there is no need to change the position once created. private boolean claimed = false; // This is used by the getter to tell whether or not this instance is claimed by a Holder. private Holder heldBy = Holder.GAME; // This is the holder of this Tile. By default it is held by GAME, which means no one has claimed it yet. private final TicTacToe game; // Private final instance of our TicTacToe game, used to interact with our game. public Tile(int x, int y, int width, int height, TicTacToe game) { // Constructer. Include the dimensions, and the TicTacToe instance used for communication. this.x = x; this.y = y; this.width = width; this.height = height; this.game = game; } public void claim(Holder h) { // Used by TicTacToe to claim this Tile under the holder specified in the parameters. if (heldBy == Holder.GAME && !claimed) { // Make sure no one has claimed this yet. claimed = true; // Claiming this Tile. heldBy = h; // Setting the holder to the claimer } } public Holder getHolder() { // Used to get the holder who possesses control over this Tile. return heldBy; } public void paint(Graphics g) { // Paints (Displays) this Tile on our game's frame. g.setColor(heldBy.getColor()); // Getting the color to use. Uses the color of the current holder. g.fillRect(x, y, width, height); // Creating the rectangle of the background using the dimensions specified. g.setColor(heldBy.getTextColor()); // Getting the color that the text should be. Uses the current holder to get the color. g.drawString(heldBy.getText(), middleX() - (game.getFontSize() / 3), middleY() + (game.getFontSize() / 3)); // Drawing the text (X or O) specified by the Holder. Subtracts one third and adds one third of the font size used by the game, so that the text will be centered. } private int middleX() { // Get the middle x value of this Tile return (x + width / 2); // Returns the middle x value. } private int middleY() { // Get the middle y value of this Tile return (y + height / 2); // Returns the middle y value. } public void reset() { // Used to reset this Tile after the game is over. this.heldBy = Holder.GAME; // Remove the Holder. this.claimed = false; // Make sure that it is not claimed. } public boolean inArea(int x, int y) { // Checks whether the x y parameters are within the range of this Tile. return (this.x <= x && this.x + this.width >= x) && (this.y <= y && this.y + this.height >= y); } public boolean isClaimed() { // Returns whether or not this Tile is claimed. return claimed; } public int getX() { // Returns the X value of this Tile. return x; } public int getY() { // Returns the Y value of this Tile. return y; } public int getWidth() { // Returns the width of this Tile. return width; } public int getHeight() { // Returns the height of this Tile. return height; } }
Great! Only one more class left to make, then we can finish our TicTacToe class, and thus finish the game! All we need to add now is the TilePainter. Since graphics are relatively hard to understand at first, I will try to explain it as best I can. What the painter does is, whenever the TicTacToe game calls a repaint on the games frame, it will send a paint call to the method contained within. From inside this class, the paint method will paint (display) all the Tiles of the game, in their current state. This is the core graphical component, and so very important to the game. Now, you might be thinking "Oh no, now I gota make this HUGE file. Ughh". No. Infact, TilePainter is the smallest class in our game. As with all the other classes, we are going to declare it as final. We also need to import some graphical components. This is what TilePainter looks like:
package game; // Graphical component imports. import java.awt.Color; import java.awt.Component; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; public final class TilePainter extends Component { private static final long serialVersionUID = 1L; // Default serialized value. Required by all classes that extend Component. We do not need to worry about this, in this tutorial, as we are not going to be messing with serializable classes and methods. private final TicTacToe game; // Private final reference to the TicTacToe game. Instantiated by the constructor. public TilePainter(TicTacToe game) { // Constructor. Requires a TicTacToe game to be specified. this.game = game; // Make sure that the game in this class is that of the one being used. } public void paint(Graphics g) { // Paint method. Called when the repaint method is called on the JFrame this is attached to. Graphics2D g2d = (Graphics2D) g; // Create a Graphics2D out of casting the Graphics provided. g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); // Create Anti-aliasing so our characters are smooth. g2d.setFont(new Font("Dialogue", Font.BOLD, game.getFontSize())); // Since all the Xs and Os need to be bold, and their is no other text to be displayed, simply make it bold. Uses the font size provided by the TicTacToe game. for (Tile t : game.getTiles()) { // For-Each loop to iterate throught the Tiles of our game. g.setColor(Color.BLACK); // Set the color to black, so that we can draw an outline to show the different Tiles and their boundaries. g.drawRect(t.getX() - 1, t.getY() - 1, t.getWidth() + 1, t.getHeight() + 1); // Drawing the outline using the dimensions of the Tile being shown. Makes the dimensions either 1px smaller or larger, so that acts as an outline. t.paint(g2d); // Call paint on the Tile itself, so that the tile can display itself. } } }
Yay! Now all we have to do is finish our TicTacToe class, and then we can play our game! Since we are going to instantiate a new TicTacToe game within our class, we are going to provide a modified constructor. This will help set up the game, and it will also allow for use to add AI later. Because it is difficult to explain features without visual reference, I will give you the finished TicTacToe, and provide comments to explain things. This is our finished TicTacToe class:
package game; import java.awt.Dimension; // This is used as a compact way to store the dimensions. Used for the JFrame. import java.util.concurrent.TimeUnit; // I'm using this to put a time delay on the game loops, so that it doesn't use all of your processor. import javax.swing.JFrame; // This is used to show the game to the player(s). import javax.swing.JLabel; // This is used to display a simple String, without the need to get deep into the Graphics. public final class TicTacToe { // Declares our new class. Final to prevent subclassing. private final Tile[] TILES = new Tile[9]; // The final array of Tiles. Final because we will only ever need the specified amount, in this case, 9. private final int TILE_SPACING = 96; // This is the final integer primitive of how far appart (in pixels) the Tiles are. private final int WIDTH = 96, HEIGHT = 96; // Normal dimensions for our Tiles to use. private final JFrame GAMEFRAME = new JFrame("Tic-Tac-Toe"); // The game frame. The whole game will be shown on this Object. Final because we never need to make a new one. private final TilePainter PAINTER = new TilePainter(this); // This will get added into GAMEFRAME so that the repaint call will affect it. Final because, just like the GAMEFRAME, it will never need to be reinstantiated. private final ClickHandler CLICK_HANDLER = new ClickHandler(this); // Creates the ClickHandler to get attached to GAMEFRAME to handle clicks. Is declared final for the same reason as PAINTER. private Holder turn = Holder.X; // Current holder. Instantiates as X. private int whoseTurn = 0; // Whose turn is it? Used to tell when to swap who startes the game. private final Dimension FRAME_SIZE = new Dimension(295, 304); // Creates the dimensions to be added to GAMEFRAME. Represents the only size our game will ever become. Final because it will never change. private final int FONT_SIZE = 64; // The integer primitive that represents the size of all global fonts, to this game. private int oWins = 0; // How many times the player O has won. private int xWins = 0; // How many times the player X has won. private boolean gameOver = false; // Whether or not to stop the game loop, and start a new game. private boolean nextTurn = false; // Used to tell the game loop when it is time to switch players. private JFrame outcome = new JFrame(); // Outcome frame. This will be shown whenever a player wins, or a draw occurs. private final int[][] WINS = { { 1, 1, 1, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 1, 1, 1, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 1, 1, 1 }, { 1, 0, 0, 0, 1, 0, 0, 0, 1 }, { 1, 0, 0, 1, 0, 0, 1, 0, 0 }, { 0, 1, 0, 0, 1, 0, 0, 1, 0 }, { 0, 0, 1, 0, 0, 1, 0, 0, 1 }, { 0, 0, 1, 0, 1, 0, 1, 0, 0 } }; // This array represents all possible winning arrangements. The reason they are 1 and 0 is because the game's win checker will use the current turn, and the 1s mean that the current player has to control this tile. If the player controls all 3 tiles that are represented as 1, then they win this game, and gameOver is set to true. public boolean allFull() { // Returns whether or not any more moves can be made. Positive means that all tiles are claimed, and false means there are still move(s) to be made. for (Tile t : TILES) { // For-Each loop to iterate through all the tiles. if (!t.isClaimed()) { // If even one tile isn't claimed yet, return false, as there is atleast 1 more move to be made. return false; } } return true; // If the For-Each never returned false, then there must not be any moves left. Returns true. } public boolean hasWon(Holder h) { // Check whether the specified holder has won the game. boolean hasWon; // Uses this value to check whether or not they have won. for (int[] i : WINS) { hasWon = true; // Set it to true. Unless proved otherwise, this player has won. for (int j = 0; j < i.length; j++) { // Iterate through the possible wins. if (i[j] == 1) { // If the encountered value is a 1 (Meaning the player must control this tile)... if (TILES[j].getHolder() != h) { // If the player does NOT control this tile... hasWon = false; // Proves otherwise (Sets hasWon to false, meaning this win combo is not possible. j = i.length; // Set j to the length of this win, so that we can exit this loop, as we have already proven the player has not won this one. } } } if (hasWon) // If hasWon is still true, then they must have won. return true; // Return true, as the player has won. } return false; // Else, if it gets throught the entire wins array, and non of them have been achieved, return false, this player has not won. } public int getFontSize() { // Used by the other classes to get the font size they should use. return FONT_SIZE; // Return the specified font size. } public TicTacToe(boolean ai) { // Constructor PAINTER.setSize(FRAME_SIZE); // Set the size of PAINTER to that of FRAME_SIZE. buildFrame(); // Frame Builder method. Only used once, but it improves code readability. loadTiles(); // Load the tiles. Gets them set up with the correct coordinates and dimensions. } public void loadTiles() { // Loads the tiles (Gets them ready for use). int tile = 0; // Current tile being set. Increases each time a tile is set. Starts at 0, ends at 8. for (int i = 0; i < TILES.length / 3; i++) { // iterate through TILES by a third of the size of our game (3). This iteration is the columns. for (int j = 0; j < TILES.length / 3; j++) { // iterate throught TILES in a similar maner as above. This iteration is the rows. TILES[tile] = new Tile(i * this.TILE_SPACING, j * this.TILE_SPACING, this.WIDTH, this.HEIGHT, this); // Instantiate a new tile at the specified position, using the default values. Uses the iteration value * whatever the default size is, so that they will be equally spread apart. tile++; // Increases tile by 1, so that next time, it will be a different tile being set. } } } private void nextTurn() { // Used to switch turns. Called each time a valid move is made. if (hasWon(turn)) { // Check to see if the move the current player made was a winning move. gameOver = true; // If it was, then set gameOver to true; sendWin(turn); // Also, display a window informing the user(s) of what occured. Also shows scores. return; // Exit this method. Nothing left to do. } if (allFull()) { // If there are no moves left, and the last players move wasn't a winning one... gameOver = true; // The game is over sendDraw(); // Call the method that creates a frame informing the user(s) of the draw. Also shows scores. return; // Exit this method. Nothing left to do. } turn = turn.getOpposite(); // Switch turns. } public void attemptClaim(int x, int y) { // Used to claim a Tile. Checks to get which tile is within coordinates, and then if it isn't claimed, claims it. for (int i = 0; i < TILES.length; i++) { // Iterate through all the tiles. if (!TILES[i].isClaimed() && TILES[i].inArea(x, y)) { // If the tile isn't claimed, and the tiles is in the required area. TILES[i].claim(turn); // Claim the tile under the current player. nextTurn = true; // on next game loop, ensure that the players will be switched, as the current players turn has ended. return; // Return. Nothing left to do. } } } private void buildFrame() { // Sets up GAMEFRAME. getGameframe().addMouseListener(CLICK_HANDLER); // Add ClickHandler getGameframe().setSize(FRAME_SIZE); // Add the dimensions getGameframe().setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Make it so game exits when this frame closes. getGameframe().setResizable(false); // Make it so that this frame is always the same size. getGameframe().setMaximumSize(FRAME_SIZE); // Honestly, these probably arn't needed, but just in case. getGameframe().setMinimumSize(FRAME_SIZE); getGameframe().add(PAINTER); // Add the TilePainter. getGameframe().pack(); // Pack all the changes. } private void sendWin(Holder winner) { // Create the win frame based on the winner defined in parameters. outcome.setVisible(false); // If there was already a copy of outcome in use, remove it from site. outcome.dispose(); // Remove any current outcome's members. outcome = null; // Destroy any current outcome. if (winner == Holder.X) // If the winner is X xWins++; // X wins +1 else if (winner == Holder.O) // Else if the winner is O oWins++; // O wins +1 outcome = new JFrame(winner.getText() + " has won!"); // Create new JFrame with winning title. JLabel winMessage = new JLabel(" " + winner.getText() + " has won! Score is X: " + xWins + ", O: " + oWins); // Create a message that informs of win, and displays current score. outcome.add(winMessage); // Add the message to the JFrame. outcome.setResizable(false); // Set the size to constant. outcome.setAlwaysOnTop(true); // Make it always on top. outcome.pack(); // Pack it. outcome.setVisible(true); // Set it visible so it can be seen. } private void sendDraw() { // Send a JFrame with Draw. Practically the same as sendWin, but different event. outcome.setVisible(false); // If any current instance is visible, not any more. outcome.dispose(); // Remove members. outcome = null; // Destroy outcome = new JFrame("Draw!"); // Declare the match a draw. JLabel drawMessage = new JLabel(" Its a Draw! Score is X: " + xWins + ", O: " + oWins); // Display Draw, and score. outcome.add(drawMessage); // Add the message to the JFrame. outcome.setResizable(false); // Set the size to constant. outcome.setAlwaysOnTop(true); // Make it always on top. outcome.pack(); // Pack it. outcome.setVisible(true); // Set it visible to be seen. } private void resetTiles() { // Resets the tiles for (Tile t : TILES) // Iterate through all the tiles. t.reset(); // Reset each tile. } public void newGame() { // Called when our game is executed. This is the game loop. while (true) { // Repeat forever. Makes sure you can keep playing using the same settings, as this way, it just repeats the game startup process. gameOver = false; // Game is no longer over. resetTiles(); // Reset the tiles to clear the data from the previous game. GAMEFRAME.setVisible(true); // Set GAMEFRAME visible, so you can see it. turn = Holder.X; // By default, X will start every game. while (!gameOver) { // Loop until game over is true. if (nextTurn) { // If nextTurn was set to true.. nextTurn = false; // set back to false, so it doesn't repeat next loop. nextTurn(); // Switch turns. } try { TimeUnit.MILLISECONDS.sleep(25); // Wait 25 milliseconds. Added to decrease the load on your CPU from constant updates. } catch (InterruptedException e) { e.printStackTrace(); } GAMEFRAME.repaint(); // Repaint. Displays any changes made. } // Game is now over. try { TimeUnit.SECONDS.sleep(5); // Wait 5 seconds, so user(s) can see why they lost/won/ had a draw. } catch (InterruptedException e) { e.printStackTrace(); } getGameframe().setVisible(false); // Remove GAMEFRAME from sight so it's members can be reset. } } public Holder getTurn() { // Returns the current turn (player who is playing). return turn; } public Tile[] getTiles() { // Returns TILES so that other classes can use them. return TILES; } public static void main(String[] args) { // Main method. TicTacToe game = new TicTacToe(); // Instantiate new instance of TicTacToe. game.newGame(); // Start a new game. } public JFrame getGameframe() { // Returns GAMEFRAME. return GAMEFRAME; } }
Congrats! You have successfully completed this tutorial! You should now be able to compile, and run your game. Currently it is only single player, but AI will be comming soon (After I finish my current Battleship project).
Please feel free to comment suggestions or questions. I am open to criticism, so don't hold back.
Source Files (No AI) (All are declared inside package "main"):
Modified/Added Source Files(Has AI) (All are declared inside package "main"):
The rest are the same as above. | http://forum.codecall.net/topic/72378-java-tutorial-tictactoe-revised/ | CC-MAIN-2020-05 | en | refinedweb |
In addition, this book is part of InformIT’s Content Update Program, which provides content updates for major technology improvements! As significant updates are made to WIndows Server 2016,.
[image: Image]
CHAPTER 19
Windows Server 2016 Management and Maintenance Practices
IN THIS CHAPTER
[image: Image] Going Green with Windows Server 2016
[image: Image] Initial Configuration Tasks
[image: Image] Managing Windows Server 2016 Roles and Features
[image: Image] Server Manager
[image: Image] Server Manager Diagnostics Page
[image: Image] Server Manager Configuration Page
[image: Image] Server Manager Storage Page
[image: Image] Auditing the Environment
[image: Image] Managing Windows Server 2016 Remotely
[image: Image] Using Common Practices for Securing and Managing Windows Server 2016
[image: Image] Keeping Up with Service Packs and Updates
[image: Image] Maintaining Windows Server 2016
Modern businesses depend on their IT infrastructure in order to keep their processes moving and their products delivering. Most IT infrastructures these days depend fairly heavily on Windows-based servers. These servers need to be managed and maintained to keep the businesses running optimally. Server management and maintenance help maximize investment in infrastructure and productivity. They also keep the IT infrastructure running effectively and efficiently to boost availability and reliability.
Windows Server 2016 brings many new tools and features to help keep the servers managed and maintained and they have been designed to scale to levels never before seen. These tools include the updated Server Manager, better auditing, improved configuration of servers through the roles and features, better remote management, IPAM (IP Address Management), and a slew of other capabilities. Many formerly manual tasks are automated in Windows Server 2016 using the enhanced Task Scheduler. These include tasks such as defragmentation and backup.
Server management entails many different tasks, including administering and supervising servers based on functional roles, proactively monitoring the network environment, keeping track of activity, and implementing solid change-control practices. These management functions for Windows Server 2016 Server 2016 environment.
Going Green with Windows Server 2016
A big part of server management and maintenance practices is planning for resources, including reducing the environmental impact of servers. Power consumption of servers is a huge environmental concern today and a significant expense for large data centers.
Windows Server 2016 continues the “green” trend with green concerns in mind and specifically with reducing the power consumption, carbon footprint, and therefore, the environmental impact of running a server. This includes server-level improvements and data center-level improvements.
Windows Server 2016 reduces the power consumption of individual servers through several new or improved technologies, as follows:
[image: Image] An improved Processor Power Management (PPM) engine—The new PPM engine adjusts the processor speed and, therefore, power consumption in response to demand. Windows Server 2016 also supports the core-parking feature, which idles processor cores that are not being used, thus reducing their power consumption.
[image: Image] Storage power management—The ATA Slumber feature allows for new power states for a more nuanced power utilization. Windows Server 2016 will recognize solid state drives and power them down when not in use, to reduce their power consumption. And Windows Server 2016 supports boot to storage area networks (SANs), eliminating the need for direct attached drives and thus reducing power consumption.
[image: Image] Intelligent Timer Tick Distribution—This allows processors to skip activation if not needed for work, reducing the power consumption of underutilized systems.
[image: Image] Reduced background work—Windows Server 2016 also has reduced operating system (OS) background work requirements, reducing power draw even further, especially in idle states.
Windows Server 2016 also enables administrators to better manage power consumption across servers through the following:
[image: Image] Remote manageability of power policy—Windows Server 2016 has Group Policy features for controlling power options across a number of servers. Power policy can also be configured remotely with PowerShell and with Windows Management Instrumentation (WMI) scripting via the new root\cimv2\power namespace. These allow for much more sophisticated programmatic control of power consumption.
[image: Image] In-band power metering and budgeting—Power consumption can be displayed as a performance counter in the new Power Meter object. This object allows manufacturers to instrument their platform power consumption live. This can be consumed by management applications such as System Center Operations Manager with thresholds and alerts. The Power Meter object also contains a budget counter, enabling you to set power budgets on a server-by-server basis.
[image: Image] New additional qualifier designed for Windows Server 2016 Logo program—This Power Management AQ addition to the program allows manufacturers to distinguish themselves and identify power-saving features in their products, enabling IT managers to purchase power-saving hardware to complement the power-saving Windows Server 2016 OS.
[image: Image] Virtualization—Although virtualization might not initially seem like a power-saving technology, consider the fact that many servers in modern IT infrastructures are not fully using their resources. An application might have justified a high-powered server based on its high I/O requirements or high memory requirements but might not be fully utilizing the CPU power of the server. By creating multiple virtual servers on a physical server and deploying servers based on complementary resource usage, you can more fully utilize modern servers and thus reduce the overall number of physical servers, thus reducing power consumption and eventually resulting in fewer retired servers in landfills.
Many of these features require no specific action on the part of an administrator, but management and maintenance practices can be adjusted to account for these green power features. For example, the power consumption at 100% utilization for Windows Server 2003 SP2 and for Windows Server 2016 servers is roughly the same. However, the power consumption at 30% utilization is approximately 20% higher for Windows Server 2003 SP2 than for Windows Server 2016. At lower workloads, Windows Server 2016 consumes less power; and Windows Server 2016 is even more efficient . . . especially without the GUI. Most servers operate at lower workloads, so the power savings for a Windows Server 2016 server can be significant.
These Windows Server 2016 features help organization move toward greener servers and data centers and protect the environment.
Server Manager Dashboard
One of the features of Windows Server 2016 is the Dashboard available in Server Manager, which by default will appear at logon. This interface enables an administrator to easily add roles or features, create server groups, and make management changes to groups of servers. One can create a group and populate it with servers destined to become Internet Information Services (IIS) servers and add the same roles and features to each in a single interface. This greatly improves the ability to manage multiple systems.
As shown in Figure 19.1, the Dashboard gives a quick view of the roles installed, quick access to events specific to that role, a link to see associated services, and links to the management functions of each role.
[image: Image]
FIGURE 19.1 Server Manager—Dashboard.
For example, clicking Manageability under AD DS brings up the AD DS Manageability Detail view, which shows servers based on status criteria. From here, you can click Go to AD DS and see the full level of detail, including the following:
[image: Image] Servers—This section shows the list of servers associated with the role that was previously chosen (in this example, AD Domain Controllers). The view shows server name, IPv4 address, manageability state, last update, and Windows activation.
[image: Image] Events—This section shows events associated with the role previously selected. Information includes server name, event ID, severity, source, log, and date/time.
[image: Image] Services—This section is where the services specific to the role selected are shown. Information includes server name, display name of the service, service name, status, and start type.
[image: Image] Best Practices Analyzer—This section is where BPA scan results are displayed, including server name, severity, title and category. BPA scans can also be launched from the Tasks button here.
[image: Image] Performance—This section shows performance data, including server name, counter status, CPU alert count, memory alert count, first occurrence, and last occurrence. Performance alerts can be configured from the Tasks button.
[image: Image] Roles and Features—This section shows the roles and features information, including server name, name, type, and path.
Each of these sections has the ability to filter the view, save queries, or pull up a list of saved queries. This proves exceptionally helpful in large environments where a list of servers could be very large. This is also helpful when viewing events and you are looking for specific events. Each of the views can also sorted based on various clickable fields.
The initial configuration settings in a newly built Windows Server 2016 system are stripped down and basic (as shown in Table 19.1), with little or no security. For example, the latest security updates have not been applied, and the system is not configured to download them automatically. Therefore, the Windows Firewall is enabled by default to protect the server from network access until the initial configuration is completed, and the Remote Desktop feature is turned off.
TABLE 19.1 Default Configuration Settings
Setting
Default Configuration
Time zone
Pacific time (GMT – 8) is the time zone set by default.
Computer name
The computer name is randomly assigned during installation. Administrators can modify the computer name by using commands in the Initial Configuration Tasks Wizard.
Domain membership
The computer is not joined to a domain by default; it is joined to a workgroup named WORKGROUP.
Windows Update
Windows Update is turned off by default.
Network connections
All network connections are set to obtain IP addresses automatically by using Dynamic Host Configuration Protocol (DHCP).
Windows Firewall
Windows Firewall is turned on by default.
Roles installed
No role or features are installed by default.
You can configure each of these settings via the properties of the computer object. Just clicking the Start button (activated by hovering the mouse in the far right side of the screen) and then right-clicking Computer will offer up an Advanced option that exposes Manage, Map Network Drive, Disconnect Network Drive, and Properties. Selecting Properties will provide an interface familiar to Server 2008 R2 administrators where the previously described settings can be modified.
Managing Windows Server 2016 Roles and Features
To help organize and manage the expanded functionality of Windows Server 2016, the platform continues to use the roles and features paradigm. The roles and features enable administrators to add and manage functionality in coherent blocks. This includes tools to summarize, manage, and maintain the installed roles and features with the enhanced ability to configure these roles and features across multiple systems simultaneously.
Roles in Windows Server 2016
Server roles in Windows Server 2016 are used to organize the functionality of the OS. The server roles are an expansion of the server roles of earlier versions of Windows, with significant enhancements. Roles usually include a number of related functions or services that make up the capabilities that the server will offer. A role designates a primary function of the server, although a given server can have multiple roles.
Windows Server 2016 offers the traditional role-based or feature-based installation and introduces a scenario-based installation. Currently the scenario-based installation supports Remote Desktop Services installations only.
Administrators familiar with Server 2008 R2 will notice that the new Add Roles and Features Wizard now offers the option to select multiple servers from a pool or to apply services or roles to a virtual hard disk.
Windows Server 2016 includes the following roles:
[image: Image] Active Directory Certificate Services
[image: Image] Active Directory Domain Services
[image: Image] Active Directory Federation Services
[image: Image] Active Directory Lightweight Directory Services
[image: Image] Active Directory Rights Management Services
[image: Image] Application Server
[image: Image] DHCP Server
[image: Image] DNS Server
[image: Image] Fax Server
[image: Image] File And Storage Services
[image: Image] Hyper-V
[image: Image] Network Policy and Access Services
[image: Image] Print and Document Services
[image: Image] Remote Access
[image: Image] Remote Desktop Services
[image: Image] Volume Activation Services
[image: Image] Web Server (IIS)
[image: Image] Windows Deployment Services
[image: Image] Windows Server Update Services
Within each role, a number of role services make up the role. The role services allow the administrator to load only the specific services that are needed for a particular server instance. In some cases, such as for the DHCP Server or DNS Server roles, the role and the role service are one and the same. In other cases, the role contains multiple services that can be chosen. For example, the File Services role contains the following role services:
[image: Image] File Server
[image: Image] BranchCache for Network Files
[image: Image] Data Deduplication
[image: Image] DFS Namespaces
[image: Image] DFS Replication
[image: Image] File Server Resource Manager
[image: Image] File Server VSS Agent Service
[image: Image] iSCSI Target Server
[image: Image] Server for NFS
Adding a role and role services installs the binaries (that is, the code) that allow the services to function. Additional installation and configuration usually needs to be done after the roles are installed, such as for the Active Directory Domain Services role.
Only loading the roles required for each server (and therefore only the appropriate binaries) reduces the complexity, the attack surface, and the patch surface of the server. This results in a more-secure, less-complex, and more-efficient server—in short, resulting in fewer headaches for the administrator who has to manage the server!
NOTE
The patch surface of a server is the code in the server that requires patches to be applied. This can increase the need for patches and therefore downtime, as well as administrative overhead. If code is installed on a server, it needs to be patched even if that particular code is not in use on a server. This is analogous to the attack surface of the server.
A good example of this is the Web Server role. If a domain controller has the Web Server role added, any patches that apply to the code base of the Web Server role need to be installed. This is true even if the services are disabled or just not used. Therefore, the patch surface of the domain controller has been increased.
However, if the domain controller only has the roles (and therefore the code) for the roles it needs, the patches for other roles will not need to be applied to the domain controller. Therefore, the patch surface of the domain controller has been reduced.
Features in Windows Server 2016
In addition to the roles and role services, Windows Server 2016 also has the ability to add features. Features are typically supporting components that are independent of the server role but might provide support for a role or role service. For example, a domain controller is configured with the Active Directory Domain Services role. However, in some organizations, the domain controller will also serve as a Windows Internet Naming Service (WINS) server. WINS is a feature in Windows Server 2016.
There are many different features in Windows Server 2016, including the following:
[image: Image] .NET Framework 3.5.1
[image: Image] .NET Framework 4.6 and later
[image: Image] Background Intelligent Transfer Service (BITS)
[image: Image] BitLocker Drive Encryption
[image: Image] BitLocker Network Unlock
[image: Image] BranchCache
[image: Image] Client for NFS
[image: Image] Data Center Bridging
[image: Image] Desktop Experience
[image: Image] Enhanced Storage
[image: Image] Failover Clustering
[image: Image] Group Policy Management
[image: Image] Ink and Handwriting Services
[image: Image] Internet Printing Client
[image: Image] IP Address Management (IPAM) Server
[image: Image] iSCSI Target Storage Provider (VDS and VSS hardware providers)
[image: Image] iSNS Server service
[image: Image] LPR Port Monitor
[image: Image] Management OData IIS Extension
[image: Image] Media Foundation
[image: Image] Message Queuing
[image: Image] Multipath I/O
[image: Image] Network Load Balancing
[image: Image] Peer Name Resolution Protocol
[image: Image] Quality Windows Audio Video Experience
[image: Image] RAS Connection Manager Administration Kit
[image: Image] Remote Assistance
[image: Image] Remote Differential Compression
[image: Image] Remote Server Administration Tools
[image: Image] RPC over HTTP Proxy
[image: Image] Simple TCP/IP Services
[image: Image] SMTP Server
[image: Image] SNMP Services
[image: Image] Subsystem for UNIX-Based Applications
[image: Image] Telnet Client
[image: Image] Telnet Server
[image: Image] TFTP Client
[image: Image] User Interfaces and Infrastructure
[image: Image] Windows Biometric Framework
[image: Image] Windows Feedback Forwarder
[image: Image] Windows Identity Foundation 3.5
[image: Image] Windows Internal Database
[image: Image] Windows PowerShell
[image: Image] Windows PowerShell Web Access
[image: Image] Windows Process Activation Service
[image: Image] Windows Search Service
[image: Image] Windows Server Backup
[image: Image] Windows Server Migration Tools
[image: Image] Windows Standards-Based Storage Management
[image: Image] Windows System Resource Manager
[image: Image] Windows TIFF IFilter
[image: Image] WinRM IIS Extension
[image: Image] WINS Server
[image: Image] Wireless LAN Service
[image: Image] WoW64 Support
[image: Image] XPS Viewer
The features are installed with the Server Manager’s Add Roles and Features Wizard. To add a feature, follow these steps:
1. Launch Server Manager.
2. From the Server Manager Dashboard, click Add Roles and Features.
3. Choose Role-Based or Feature-Based Installation. Click Next.
4. Select the server from the server pool, and click Next.
5. Click Next to skip past roles and select the features to install. Click Next.
6. Click Install, and then click Close.
The feature will now be installed.
NOTE
Unlike earlier versions of Windows, all the binaries for Windows Server since version 8, Windows Vista, Windows 7, Windows 8, and Windows 10 are installed in the C:\WINDOWS\WINSXS directory. All the components—that is, roles and features—are stored in the WINSXS directory. This eliminates the need to use the original DVD installation media when adding roles or features.
However, the trade-off is that the WINSXS folder is more than 6GB, because it contains the entirety of the OS. In addition, it will grow over time as updates and service packs are installed. For a physical machine, the additional disk space is not much of an issue. However, for virtual machines, it means that there is an additional 6GB of additional disk space that has to be allocated for each and every Windows server.
Creating a Server Group
To manage Windows Server 2016 systems in groups, it is necessary to create a server group. You can do so from the Server Manager Dashboard as follows:
1. Click Option 4, Create a Server Group.
2. Enter a server group name.
3. Select systems from either the server pool, Active Directory, or DNS, as appropriate. Use the Ctrl or Select key to select more than one server.
4. Click the right-arrow key to add the computers to the Selected list.
5. Click Finish.
This updates the Roles and Server Groups view to include the new group.
Viewing Events
The Windows Server 2016 Event Viewer functionality is located in the Server Manager. Selecting the Local Server or a Server Group gives administrators access to the event logs from that system. This provides a consolidated view that summarizes application and system event logs.
A more detailed view of event logs can be accessed by selecting a server group, right-clicking a server, and then choosing Computer Management. This will give the Server 2008 R2-style view that places event logs under the System Tools folder. This view gives the more traditional view that includes Application, Security, System, and Setup logs as well as Application and Services logs. The Events Viewer object on this page shows a high-level summary of the administrative events, organized by level:
[image: Image] Critical
[image: Image] Error
[image: Image] Warning
[image: Image] Information
[image: Image] Audit Success
[image: Image] Audit Failure
The view shows the total number of events in the past hour, 24 hours, and 7 days. You can expand each of these nodes to show the counts of particular event IDs within each level. Double-clicking the event ID count shows a detailed list of the events with the matching event ID. This is very useful for drilling into the specific events to see when they are occurring.
The Overview and Summary page also has a Log Summary section, which shows a list of all the various logs on the server. This is important because there are now nearly 220 different logs in Windows Server 2016. In addition to the standard system, security, and application logs, there is a setup log and a forwarded events log. Then there are the numerous application and services logs, including logs for each application and service, and a huge number of diagnostic and debugging logs. For each of the logs, the Log Summary section shows the log name, current size, maximum size, last modification, if it is enabled, and what the retention policy for the log is. This enables administrators to quickly see the status of all the logs, a daunting task otherwise.
Of course, you can view the logs directly by expanding the Windows Logs folder or the Applications and Services Logs folder. The Windows Logs folder contains all the standard application, security, setup, system, and forwarded events logs. The applications and services logs contain all the other ones.
Custom views can be created to filter events and combine logs into a coherent view. There is a default Administrative Events view, which combines the critical, error, and warning events from all the administrative logs. There is also a custom view created for each role that is installed on the server. The administrator can create new ones as needed.
Subscriptions can collect events from remote computers and store them in the forwarded events log. The events to be collected are specified in the subscription. The functionality depends on the Windows Remote Management (WinRM) and the Windows Event Collector (Wecsvc) services, and they must be running on both the collecting and forwarding servers.
Server Manager Performance Monitor
The Performance Monitor is incorporated into Computer Manager, as well. This diagnostic tool enables the administrator to monitor the performance of the server in real time, generate reports, and also save the performance data to logs for analysis.
The top-level folder of the Performance Monitor displays the System Summary. This gives a comprehensive overview of the memory, network interface, physical disk, and processor utilization during the past 60 seconds (see Figure 19.2). The System Summary is organized in a matrix, with a column for each instance of the network interface, disk, and processor. The information is updated every second. Unfortunately, the pane is still a fixed height, so it is hard to see all the information at once, and excessive scrolling is needed.
[image: Image]
FIGURE 19.2 System Summary in Performance Monitor.
The Monitoring Tools container holds the Performance Monitor tool. This tool enables you to monitor the performance of the server in more detail. The Performance Monitor has not really changed from earlier versions of Windows. It allows you to select performance counters and add them to a graph view for real-time monitoring. The graph can be configured to be a line graph, a bar graph, or even a simple text report of the counters being monitored. The monitor shows the last, average, minimum, maximum, and duration of the windows (1 minute 40 seconds by default).
For longer-term tracking, you can use data collector sets can be used. Data collector sets can log data from the following data sources:
[image: Image] Performance counters
[image: Image] Event traces
[image: Image] Registry key values
This data can be logged over an extended period of time and then reviewed. The data collected will also be analyzed and presented in reports that are very useful. There are two reports defined by default: the System Diagnostics and System Performance. When roles are added, such as the Active Directory Domain Services role, there might be additional data collector sets defined. These datasets gather data that is presented in reports, which is new to Windows Server 2016. There is a new reports folder in the Performance Monitor where the reports are saved.
To generate data for a Performance Monitor report, follow these steps:
1. Launch Server Manager.
2. Expand the Diagnostics node.
3. Expand the Performance node.
4. Expand the Data Collector Sets node.
5. Expand the System node and select the System Performance data collector set. Note that the data collector set includes an NT Kernel trace and performance counters.
6. Right-click the NT Kernel trace object and select Properties. Note the events that will be collected. Click Cancel to exit without saving.
7. Right-click the Performance Counter object and select Properties. Note the performance counters that will be collected. Click Cancel to exit without saving.
8. Right-click the System Performance data collector set and select Start. The data collector set will start collecting data.
9. Right-click the System Performance data collector set and select Latest Report.
The report will show a detailed analysis of the system performance. The Summary and the Diagnostic Results are shown in Figure 19.3. The Diagnostic Results indicate that memory is the busy component on the DC1 server. The report contains a wealth of details on the CPU, network, disk, memory, and overall report statistics.
[image: Image]
FIGURE 19.3 System Performance Report in Performance Monitor data collector sets.
You can also view the performance data that the report is based on directly. This can be done by right-clicking the specific report and selecting View, Performance Monitor. This shows the graph of all the counters selected during the data collection. You can select which counters to show in the graph.
The System Performance data collector set collects for only 1 minute, which is not long enough for detailed trend analysis. New data collector sets can be defined in the User Defined folder. For example, to create a duplicate of the System Performance data collector set that will run for an hour instead of a minute, follow these steps:
1. Launch Server Manager.
2. Expand the Diagnostics node.
3. Expand the Performance node.
4. Expand the Data Collector Sets node.
5. Select the User Defined node.
6. Right-click the User Defined node and select New, Data Collector Set.
7. Enter System Performance 1 Hour for the name and make sure that the Create from a Template is selected. Click Next.
8. Select System Performance and Click Next.
9. Click Next to keep the default root directory.
10. Select the Open Properties for this Data Collector Set option, and click Finish.
11. Click the Stop Condition tab.
12. Change the Overall Duration setting to 1 hour.
13. Click OK to save.
This data collector set can now be run and will collect the same data as the default System Performance, but for 1 hour instead of just 1 minute.
Device Manager
The Device Manager node shows the hardware that is installed on the server. It shows the hardware grouped by type of device, such as disk drives, display adapters, and network adapters. Each instance of the device type is listed in a node underneath the device type.
You can use the Device Manager to update the device drivers of the hardware, to change settings, and to troubleshoot issues with the hardware. Specifically, you can perform the following tasks:
[image: Image] Scan for new hardware
[image: Image] Add legacy hardware
[image: Image] Identify hardware problems
[image: Image] Adjust configurations
[image: Image] View device driver versions
[image: Image] Update the device drivers
[image: Image] Roll back device driver upgrades
[image: Image] Enable or disable hardware
For example, sometimes older video drivers or network card drivers will cause problems with the system. It is easy to check the Microsoft online driver repository using Device Manager. To check for an update to the device driver for the network adapter, follow these steps:
1. Expand the Network Adapters node in Device Manager.
2. Select the network adapter to check.
3. Select Action, Update Driver Software from the menu.
4. Click Search Automatically for Updated Driver Software.
5. Click Yes, Always Search Online (Recommended).
6. Install the update if found.
7. Click Close to exit the wizard.
NOTE
Many times, the latest version of the driver will already be installed. In these cases, the message “The best driver for your device is already installed” will be shown.
Task Scheduler
One of the greatly expanded features of Windows Server 2016 is the Task Scheduler. In earlier versions of Windows, this was an anemic service with limited options and auditing features. The Task Scheduler features in Windows Server 2016 have been expanded into a more sophisticated tool. The scheduler can start based on a variety of triggers, can take a number of predefined actions, and can even be mitigated by conditions and the settings.
Appropriately, there are expanded elements to the Task Scheduler, as follows:
[image: Image] Triggers—Tasks run when the trigger criteria are met. This could be a scheduled time, logon, startup, idle, log event, user session connect or disconnect, or workstation lock or unlock. These various triggers give the administrator a wide range of options on when to start a task.
[image: Image] Actions—The actions are the work that the task will perform. This can be executing a program, sending an email via SMTP, or displaying a message on the desktop.
[image: Image] Conditions—Conditions allow the task trigger criteria to be filtered. Conditions include if the computer is idle, on battery power, or connected to a network. This allows administrators to prevent tasks from running if the computer is busy, on battery, or disconnected from the network.
[image: Image] Settings—The settings control how a task can be executed, stopped, or deleted. In the settings of a task, the administrator can control if the task can be launched manually, if it runs after a missed schedule start, if it needs to restart after a failure, if it needs to run multiple tasks in parallel, or to delete it if it is not set to run in the future.
Another big improvement is the Task Scheduler Library, which includes approximately 40 different predefined tasks, including the following:
[image: Image] ScheduledDefrag—This task runs every week and uses the command defrag.exe–c to defragment all the volumes on the server. This is a major improvement of earlier versions of Windows, which required this command to be run manually. The task runs at 1 a.m. every Wednesday of every week by default.
[image: Image] ServerManager—This task runs at user logon and runs the ServerManagerLauncher to launch the Server Manager console whenever a user logs on.
Both these tasks demonstrate the capabilities of the Task Scheduler to automate routine tasks or to ensure that certain tasks run at logon.
The Task Scheduler has a new feature that goes hand in hand with the library, namely the ability to create folders to store the tasks. This helps organize the tasks that are created. The scheduler includes a Microsoft folder for the tasks that ship with the OS. Administrators can create other folders to organize and store their tasks.
Selecting the Task Scheduler folder in the Computer Manager configuration shows the Task Scheduler Summary (see Figure 19.4). This window has two sections: Task Status and Active Tasks. The Task Status section shows the status of tasks within a time frame (by default, the last 24 hours). The time frame can be set to the last hour, last 24 hours, last 7 days, or last 30 days. For each task that has run within the time frame, it shows the task name, run result, run start, run end, and triggered by. The section also summarizes the task status; Figure 19.4 also shows that 223 total tasks have run with 3 running and 216 succeeded.
[image: Image]
FIGURE 19.4 Task Scheduler Summary window.
The Active Tasks name is somewhat misleading because it shows tasks that are enabled and their triggers. It does not show tasks that are running. For the scheduled tasks, it shows the Next Run Time. This section is very useful for seeing which tasks will run on a given server in response to a trigger, either a schedule or an event. If the task does not appear in this section, it will be run only if executed manually.
Services and Applications
The Services snap-in has been moved to the Services and Applications container in Computer Manager, but is essentially unchanged from the earlier version of Windows. All the services are listed, along with their status, startup type, and logon credentials.
From the Services snap-in, administrators can control services on the server, including the following:
[image: Image] Start or stop the services
[image: Image] Change the startup type to set the service to start automatically, be started manually, or even prevent the service from starting at all
[image: Image] Change the account the service runs under
[image: Image] Set up recovery actions if the service stops, such as restarting the service or even restarting the server
[image: Image] View the configuration details of the service, such as what the executable is, what the service name is (which is shown in the Task Manager window), and what dependencies it has
A feature that was added in Windows Server 2008 and still available in Windows Server 2016 is the Automatic (Delayed Start) startup type. This is a setting used to reduce the crunch of services starting simultaneously during the server boot. All the services with the Automatic (Delayed Start) setting start after the services with the Automatic setting. This allows all the services to come up automatically, but allows essential services to start first.
WMI Control
WMI Control has also been moved under the Services and Applications container. Introduced in 2008 R2, this is a tool that enables administrators to maintain the Windows Management Instrumentation (WMI) configuration on the server. Interestingly, the tool is not an integrated snap-in, but rather a separate tool which is accessed via the properties of the WMI Control object.
With the WMI Control tool, an administrator can do the following:
[image: Image] View general information about the server
[image: Image] Back up and restore the WMI repository
[image: Image] Change the default scripting namespace (root\cimv2)
[image: Image] Manage access to the WMI via the Security tab
Before the introduction of the WMI Control tool, these tasks were difficult to accomplish.
For example, to back up the WMI repository, complete these steps:
1. Open the Server Manager.
2. Click Local Server.
3. In Tasks, select Computer Management.
4. Expand Servers and Applications.
5. Right-click WMI Control and choose Properties.
6. Select the Backup/Restore tab.
7. Select the Back Up Now option.
8. Enter a filename with a full path. The file type will be a WMI Recovery File (.rec).
9. Click Save to save the file.
10. Click OK to exit the tool.
Windows Firewall with Advanced Security
The Windows Firewall with Advanced Security interface is now accessed through Server Manager or through Control Panel. Viewing the Local Server tab via Server Manager shows a high-level status of the Windows Firewall. Clicking its status launches the Windows Firewall MMC.
This feature provides access to the combined Windows Firewall and Connection Security features of Windows Server 2016. These technologies work in tandem to provide protection from network-based attacks to the server. The firewall rules determine what network traffic is allowed or blocked to the server. The connection security rules determine how the allowed traffic is secured.
The Windows Firewall and the Connection Security features are covered in detail in Chapter 12, “Server-Level Security,” and Chapter 13, “Securing Data in Transit.”
The Windows Firewall with Advanced Security folder shows a summary of which profile is active (Domain, Private, or Public), the profile’s high-level configuration, and links to the other components of the snap-in.
The other components of the Windows Firewall with Advanced Security snap-in are for configuration and monitoring the features. These components are as follows:
[image: Image] Inbound rules
[image: Image] Outbound rules
[image: Image] Connection security rules
[image: Image] Monitoring
The inbound and outbound rules control what traffic is allowed in to and out of the server. Several hundred rules govern what traffic is allowed. These are organized into profiles for ease of application. Table 19.2 shows these profiles.
TABLE 19.2 Firewall Profiles
Profile
Description
Domain
Applied when the server is connected to its Active Directory domain
Private
Applied when the server is connected to a private network but not to the Active Directory domain
Public
Applied when the server is connected to a public network
Clearly, the vast majority of services will have the domain profile active because they will likely be on a network with Active Directory. Each of the profiles has a set of rules associated with it. In addition, a number of rules apply to all profiles, which are designated as Any. Some of the rules are disabled by default.
Connection security rules are stored in the likewise named folder. The rules specify how the computers on either side of a permitted connection authenticate and secure the network traffic. This is essentially the IPsec policy from earlier versions of Windows, albeit with a much improved interface. By default, no connection security rules are created in Windows Server 2016. Rules can be created and reviewed in this portion of the snap-in.
The Monitoring folder is somewhat limited in scope. It has a Firewall folder and a Connection Security Rules folder. These two folders simply show what rules are active, but show no traffic details or if the rules have blocked or allowed anything. In effect, they show the net result of the profile that is active.
Server Manager Storage Page
The Storage folder in the Computer Manager has two tools to support storage in Windows Server 2016; Windows Server Backup and Disk Management. These tools are used to manage local backups and locally attached storage, respectively.
Windows Server Backup
Assuming the feature is installed, the Windows Server Backup page shows a summary of the backup state of the server. This includes information about the status of backups, how much disk space the backups are using, and what the oldest and newest backups are. This allows an administrator to understand how recoverable the server is at a glance. The backup subsystem in Windows Server 2016 has fundamentally changed from a backup-to-tape job paradigm to a backup-to-disk state paradigm, requiring a different understanding of where backup stands. It is not enough to know that the latest backup job completed, but rather the span of the backups and how much space they take up.
Windows Server 2016 introduces an additional backup option called Online Backup. Online Backup enables administrators to automatically back up a system to online storage. By default, administrators have access via a Windows Live ID to Microsoft’s online storage. Clicking the Continue button in this view gives the option to sign up for storage and to download the necessary agent.
For the Windows Server Backup folder to be active, you need to install the Windows Server Backup feature. To do this, follow these steps:
1. Open Server Manager.
2. Click Add roles and features.
3. Click Next and then Next again.
4. On the Select Destination Server page, choose the destination server from the server pool, and then click Next.
5. On the Select Server Roles page, click Next.
6. On the Select Features page, check the Windows Server Backup Features check box.
7. On the Confirm Installation Selections page, click Install to install the new feature.
8. Click Close to close the wizard.
Now the Server Manager Windows Server Backup folder will be active. Selecting the folder shows the Windows Server Backup summary page, shown in Figure 19.5. This figure shows the latest active backup messages, status, scheduled backup, and disk usage. From this page, the administrator can also click links to set the backup schedules, run an immediate backup, start a recovery, and perform other backup-related tasks.
[image: Image]
FIGURE 19.5 Windows Server Backup summary page.
The Messages section shows the active messages. You can see in the figure that a backup is running. You can also see that backups completed successfully at 9:00 p.m., 3:00 p.m., 9:00 a.m., 3:00 a.m., and that the current one started at 10:38 p.m.
The Status section shows a summary of the backups, including the last backup, the next scheduled backup, and for all backups. For each of these categories, you can click the View Details link to get additional information. This helps the administrator quickly understand what backups are available for recovery.
The Scheduled Backup section shows a summary of the scheduled backups for the server and the disk usage of the backups. The Settings box shows what is being backed up (backup item), where it is being backed up to (the target disk), and when it is being backed up (the backup time). The backup time can be modified using the Action, Backup Schedule option.
The Destination Usage box shows the capacity, the used space, and the number of backups that are available on the target. You can click the View Details link to see the disk usage and details of the backups. Figure 19.6 shows the disk usage after the backup in the previous figure completed.
[image: Image]
FIGURE 19.6 Windows Server Backup disk usage.
Chapter 30, “Backing Up the Windows Server 2016 Environment,” covers the use of Windows Server Backup in more detail.
Disk Management
The Disk Management snap-in is used to conduct storage disk-related tasks. The Disk Management snap-in has not changed substantially from earlier versions, and most administrators will find it to be quite familiar. The snap-in enables administrators to manage disks by doing the following:
[image: Image] Creating and formatting partitions
[image: Image] Creating and formatting volumes
[image: Image] Extending, shrinking, and mirroring volumes
[image: Image] Assigning drive letters
[image: Image] Viewing the status of disks, partitions, and volumes
As shown in Figure 19.7, the snap-in shows volumes in the top window with capacity, free space, and status information. This is a logical representation and is independent of the physical media. The bottom window shows the physical disks as recognized by Windows Server 2016 and the position of the partitions and volumes within the disks—that is, the layout of the partitions and volumes. The bottom window also shows the status and the type of disks.
[image: Image]
FIGURE 19.7 Disk Management console.
NOTE
The physical disks shown in the Disk Management snap-in are the disk configurations as recognized by Windows Server 2016. The actual hardware configuration of the disks might be very different, as it is abstracted by the hardware controller.
For example, what the OS recognizes as Disk 0 with 32GB might actually be a fault-tolerant RAID-1 configuration of two 32GB physical disks that the hard drive controller presents as one disk to the OS.
Auditing the Environment
Auditing is a way to gather and keep track of activity on the network, devices, and entire systems. By default, Windows Server 2016 enables some auditing, whereas many other auditing functions must be manually turned on. This allows for easy customization of the features the system should have monitored.
Auditing is typically used for identifying security breaches or suspicious activity. However, auditing is also important to gain insight into how the network, network devices, and systems are accessed. Windows Server 2008 greatly expanded auditing as compared with earlier versions of Windows. As it pertains to Windows Server 2016, auditing can be used to monitor successful and unsuccessful events on the system. Windows Server 2016 auditing policies must first be enabled before activity can be monitored.
Audit Policies
Audit policies are the basis for auditing events on a Windows Server 2016 system. Depending on the policies set, auditing might require a substantial amount of server resources in addition to those resources supporting the server’s functionality. Otherwise, it could potentially slow server performance. Also, collecting lots of information is only as good as the evaluation of the audit logs. In other words, if a lot of information is captured and a significant amount of effort is required to evaluate those audit logs, the whole purpose of auditing is not as effective. As a result, it is important to take the time to properly plan how the system will be audited. This allows the administrator to determine what needs to be audited, and why, without creating an abundance of overhead.
Audit policies can track successful or unsuccessful event activity in a Windows Server 2016 environment. These policies can audit the success and failure of events. The policies that can be monitored consist of the following:
[image: Image] Audit.
[image: Image] Audit account management—When an account is changed, an event can be logged and later examined.
[image: Image] Audit directory service access—Any time a user attempts to access an Active Directory object that has its own system access control list (SACL), the event is logged.
[image: Image] Audit logon events—Logons over the network or by services are logged.
[image: Image] Audit object access—The object access policy logs an event when a user attempts to access a resource (for example, a printer or shared folder).
[image: Image] Audit policy change—Each time an attempt to change a policy (user rights, account audit policies, trust policies) is made, the event is recorded.
[image: Image] Audit privilege use—Privileged use is a security setting and can include a user employing a user right, changing the system time, and more. Successful or unsuccessful attempts can be logged.
[image: Image] Audit process tracking—An event can be logged for each program or process that a user launches while accessing a system. This information can be very detailed and take a significant amount of resources.
[image: Image] Audit system events—The system events policy logs specific system events such as acomputer restart or shutdown.
The audit policies can be enabled or disabled through the local system policy, domain controller security policy, or group policy objects (GPOs). Audit policies are located within the Computer Configuration\Policies\Windows Settings\Security Settings\Local Policies\Audit Policy folder of the Group Policy Management Editor, as shown in Figure 19.8.
[image: Image]
FIGURE 19.8 Audit policies and the recommended settings.
For the audit policies, the commonly used settings are given in Table 19.3. These should be set on custom policies and linked to the same locations as the Default Domain and Default Domain Controller GPOs. By default, all the policies are Not Defined. Table 19.3 also shows the recommended settings.
TABLE 19.3 Matching Audit Policies Recommended Settings
Audit Policy
Recommended Setting
Audit account logon events
Success and Failure
Audit account management
Success and Failure
Audit directory service access
Success
Audit logon events
Success and Failure
Audit object access
Not Defined
Audit policy change
Success
Audit privilege use
Not Defined
Audit process tracking
Success
Audit system events
Success
The recommended settings are designed to address specific threats. These threats are primarily password attacks and misuse of privilege. Table 19.4 matches the threats to the specific audit policies.
TABLE 19.4 Matching Specific Threats to Audit Policy Recommended Settings
Threat Addressed
Audit Policy
Random password attacks
Audit account logon events (failures)
Audit logon events (failures)
Stolen password attacks
Audit account logon events (successes)
Audit logon events (successes)
Misuse of privileges
Audit account management
Audit directory service access
Audit policy change
Audit process tracking
Audit system events
These recommended settings are sufficient for the majority of organizations. However, they can generate a heavy volume of events in a large organization. Or, there might be a subset of security events that an organization needs to track. In those cases, the next section discusses how to fine-tune the audit policy using audit policy subcategories.
Audit Policy Subcategories
Windows Server 2016 allows more granularity in the setting of the audit policies. In earlier versions of the Windows Server platform, the audit policies could only be set on the general categories. This usually resulted in a large number of security events, many of which are not of interest to the administrator. System management software was usually needed to help parse all the security events to find and report on the relevant entries. Windows Server 2016 exposes additional subcategories under each of the general categories, which can each be set to No Auditing, Success, Failure, or Success and Failure. These subcategories allow administrators to fine-tune the audited events.
Unfortunately, the audit categories do not quite match the audit policies. Table 19.5 shows how the categories match the policies.
TABLE 19.5 Matching Audit Policies to Audit Categories
Audit Policy
Audit Category
Audit account logon events
Account Logon
Audit account management
Account Management
Audit directory service access
DS Access
Audit logon events
Logon/Logoff
Audit object access
Object Access
Audit policy change
Policy Change
Audit privilege use
Privilege Use
Audit process tracking
Detailed Tracking
Audit system events
System
There are 57 different subcategories that can be individually set. These give the administrator and security professionals unprecedented control over the events that will generate security log entries. Table 19.6 lists the categories and the subcategories of audit policies.
TABLE 19.6 Audit Subcategories
Audit Category
Audit Subcategory
System
Security State Change
Security System Extension
System Integrity
IPsec Driver
Other System Events
Logon/Logoff
Logon
Logoff
Account Lockout
IPsec Main Mode
IPsec Quick Mode
IPsec Extended Mode
Special Logon
Network Policy Server
Other Logon/Logoff Events
Object Access
File System
Registry
Kernel Object
SAM
Certification Services
Application Generated
Handle Manipulation
File Share
Filtering Platform Packet Drop
Detailed File ShareFiltering Platform Connection Central Policy StagingRemovable Storage
Other Object Access Events
Privilege Use
Sensitive Privilege Use
Non-Sensitive Privilege Use
Other Privilege Use Events
Detailed Tracking
Process Creation
Process Termination
DPAPI Activity
RPC Events
Policy Change
Audit Policy Change
Authentication Policy Change
Authorization Policy Change
MPSSVC Rule-Level Policy Change
Filtering Platform Policy Change
Other Policy Change Events Device Claim Configuration Change* Device Assessment Membership Certificate Requests*
Account Management
User Account Management
Computer Account Management
Security Group Management
Distribution Group Management
Application Group Management
Other Account Management Event
DS Access
Directory Service Access
Directory Service Changes
Directory Service Replication
Detailed Directory Service Replication
Account Logon
Kerberos Service Ticket Operations
Credential Validation
Kerberos Authentication Service
Other Account Logon Events
*These settings are available only on an Active Directory Certificate Services system.
You can use the auditpol command to get and set the audit categories and subcategories. To retrieve a list of all the settings for the audit categories and subcategories, use the following command:
auditpol /get /category:*
To enable auditing of the Distribution Group Management subcategory of the Account Management category for both success and failure events, use the following command:
auditpol /set /subcategory:"Distribution Group Management"
/success:enable /failure:enable
This command must be run on each domain controller for the policy to have a uniform effect. To get all the options for the Audit Policy command, use the following command:
auditpol /? whether both failure and success events will be logged. The two options are as follows:
[image: Image] Audit object access failure enables you to see if users are attempting to access objects to which they have no rights. This shows unauthorized attempts.
[image: Image] Audit object access success enables you to see usage patterns. This shows misuse of privilege.
Enable the appropriate policy setting in the GPO. It is a best practice to apply the GPO as close to the monitored system as possible, so avoid enabling the auditing on too wide a set of systems.
NOTE
Monitoring both success and failure resource access can place additional strain on the system. Success events can generate a large volume of events.
After enabling the object access policy, the administrator can make auditing changes through the property pages of a file, folder, or a Registry key. If the object access policy is enabled for both success and failure, the administrator can audit both successes and failures for a file, folder, or Registry key.
After object access auditing is enabled, you can easily monitor access to resources such as folders, files, and printers.
Auditing Files and Folders
The network administrator can tailor the way Windows Server 2016, follow these steps:
1. In Windows Explorer, right-click the file or folder to audit and select Properties.
2. Select the Security tab and then click the Advanced button.
3. In the Advanced Security Settings window, select the Auditing tab.
4. Click the Add button to display Audit, shown in Figure 19.9, select which events to audit for successes or failures.
[image: Image]
FIGURE 19.9 The Auditing Entry window.
8. Click OK three times to exit.
New to Windows Server 2016 is the option to define conditions to help limit the scope of an auditing entry. More specifically, security events would only be logged if the defined condition were met.
Conditions can be created from the Auditing Entry screen by simply clicking Add a Condition. This brings up the interface shown in Figure 19.9. Administrators can set conditions based on the following attributes:
User or Device based on Groups (Member of Each, Member of Any, Not Member of Each, Not Member of Any) with a defined list of groups.
For example, one could set the condition to User, Group, Not Member of Any, and then set the groups to Domain Admins and Enterprise Admins and effectively filter the condition to users who are not a member of either of those groups.
NOTE
This step assumes that the audit object access policy has been enabled.
When the file or folder is accessed, an event is written to Event Viewer’s security log. The category for the event is Object Access. An Object Access event is shown in the following security log message:
Log Name: Security
Source: Microsoft-Windows-Security-Auditing
Date: 4/01/2016 6:22:56 PM
Event ID: 4663
Task Category: File System
Level: Information
Keywords: Audit Success
User: N/A
Computer: DC1.companyabc.com
Description:
An attempt was made to access an object.
Subject:
Security ID: COMPANYABC\Administrator
Account Name: Administrator
Account Domain: COMPANYABC
Logon ID: 0x2586e
Object:
Object Server: Security
Object Type: File
Object Name: C:\Confidential\Secret.txt
Handle ID: 0xec
Process Information:
Process ID: 0xfd8
Process Name: C:\Windows\System32\notepad.exe
Access Request Information:
Accesses: WriteData (or AddFile)
AppendData (or AddSubdirectory or CreatePipeInstance)
Access Mask: 0x6
The event is well organized into Subject (who attempted the access), Object (what was acted on), Process Information (what program was used), and Access Request Information (what was done). If the event was Audit Success, the attempt was successful. If the event was Audit Failure, the attempt failed. You can see from the event that the administrator wrote to the file Secret.txt at 6:22:56 p.m. and even that the program Notepad was used.
Auditing Printers
Printer auditing operates on the same basic principles as file and folder auditing. In fact, the same step-by-step procedures for configuring file and folder auditing apply to printers. The difference lies in what successes and failures can be audited. These events include the following:
[image: Image] Print
[image: Image] Manage this printer
[image: Image] Manage documents
[image: Image] Special permissions
These events are stored in Event Viewer’s security log, as are all audit events.
To audit a printer, follow these steps:
1. In the Devices and Printers applet, right-click the printer to audit, and select Printer Properties.
2. Select the Security tab and then click the Advanced button.
3. In the Advanced Security Settings window, select the Auditing tab.
4. Click the Add button to display the Auditing, select which events to audit for successes or failures. The objects to audit will be different than the auditing available for files and folders, as the printer is a different class of object.
8. Click OK four times to exit.
Now access to the printer will generate security log events, depending on the events that were selected to be audited.
Managing Windows Server 2016 Remotely
Windows Server 2016’s built-in feature set allows it to be easily managed remotely. This capability reduces administration time, expenses, and energy by allowing administrators to manage systems from remote locations rather than having to be physically at the system.
Server Manager Remote Management
A carryover from earlier versions of Windows Server is the Server Manager Remote Management, which allows the Server Manager console to remotely manage another server. This makes available all the features of Server Manager to the remote computer, allowing administrators to easily manage Windows Server 2016 servers from a central location.
Several functions of Server Manager Remote Management are disabled by default. This is a security feature, much like Remote Desktop, and so Windows Server 2016 defaults to a more secure state out of the box. To enable the Server Manager Remote Management, follow these steps:
1. Launch Control Panel.
2. Click the Check Firewall Status link.
3. Click Advanced Settings.
4. Click Inbound Rules.
5. Enable the remote management rules you plan to use.
6. Close the Windows Firewall control panel.
Now the system is ready to accept connections from remote Server Manager consoles. To connect to a remote computer with the Server Manager console, right-click a member of a defined server group and select Computer Management.
New to Windows Server 2016 is the ability to launch additional remote management events from the Server Manager console. Administrators can also do the following against remotely managed servers:
[image: Image] Add Roles and Features
[image: Image] Restart Server
[image: Image] Computer Management
[image: Image] Remote Desktop Connection
[image: Image] Windows PowerShell
[image: Image] Configure NIC Teaming
[image: Image] Configure Windows Automatic Feedback
[image: Image] Manage As
Remote Server Administration Tools
The Remote Server Administration Tools set includes a number of tools to manage Windows Server 2016 remotely. This set of tools replaced the Adminpack.msi set of tools that shipped with Windows Server 2003.
There are different tools for the roles (see Table 19.7) and for the features (see Table 19.8).
TABLE 19.7 Remote Server Administration Tools for Roles
Tool
Description
Active Directory Administrative Center
ADAC is the new primary administrative tool covering object management and dynamic access control.
Active Directory Certificate Services Tools
Active Directory Certificate Services Tools include the Certification Authority, Certificate Templates, Enterprise PKI, and Online Responder Management snap-ins.
Active Directory Domain Services (AD DS) Tools
Active Directory Domain Services Tools include Active Directory Users and Computers, Active Directory Domains and Trusts, Active Directory Sites and Services, and other snap-ins and command-line tools for remotely managing Active Directory Domain Services.
Active Directory Lightweight Directory Services (AD LDS) Tools
Active Directory Lightweight Directory Services Tools include Active Directory Sites and Services, ADSI Edit, Schema Manager, and other snap-ins and command-line tools for managing Active Directory Lightweight Directory Services.
Active Directory Rights Management Services (AD RMS) Tools
Active Directory Rights Management Services (AD RMS) Tools includes the Active Directory Rights Management Services (AD RMS) snap-in.
DHCP Server Tools
DHCP Server Tools include the DHCP snap-in.
DNS Server Tools
DNS Server Tools include the DNS Manager snap-in and dnscmd.exe command-line tool.
File Services Tools
File Services Tools include the following: Distributed File System Tools, which include the DFS Management snap-in, and the dfsradmin.exe, dfscmd.exe, dfsdiag.exe, and dfsutil.exe command-line tools. File Server Resource Manager Tools include the File Server Resource Manager snap-in, and the filescrn.exe and storrept.exe command-line tools. Services for Network File System Tools include the Network File System snap-in, and the nfsadmin.exe, showmount.exe, and rpcinfo.exe command-line tools.
Hyper-V Management Tools
Hyper-V Management Tools include the snap-ins and tools for managing the Hyper-V role.
Print and Document Services Tools
Print Services Tools include the Print Management snap-in.
Remote Desktop Services Tools
Remote Desktop Services Tools include the TS RemoteApp Manager, TS Gateway Manager, and TS Licensing Manager snap-ins.
Windows Deployment Services Tools
Windows Deployment Services Tools include the Windows Deployment Services snap-in, wdsutil.exe command-line tool, and Remote Install extension for the Active Directory Users and Computers snap-in.
Windows Server Update Services Tools
Windows Server Update Services Tools includes graphical and PowerShell tools for managing WSUS
Network Policy and Access Services Tools
Network Policy and Access Services Tools includes the Network Policy Server and Health Registration Authority snap-ins.
Remote Access Management Tools
Remote Access Management tools includes graphical and PowerShell tools for managing Remote Access
Volume Activation Tools
Volume Activation Tools console can be used to manage volume activation license keys on a Key Management Service (KMS) host or in Active Directory Domain Services. One can use the Volume Activation Tools to install, activate, and manage one or more volume activation license keys, and to configure KMS settings.
TABLE 19.8 Remote Server Administration Tools for Features
Tool
Description
BitLocker Drive Encryption Tools
BitLocker Drive Encryption Tools include the managebde.exe program.
BITS Server Extensions Tools
BITS Server Extensions Tools include the Internet Information Services (IIS) 10.0 Manager and IIS Manager snap-ins.
Failover Clustering Tools
Failover Clustering Tools include the Failover Cluster Manager snap-in and the cluster.exe command-line tool.
IP Address Management (IPAM) Client
Includes the IPAM snap-in.
Network Load Balancing Tools
Network Load Balancing Tools include the Network Load Balancing Manager snap-in and the nlb.exe and wlbs.exe command-line tools.
SMTP Server Tools
SMTP Server Tools include the Internet Information Services (IIS) 10.0 Manager snap-in.
WINS Server Tools
Windows Internet Naming Service (WINS) Server Tools include the WINS snap-in.
SNMP Tool
Simple Network Management Protocol (SNMP) Tools includes tools for managing SNMP.
Windows System Resource Manager
Windows System Resource Manager (WSRM) is an administrative tool that can control how CPU and memory resources are allocated.
The tools are installed as a feature. You can install all the tools or only the specific ones that you need. To install the Remote Server Administration Tools, follow these steps:
1. Launch Server Manager.
2. Click Add Roles and Features, and then click Next.
3. Select the server from the pool, and then click Next.
4. Click Next to skip past the server roles.
5. Expand RSAT and select the RSAT tools desired, and then click Next.
6. Review the options selected and click Install to proceed. Check the Restart Each Destination Server Automatically If Required check box if you want servers to automatically reboot if needed for their new features.
New to Windows Server 2016 is the ability to close the Roles and Features Installation dialog before the completion of the installation. This will not interrupt the process, and it can be checked on later in the Server Manager interface. The flag in the upper right of the tool indicates whether there are task messages waiting for the administrator.
After the tools are installed, you can manage remote computers by selecting the Connect to Another Computer command from the Action menu.
Windows Remote Management
Windows Remote Management (WinRM) enables an administrator to run command lines remotely on a target server. When WinRM is used to execute the command remotely, the command executes on the target server and the output of the command is piped to the local server. This allows administrators to see the output of those commands.
The commands run securely because the WinRM requires authentication and also encrypts the network traffic in both directions.
WinRM is both a service and a command-line interface for remote and local management of servers. The service implements the WS-Management protocol on Windows Server 2016. WS-Management is a standard web services protocol for management of software and hardware remotely.
In Windows Server 2016, the WinRM service establishes a Listener on the HTTP and HTTPS ports. It can coexist with Internet Information Services (IIS) and share the ports, but uses the /wsman URL to avoid conflicts. The IIS role does not have to be installed for this to work.
In most situations, WinRM will work out of the box, but in some situations the WinRM service must be configured to allow remote management of the target server, and the Windows Firewall must be configured to allow Windows Remote Management traffic inbound. The WinRM service can be configured through GPO or via the WinRM command line. To have the WinRM service listen on port 80 for all IP addresses on the server and to configure the Windows Firewall, execute the following commands on the target server:
1. Select Start, Run.
2. Enter the command winrm quickconfig.
3. Click OK to run the command.
4. Read the output from WinRM. Answer y to the prompt that asks, “Make These Changes [y/n]?”
Fans of PowerShell may recognize that the same task can be accomplished with the Enable-PSRemoting commandlet.
Now the target server is ready to accept commands. For example, suppose an administrator is logged on to a server dc1.companyabc.com and needs to remotely execute a command on branch office server dc3.companyabc.com. These steps assume that WinRM has been configured and the firewall rule has been enabled. To remotely execute the command, follow these steps:
1. Open a command prompt on DC1.
2. Enter the command winrs–r: ipconfig /all.
The output of the command will be shown on the local server (DC1)—in this case, the IP configuration of the target server (DC3).
This is particularly useful when executing a command or a set of commands on numerous servers. Instead of having to log on to an RDP session on each server and execute the command, the command can be remotely executed in a batch file against all the target servers.
PowerShell
The powerful new command-line shell is now integrated into Windows Server 2016. PowerShell is an administrator-focused shell and scripting language that has a consistent syntax that makes it easy to use. It operates on a commandlet paradigm, which is, in effect, mini command-line tools. The syntax for the commandlets is the same as for the PowerShell scripting language, reducing the learning curve of the administrator. In the Windows Server 2016, the PowerShell allows for shells to run against remote systems. This enables administrators to execute commandlets and scripts across the organization from a central console.
PowerShell can run its own scripts and commandlets, as well as legacy scripts such as VBScript (.vbs), batch files (.bat), and Perl scripts (.perl). The shell can even run Windows-based command-line tools. Many of Microsoft’s new applications, such as Microsoft Exchange 2016 and System Center Operations Manager 2012 R2, are integrated with PowerShell and add a host of commandlets to help automate administration.
Print Management Console
The Print Management console enables administrators to manage printers across the enterprise from a single console. It shows the status of printers on the network. It also allows the control of those printers, such as the following:
[image: Image] Pausing or resuming printing
[image: Image] Canceling jobs
[image: Image] Listing printers in Active Directory
[image: Image] Deleting printers
[image: Image] Managing printer drivers
Many of the operational controls support multiselecting printers so that the commands can be run against many printers at once.
The Print Management console is available as a standalone tool as part of the Print and Document Services role installation. It can also be installed on non-print servers as part of the RSAT tools.
The Print Management console supports printers running on a wide variety of OSs, including Windows Server 2016, Windows 7, Windows Server 2008, Windows Vista, Windows Server 2003, Windows XP, and even Windows 2000.
Common Practices for Securing and Managing Windows Server 2016
You can secure and manage a Windows Server 2016 environment with just a few practices. The first is to identify security risks to determine what the organization needs to be concerned about when applying a security policy. The second is that the organization can implement a tool such as Microsoft System Center Operations Manager to monitor the network and simplify management tasks on a day-to-day basis. And the third is to use maintenance practices to help keep the network environment stable and operational.
Identifying Security Risks
A network’s security is only as good as the security mechanisms put into place and the review and identification process. Strong security entails employing Windows Server 2016 security measures, such as authentication, auditing, and authorization controls, but it also means that security information is properly and promptly reviewed. Information that can be reviewed includes Event Viewer logs, service-specific logs, application logs, and performance data.
All the security information for Windows Server 2016 can be logged, but without a formal review and identification process the information is useless. Also, security-related information can be complex and unwieldy depending on what information is being recorded. For this reason, manually reviewing the security information might be tedious, but it can prevent system or network compromise.
The formal review and identification process should be performed daily. Any identified activity that is suspicious or could be potentially risky should be reported and dealt with appropriately. For instance, an administrator reviewing a particular security log might run across some data that might alert him of suspicious activity. This incident would then be reported to the security administrator to take the appropriate action. Whatever the course of action might be in the organization, there should be points of escalation and remediation.
Using System Center Operations Manager 2012 R2 to Simplify Management
Many of the recommendations in this chapter focus on reviewing event logs, monitoring the configuration, and monitoring the operations of the Windows Server 2016 system. This can be difficult to do for an administrator on a daily basis and the problem is proportional to the number of servers that an administrator is responsible for. Microsoft has developed a product to make these tasks easier and more manageable, namely System Center Operations Manager 2012 R2.
System Center Operations Manager 2012 R2 2016 operation and any problems that exist or might occur.
Many other intrinsic benefits are gained by using System Center Operation Manager 2012 R2, including the following:
[image: Image] Event log monitoring and consolidation
[image: Image] Monitoring of various applications, including those provided by third parties
[image: Image] Enhanced alerting capabilities
[image: Image] Assistance with capacity-planning efforts
[image: Image] A customizable knowledge base of Microsoft product knowledge and best practices
[image: Image] Web-based interfaces for reporting and monitoring
See Chapter 22, “Integrating System Center Operations Manager 2016 with Windows Server 2016,” for more details on System Center Operations Manager 2012 R2.
Leveraging Windows Server 2016 Maintenance Practices
Administrators face the often-daunting task of maintaining the Windows Server 2016 environment in the midst of daily administration and firefighting. Little time is spent identifying and then organizing maintenance processes and procedures.
To decrease the number of administrative inefficiencies and the amount of firefighting an administrator must go through, it is important to identify those tasks that are important to the system’s overall health and security. After they have been identified, routines should be set to ensure that the Windows Server 2016 environment is stable and reliable. Many of the maintenance processes and procedures described in the following sections are the most opportune areas to maintain.
Keeping Up with Service Packs and Updates
Service packs (SPs) and updates for both the OS and applications are vital parts to maintaining availability, reliability, performance, and security. Microsoft packages these updates into SPs or individually.
An administrator can update a system with the latest SP or update in several ways: Automatic Windows Updates, DVD, manually entered commands, or Microsoft Windows Server Update Services (WSUS).
NOTE
Thoroughly test and evaluate SPs and updates in a lab environment before installing them on production servers and client machines. Also, install the appropriate SPs and updates on each production server and client machine to keep all systems consistent.
Manual Update or DVD Update
Manual updating is typically done when applying service packs, rather than hotfixes. SPs tend to be significantly larger than updates or hotfixes, so many administrators download the service pack once and then apply it manually to their servers, or the SP can be obtained on DVD.
When an SP DVD is inserted into the drive of the server, it usually launches an interface to install the SP.
In the case of downloaded SPs or of DVD-based SPs, the SP can also be applied manually via a command line. This allows greater control over the install (see Table 19.9), such as by preventing a reboot or to not back up files to conserve space.
TABLE 19.9 Update.exe Command-Line Parameters
Parameter
Description
/Quiet
Quiet Mode (no user interaction or display)
/Unattend
Unattended mode (progress bar only)
/NoDialog
Hide the installation result dialog after commpletion
/NoRestart
Do not restart when installation is complete
-/ForceRestart
Restart after installation
-/WarnRestart[:<seconds>]
Warn and restart automatically if required (default timeout 30 seconds)
/PromptRestart
Prompt if restart is required
Automatic Updates
Windows Server 2016 can be configured to download and install updates automatically using Automatic Windows Updates. With this option enabled, Windows Server 2016 checks for updates, downloads them, and applies them automatically on a schedule. The administrator can just have the updates downloaded, but not installed, to give the administrator more control over when they are installed. Windows Update can also download and install recommended updates, which is new for Windows Server 2016.
When the Windows Server 2016 OS is installed, Windows Update is not configured and, the Server Manager Security Information section shows the Windows Update as Not Configured. This can be an insecure configuration, as security updates will not be applied.
You can configure Windows Updates as follows:
1. Open the Action center by right-clicking the icon next to the date and time on the taskbar.
2. Click All Settings and then click the Windows Update panel.
3. Click Advanced Options to change settings.
4. Select Install Updates Automatically (recommended) and click OK.
The Windows Updates status will change to You’re Set to Automatically Install Updates.
The configuration of Windows Update can be reviewed by clicking the Windows Updates link again. The Windows Update console appears (see Figure 19.10). The figure shows that updates will be installed automatically at 3 a.m. every day. The console also shows when updates were checked for last. In the console, the administrator can also do the following:
[image: Image] Manually check for updates
[image: Image] Change the Windows Updates settings
[image: Image] View the update history
[image: Image] See installed updates
[image: Image] Get updates for more products
[image: Image]
FIGURE 19.10 Windows Update console.
The link to get updates for more products allows the administrator to check for updates not just for the Windows Server 2016 platform, but for other products, as well, such as Microsoft Exchange and Microsoft SQL. Clicking the link launches a web page to authorize the server to check for the broader range of updates.
Clicking the Change Settings link allows the Windows Update setting to be changed. The Change Settings window, shown in Figure 19.11, enables the administrator to adjust the time of installs, to install or just download, and to configure whether to install recommended updates.
[image: Image]
FIGURE 19.11 Windows Update console.
The Windows Updates functionality is a great tool for keeping servers updated with very little administrative overhead, albeit with some loss of control because it is difficult to centrally manage and it lacks any form on consolidated reporting on results.
Windows Server Update Services
Realizing the increased administration and management efforts administrators must face when using Windows Update to keep up with SPs and updates for anything other than small environments, Microsoft has overhauled the Windows Server Update Services (WSUS) client and server versions to minimize administration, management, and maintenance of middle- to large-size organizations. WSUS communicates directly and securely with Microsoft to gather the latest SPs and updates.
Microsoft Windows Server Update Services provides a number of features to support organizations, such as the following:
[image: Image] Support for a broad range of products, such as the Windows OS family, Exchange messaging, SQL Server, Office, System Center family, and Windows Defender.
[image: Image] Automatic download of updates.
[image: Image] Administrative control over which updates are approved, removed, or declined. The Remove option permits updates to be rolled back.
[image: Image] Email notification of updates and deployment status reports.
[image: Image] Targeting of updates to specific groups of computers for testing and for control of the update process.
[image: Image] Scalability to multiple WSUS servers controlled from a single console.
[image: Image] Reporting on all aspects of the WSUS operations and status.
[image: Image] Integration with Automatic Windows Updates.
The SPs and updates downloaded onto WSUS can then be distributed to either a lab server for testing (recommended) or to a production server for distribution. After these updates are tested, WSUS can automatically update systems inside the network.
The following steps install the Windows Server Update Services role:
1. Open the Server Manager console.
2. Click Add Roles or Features.
3. Click Next.
4. Select Role-Based or Feature-Based Installation and click Next.
5. Select the server to receive the WSUS role and click Next.
6. Select the Windows Software Update Service role and click Add Features to accept the related features, and then click Next.
7. Click Next to skip past the features, and then click Next to accept the IIS installation.
8. Review the role services, and then click Next.
9. Review the WSUS requirements, and then click Next.
10. Review the role services, and then click Next.
11. Select a Content location for WSUS downloads, and then click Next.
12. Review the summary, optionally select Restart the Destination Server Automatically If Required, and click Install.
13. Close the Add Roles and Features Wizard.
Unlike other server roles, the binaries for WSUS are downloaded from Microsoft. This ensures that any time WSUS is installed you will always be installing the most current version.
Maintaining Windows Server 2016
Maintaining Windows Server 2016 systems is not an easy task for administrators. They must find time in their firefighting efforts to focus and plan for maintenance on the server systems. When maintenance tasks are commonplace in an environment, they can alleviate many of the common firefighting tasks.
The processes and procedures for maintaining Windows Server 2016 systems can be separated based on the appropriate time to maintain a particular aspect of Windows Server 2016. Some maintenance procedures require daily attention, whereas others might require only quarterly into the daily procedures. Therefore, it is recommended that an administrator take on these procedures each day to ensure system reliability, availability, performance, and security. These procedures are examined in the following three sections.
Checking Overall Server Functionality
Although checking the overall server health and functionality might seem redundant or elementary, this procedure is critical to keeping the system environment and users working productively.
Questions that should be addressed during the checking and verification process including the following:
[image: Image] Can users access data on file servers?
[image: Image] Are printers printing properly? Are there long queues for certain printers?
[image: Image] Is there an exceptionally long wait to log on (that is, longer than normal)?
[image: Image] Can users access messaging systems?
[image: Image] Can users access external resources?
Verifying That Backups Are Successful
To provide a secure and fault-tolerant organization, it is imperative that a successful backup be performed each night. In the event of a server failure, the administrator might be required to perform a restore from tape. Without a backup each night, the IT organization is forced to rely on rebuilding the server without the data. Therefore, the administrator should always back up servers so that the IT organization can restore them with minimum downtime in the event of a disaster. Because of the importance of the backups, the first priority of the administrator each day needs to be verifying and maintaining the backup sets.
If disaster ever strikes, the administrators want to be confident that a system or entire site can be recovered as quickly as possible. Successful backup mechanisms are imperative to the recovery operation; recoveries are only as good as the most recent backups.
Monitoring Event Viewer
Event Viewer is used to check the system, security, application, and other logs on a local or remote system. These logs are an invaluable source of information about the system. The Event Viewer Overview and Summary page in Server Manager is shown in Figure 19.12.
[image: Image]
FIGURE 19.12 The Event Viewer snap-in.
NOTE
Checking these logs often helps your understanding of them. There are some events that constantly appear but are not significant. Events will begin to look familiar, so you will notice when something is new or amiss in your event logs.
All Event Viewer events are categorized either as informational, warning, or error. Best practices for monitoring event logs include the following:
[image: Image] Understanding the events that are being reported
[image: Image] Setting up a database for archived event logs
[image: Image] Archiving event logs frequently
To simplify monitoring hundreds or thousands of generated events each day, the administrator should use the filtering mechanism provided in Event Viewer. Although warnings and errors should take priority, the informational events should be reviewed to track what was happening before the problem occurred. After the administrator reviews the informational events, she can filter out the informational events and view only the warnings and errors.
To filter events, follow these steps:
1. Launch Server Manager.
2. Click All Servers.
3. Right-click the server whose Event Viewer you want to view and click Computer Management.
4. Expand the Event View folder in Computer Management.
5. Select the log from which you want to filter events.
6. Right-click the log and select Filter Current Log.
7. In the log properties window, select the types of events to filter. In this case, check the Critical, Error, and Warning check boxes.
8. Click OK when you have finished.
Figure 19.13 shows the results of filtering on the system log. You can see in the figure that there are a total of 17,941 events. In the message above the log, the filter is noted and also the resulting number of events. The filter reduced the events by a factor of almost 9,000 to 1. This really helps reduce the volume of data that an administrator needs to review.
[image: Image]
FIGURE 19.13 The Event Viewer filter.
Some warnings and errors are normal because of bandwidth constraints or other environmental issues. The more you monitor the logs, the more familiar you will become with the messages and therefore the more likely you will be able to spot a problem before it affects the user community.
TIP
You might need to increase the size of the log files in Event Viewer to accommodate an increase in logging activity. The default log sizes are larger in Windows Server 2016 than in earlier versions of Windows, which were notorious for running out of space.
Weekly Maintenance
Maintenance procedures that require slightly less attention than daily checking are categorized in a weekly routine and are examined in the following sections.
Checking Disk Space
Disk space is a precious commodity. Although the disk capacity of a Windows Server 2016 system can be almost endless, the amount of free space on all drives should be checked at least weekly if not more frequently. Serious problems can occur if there is not enough disk space.
One of the most common disk space problems occurs on data drives where end users save and modify information. Other volumes such as the system drive and partitions with logging data can also quickly fill up.
As mentioned earlier, lack of free disk space can cause a multitude of problems, including the following:
[image: Image] Application failures
[image: Image] System crashes
[image: Image] Unsuccessful backup jobs
[image: Image] Service failures
[image: Image] The inability to audit
[image: Image] Degradation in performance
To prevent these problems from occurring, administrators should keep the amount of free space to at least 25%.
CAUTION
If you need to free disk space, you should move or delete files and folders with caution. System files are automatically protected by Windows Server 2016, but data is not.
Verifying Hardware
Hardware components supported by Windows Server 2016 are reliable, but this does not mean that they will. So, hardware should be monitored weekly to ensure efficient operation.
You can monitor hardware in many different ways. For example, server systems might have internal checks and logging functionality to warn against possible failure, Windows Server 2016.
Running Disk Defragmenter
Whenever files are created, deleted, or modified, Windows Server 2016 does not reside in a contiguous location on the disk.
As fragmentation levels increase, disk access slows. The system must take additional resources and time to find all the cluster groups to use the file. To minimize the amount of fragmentation and give performance a boost, the administrator should use the Disk Defragmenter to defragment all volumes. As mentioned earlier in this chapter, the Disk Defragmenter is a built-in utility that can analyze and defragment volume fragmentation. Fragmentation negatively affects performance because files aren’t efficiently read from disk. There is a command-line version of the tool and a GUI version of the tool.
To use the GUI version of the Disk Defragmenter, follow these steps:
1. Start Disk Defragmenter by running dfrgui from a command prompt or from the PowerShell prompt.
The tool automatically analyzes all the drives and suggests whether to defragment. This only happens if disk defragmentation is not scheduled to run automatically.
2. Select the volumes to defragment.
3. Click Optimize to defragment immediately.
4. The defragmentation runs independently of the Disk Defragmenter GUI, so you can exit the tool while the defragmentation is running by clicking Close.
Unlike earlier versions of the software, the Windows Server 2016 Disk Defragmenter does not show a graphical view of the Disk Defragmenter.
The Disk Defragmenter also enables the administrator to set up a schedule for the backup. This modifies the ScheduledDefrag task in the Task Scheduler (located in Task Scheduler\Task Scheduler Library\Microsoft\Windows\Defrag\). After you select the Run on a Schedule option, you can set the schedule by clicking the Modify Schedule button and select the volumes to be defragmented by clicking the Select Volumes button. New volumes will automatically be defragmented by the task.
Running the Domain Controller Diagnosis Utility
The Domain Controller Diagnosis (DCDIAG) utility is installed with the Active Directory Domain Services roles in Windows Server 2016 and is used to analyze the state of a domain controller (DC) and the domain services. It runs a series of tests, analyzes the state of the DC, and verifies different areas of the system, such as the following:
[image: Image] Connectivity
[image: Image] Replication
[image: Image] Topology integrity
[image: Image] Security descriptors
[image: Image] Netlogon rights
[image: Image] Intersite health
[image: Image] Roles
[image: Image] Trust verification
DCDIAG should be run on each DC on a weekly basis or as problems arise. DCDIAG’s syntax is as follows:
dcdiag.exe /s:<Directory Server>[:<LDAP Port>] [/u:<Domain>\<Username>
/p:*|<Password>|””]
[/hqv] [/n:<Naming Context>] [/f:<Log>] [/x:XMLLog.xml]
[/skip:<Test>] [/test:<Test>]
Parameters for this utility are as follows:
[image: Image] /h—Display this help screen.
[image: Image] /s—Use <Domain Controller> as the home server. This is ignored for DCPromo and RegisterInDNS tests, which can only be run locally.
[image: Image] /n—Use <Naming Context> as the naming context to test. Domains can be specified in NetBIOS, DNS, or distinguished name (DN) format.
[image: Image] /u—Use domain\username credentials for binding with a password. Must also use the /p option.
[image: Image] /p—Use <Password> as the password. Must also use the /u option.
[image: Image] /a—Test all the servers in this site.
[image: Image] /e—Test all the servers in the entire enterprise. This parameter overrides the /a parameter.
[image: Image] /q—Quiet; print only error messages.
[image: Image] /v—Verbose; print extended information.
[image: Image] /i—Ignore; ignore superfluous error messages.
[image: Image] /fix—Fix; make safe repairs.
[image: Image] /f—Redirect all output to a file <Log>; /ferr redirects error output separately.
[image: Image] /c—Comprehensive; run all tests, including nondefault tests but excluding DCPromo and RegisterInDNS. Can use with /skip.
[image: Image] /skip:<Test>—Skip the named test. Do not use in a command with /test.
[image: Image] /test:<Test>—Test only the specified test. Required tests will still be run. Do not use with the /skip parameter.
[image: Image] /x:<XMLLog.xml>—Redirect XML output to <XMLLog.xml>. Currently works with the /test:dns option only.
[image: Image] /xsl:<xslfile.xsl or xsltfile.xslt>—Add the processing instructions that reference a specified style sheet. Works with the /test:dns /x:<XMLLog.xml> option only.
The command supports a variety of tests, which can be selected. Some tests are run by default and others need to be requested specifically. The command line supports selecting tests explicitly (/test) and skipping tests (/skip). Table 19.10 shows valid tests that can be run consistently.
TABLE 19.10 DCDIAG Tests
Test Name
Description
Advertising
Checks whether each DC is advertising itself and whether it is advertising itself as having the capabilities of a DC.
CheckSDRefDom
Checks that all application directory partitions have appropriate security descriptor reference domains.
CheckSecurityError
Locates security errors and performs the initial diagnosis of the problem. This test is not run by default and has to be requested with the /test option.
Connectivity
Tests whether DCs are DNS registered, pingable, and have LDAP/RPC connectivity. This is a required test and cannot be skipped with the /skip option.
CrossRefValidation
This test looks for cross-references that are in some way invalid.
CutoffServers
Checks for servers that will not receive replications because their partners are down. This test is not run by default and has to be requested with the /test option.
DCPromo
Tests the existing DNS infrastructure for promotion to the domain controller.
DNS
Checks the health of DNS settings for the whole enterprise. This test is not run by default and has to be requested with the /test option.
FrsEvent
Checks to see if there are any operation errors in the file replication server (FRS). Failing replication of the SYSVOL share can cause policy problems.
DFSREvent
Checks to see if there are any operation errors in the DFS.
LocatorCheck
Checks that global role holders are known, can be located, and are res | https://it.b-ok.org/book/3510284/92da64 | CC-MAIN-2020-05 | en | refinedweb |
In the very first post, I wrote simple Teamcenter login program. Following is the step-wise description of Teamcenterlogin program.
All ITK programs must include tc/tc.h. It has the prototype for ITK_init_module and the definition of many standard datatypes, constants, and functions that almost every ITK program requires, such as tag_t and ITK_ok.
Normal Execution of c\c++ program requires main() in same way ITK has ITK_User_main(int argc,char* argv[]) function from which main program gets executed.
ITK_ok gives the return value of ITK functions .it is an integer value .If value return 0 means code runs successfully .and if value return other than 0 means code get failed.
For login into Teamcenter we have two functions
- ITK_auto_login()
- Description: If the value of ITK_auto_login is set to true, the user does not need to enter in a user name, password, or group in the command line. Auto logon uses operating system user names and passwords to log on to Teamcenter. However, if the user wants to use a login name other than their operating system name, they may use the command line format.
- Values : TRUE Enables automatic logon. FALSE Suppresses automatic logon.
- ITK_init_module( userName, password, group);
- If your program is called without the ITK_auto_login function, supply the arguments for user, password and group.
If program fails to login then it returns non -zero value of ITK_ok
Memory management in Teamcenter
Data types in ITK programming
Teamcenter ITK Programming uses same data types that are there in C\C++ languages.
Example:- int ,char*, enum ,struct etc
The new APIs use the char* type instead of fixed char array i.e char filesize[50] size in the input and output parameters. The new APIs use dynamic buffering to
replace the fixed-size buffering method.fixed-size array got deprecated from TC 10.1 onwards.
Special data types
tag_t
tag_t is special data type where All objects in the ITK are identified by tags of C type tag_t. It is a unique identifier of a reference (typed, untyped, or external )
An unset tag_t variable is assigned the NULLTAG for null value
Tags may be compared by use of the C language == and != operators. An unset tag_t
variable is assigned the NULLTAG null value
Example :- tag_t itemTag
if(itemTag==NULLTAG) or if(itemTag!=NULLTAG)
Creation of DLL in ITK
Teamcenter also comes with a set of include files that are similar with C include files.
For example, instead of using:
#include “string.h”
You could use:
#include <fclasses/tc_string.h>
fclasses/tc_errno.h
fclasses/tc_limits.h
fclasses/tc_math.h
fclasses/tc_stat.h
fclasses/tc_stdarg.h
fclasses/tc_stddef.h etc
These include files are used in Teamcenter to insulate it from the operating system.
We will more post on PLM TUTORIAL–>Teamcenter Customization in upcoming days.
Kindly provide your valuable comment on below Comment section and also have you any question kindly ask to ASK QUESTION in FORUM. Our Team will try to provide the best workaround.
2 thoughts on “Explanation of ITK Login Program”
this is really helpful to start customization ..can you please provide some more help for basic itk programing
For ITK learning this is really really Helpful…Plz provide more itk programs ASAP.
Thank you.. | http://globalplm.com/explanation-of-itk-login-program/ | CC-MAIN-2020-05 | en | refinedweb |
Structure
Before we start let’s discuss a little bit the correct (or rather most preferable) project structure including tests. In order to have clean and effective code, master test folder shall be at the same level as master code folder, like:
sample_ | ??? core.py project: ??? jlabs | ??? __init__.py | ??? functions.py ??? tests | ??? __init__.py | ??? test_core.py | ??? test_functions.py ??? README.rst ??? setup.py
Of course, test folder is preferable when our test suite is bigger than one file – otherwise simple test.py is sufficient. From the other hand keeping 2-digit number of tests in one file is not a good idea too so I suggest creating test folder and dividing test logically in separate files.
First test
As mentioned at the beginning of this article unittest is a build-in python library so we do not have to take any actions before we start creating any test. Every test class in unittest has to inherit from unittest.TestCase class. Every method in this class with a name starting with ‘test’ will be treated as method representing test – this is a naming convention informing runner what to execute. Let’s write our first test with basic assertion:
import unittest class TestFunctions(unittest.TestCase): def test_basic_01(self): self.assertEqual(20 + 20, 40) self.assertEqual(20 + 20, 41, '20+20 is not 41')
In second assertion I added a custom message that will appear in case of failure (in my test always).
Ran 1 test in 0.003s FAILED (failures=1) 20+20 is not 41 41 != 40 Expected :40 Actual :41
Those are all the basics required to create a test for your code. Of course, it is a trivial example – real scenarios would actually test some code which need to be imported into test class and its functionality will be checked:
import unittest from jlabs.core import Person class TestCore(unittest.TestCase): def test_core_01(self): me = Person('me') self.assertTrue(me.is_handsome, 'I am not handsome')
How to run
Now we know how to write a code for testing and in this chapter we will get to know how to execute it. Of course, there is more than one way to do it. First one is running it from command line with:
python -m unittest discover
It will run all the tests files that are modules – in our case TestFunctions and TestCore and will produce execution report:
FF ====================================================================== FAIL: test_basic_01 (tests.test_basic.TestBasic) ---------------------------------------------------------------------- Traceback (most recent call last ): File "C:\dev\sample_project\tests\test_functions.py", line 7, in test_basic_01 self.assertEqual(20 + 20, 41, '20+20 is not 41') AssertionError: 20+20 is not 41 ====================================================================== FAIL: test_core_01 (tests.test_core.TestCore) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\dev\sample_project\tests\test_core.py", line 9, in test_core_01 self.assertTrue(me.is_handsome, 'I am not handsome') AssertionError: I am not handsome ---------------------------------------------------------------------- Ran 2 tests in 0.001s FAILED (failures=2)
We can narrow down the tests we want to execute by adding pattern to the command:
python -m unittest discover -p *_core.py
What will execute tests from modules matching given pattern. We can also add start directory option (what make sense when you have subfolders in tests directory):
python -m unittest discover –s tests/subfolder
Another way to launch tests with a better level of control is to create a custom script (run_tests.py) to do it where we can specify exactly what shall be executed:
from unittest import TestLoader, TestSuite, TextTestRunner from tests.test_functions import TestBasic modules_to_run = [TestBasic] suites = list(TestLoader().loadTestsFromTestCase(t) for t in modules_to_run) TextTestRunner().run(TestSuite(suites))
than we can execute it simply by:
python run_tests.py
Generated report will be similar. The biggest advantage of the second option besides full control on tests to be run is possibility to create custom test runner with different output. It is very convenient when we need report in e.g. HTML format or other fitting some continuous integration tool (like TeamCity).
Assertions
We know how to write tests and how to execute them. Next step will be to get to know what can we verify within the test and how. To check specific functionality we need assertions – an expression surrounding some testable logic what basically simplifies to checking if output is true. Of course, there is possibility to use only one type of assertion in our test code but it is not elegant and recommended solution. Unittest provides us many different types of assertions:
- comparable – group of assertions that can evaluate 2 values relative to each other (are they equal, is one greater than another, and so on)
def test_basic_02(self): self.assertEqual(20 + 20, 40) self.assertGreater(20 + 20, 39) self.assertLessEqual(20 + 20, 40) self.assertTrue(20 + 20 == 40) self.assertIsNotNone(20)
- iterable – assertions operating on sequences
def test_basic_03(self): self.assertEqual([1, 2, 3], [1, 2, 3]) self.assertIn(2, [1, 2, 3]) self.assertDictEqual({1: 'a', 2: 'b'}, {2: 'b', 1: 'a'}) self.assertDictContainsSubset({1: 'a'}, {1: 'a', 2: 'b'})
- exceptions – assertions dealing with exceptions
def test_basic_04(self): with self.assertRaises(Exception): raise Exception('ERROR') with self.assertRaisesRegexp(Exception, 'ERR.+'): raise Exception('ERROR')
- instantional – comparing objects and checking if they are instances of class
def test_basic_05(self): self.assertIsInstance('str', str) self.assertIs(None, None)
- failure – failing test on purpose when specific situation happen
def test_basic_06(self): a = 5 if a < 6: self.fail('a < 6')
Organizing your code
When we have everything covered in terms of functionality – all assertions are in place we can start thinking about our code transparency and effectiveness. It is a good practice not to write long tests but rather short ones covering little piece of logic, because every assertion failure causes tests being stopped and not executed further (so everything after failed assertion will be skipped). When we have such granularity, it is very probable we could have code duplications and to avoid that we can use pre- and post-processing blocks called setUp() and tearDown(). These methods define actions that will be taken before and after each test. If setup fails test will not be executed and will end with failure status. If setup succeed teardown will be executed no matter what the test’s status is. Also whole TestSuite (module with tests defined) can have its setUpClass() and tearDownClass() methods defined – these will be executed before first test within TestSuite and after last one and mast be annotated as @classmethod. Below there is a simple example of these methods usage:
import unittest from jlabs.core import PersonDbFactory class TestCore(unittest.TestCase): factory = None @classmethod def setUpClass(cls): cls.factory = PersonDbFactory() cls.factory.connect() def setUp(self): self.me = self.factory.get_person('me') def tearDown(self): self.me.destroy() def test_core_handsome(self): self.assertFalse(self.me.is_handsome, 'I am not handsome') def test_core_smart(self): self.assertTrue(self.me.is_smart, 'I am not smart')
Running this suite will give us output like:
Ran 2 tests in 0.002s OK Connecting to DB Gathering person from DB Destroying person object Gathering person from DB Destroying person object Disconnecting from DB
This demonstrates setup() and tearDown() are executed before every test while setUpClass() and tearDownClass() are executed once.
There are also 3 useful annotations allowing us to control test execution and skipping tests.
- @skip – just skipping the test
- @skipIf – adding condition when this test shall not be executed
- @skipUnless – adding condition when this test shall not be skipped
Summary
We reached the end of the article. I hope after lecture one can successfully write and execute tests of its code. Please keep in mind that unittest is a very universal library and it is not dedicated for tests on unit level only. It provides the test template and what is the subject of test depends on us. | https://blog.j-labs.pl/2019/07/Test-Automation-with-Python | CC-MAIN-2020-05 | en | refinedweb |
This is the GSoC 2010 - Minix 3 Firewall project page. This page describes the design evolution and provides a documentation of the developed features.
Student: Stefano Cordio [ stefano (dot) cordio (at) gmail (dot) com ]
Mentors: Cristiano Giuffrida and Lorenzo Cavallaro
SVN branch name: src.r7062.firewall (Tracking Current)
Last compiled trunk: r9022
Last branch rebase: r9022
NetBSD version: 5.1 (GENERIC)
The goal of this project is to implement a firewall for Minix 3. It is preferable to port an existing firewall from another operating system or, alternatively, make a new one that has a similar approach to one that can not be ported.
The NetBSD kernel provides a Packet Filter Interface called pfil which supports the registration of callback functions to special hooks inside of the management logic of network packets.
This project can be divided in two steps:
To follow the firewall development, the guidelines are similar to those described in the TrackingCurrent page. You only need a few attentions:
# cd /usr # mv src src.trunk # mkdir src.firewall # chown bin src.firewall # ln -s src.firewall src
$ svn --username anonymous checkout src.firewall
Revision 9591:
mkdir /usr/include/pfil/opt
Revision 9586:
mkdir /usr/include/pfil/minix
Revision 9071:
mkdir /usr/include/pfil mkdir /usr/include/pf mkdir /usr/include/pf/minix mkdir /usr/include/pf/net mkdir /usr/include/pf/opt
cp /usr/src/etc/pf.conf /etc/pf.conf cp /usr/src/etc/pf.os /etc/pf.os
Once the system is built and after a reboot, you can run the tests under the test/pf folder:
# cd /usr/src/test/pf # make run
The pfil is a framework that offers two main capabilities:
To understand how this framework works, its internals must be analyzed.
The NetBSD base system source code is in the directory /usr/src on a NetBSD box. The kernel is in the directory /usr/src/sys. All paths in this chapter are relative to the kernel source directory. TAILQ_* and LIST_* macros are defined in the <sys/queue.h> header file and refer to specific implementation of lists, so there is no need to deepen these now.
A hook is an entity that allows applications to run their callback functions at special points of the networking code. It is defined as following:
struct packet_filter_hook { TAILQ_ENTRY(packet_filter_hook) pfil_link; int (*pfil_func)(void *, struct mbuf **, struct ifnet *, int); void *pfil_arg; int pfil_flags; };
The pfil_link field is used to insert the packet_filter_hook object in the functions list of the head to which it belongs (see below).
The pfil_arg field is the pointer of the function argument.
The pfil_flags field determines when the function must be called, it may take the following values: «Anchor(pfil_flags)»
PFIL_IN call the function on incoming packets PFIL_OUT call the function on outgoing packets PFIL_ALL call the function on all of the above PFIL_IFADDR call the function on interface reconfiguration PFIL_IFNET call the function on interface attach/detach PFIL_WAITOK as reported in the pfil man page: "OK to call malloc with M_WAITOK" -- need more understanding here :)
The pfil_func field is the pointer of the associated function. A generic function is declared as following:
int pfil_func(void *, struct mbuf **, struct ifnet *, int);
The return value should be 0 if the packet processing is to continue or an errno value if the processing is to stop.
A head is a filtering point where it is possible to attach a hook. It is defined as following:
typedef TAILQ_HEAD(pfil_list, packet_filter_hook) pfil_list_t; struct pfil_head { pfil_list_t ph_in; pfil_list_t ph_out; pfil_list_t ph_ifaddr; pfil_list_t ph_ifnetevent; int ph_type; union { u_long phu_val; void *phu_ptr; } ph_un; LIST_ENTRY(pfil_head) ph_list; };
PFIL_TYPE_AF address family hook PFIL_TYPE_IFNET interface hook
Depending on the value assumed by the previous field, the ph_un union contains different values and the following macros simplify the access to it:
#define ph_af ph_un.phu_val /* the ph_un field contains an AF_* type (e.g. IPv4 type is AF_INET, IPv6 type is AF_INET6) */ #define ph_ifnet ph_un.phu_ptr /* the ph_un field contains an ifnet pointer */
Finally, the ph_list field is used to insert the pfil_head object in the global list of head objects named pfil_head_list and defined as follow:
LIST_HEAD(, pfil_head) pfil_head_list = LIST_HEAD_INITIALIZER(&pfil_head_list);
The framework offers two functions to place a new head:
int pfil_head_register(struct pfil_head *ph); int pfil_head_unregister(struct pfil_head *ph);
In both functions, the ph parameter is the object pointer to be register.
A network component can place a new head by setting the ph_type and ph_un fields and calling the pfil_head_register() function. In this way the new head is added to the global list of head and it is possible getting it to attach a new hook.
Instead, the call of the pfil_head_unregister() function causes the removal from the global list of the specified head .
An application can register its callback function by registering a new hook with an existing head. The functions provided for this purpose by the framework are:
struct pfil_head * pfil_head_get(int type, u_long val); int pfil_add_hook(int (*func)(void *, struct mbuf **, struct ifnet *, int), void *arg, int flags, struct pfil_head *ph); int pfil_remove_hook(int (*func)(void *, struct mbuf **, struct ifnet *, int), void *arg, int flags, struct pfil_head *ph);
At first, the app must identify the head that should be used by calling the pfil_head_get() function and specifying its type and value. Once the head is obtained, the recording of the new hook is done by calling the pfil_add_hook() function and passing as parameter the name of the target callback function.
Removing a registered hook is done by calling the pfil_remove_hook() function.
The framework provides the function pfil_run_hooks() to perform the callback functions registered to a head. It is the following:
int pfil_run_hooks(struct pfil_head *ph, struct mbuf **mp, struct ifnet *ifp, int dir);
The ph parameter is the target head.
The mp parameter holds the data received from the network (refer to the second argument explained here for further informations).
The ifp parameter represents the network device logically connected with this head (refer to the third argument explained here for further informations).
The dir parameter determines which list must be traversed (refer to the pfil_flags values of the packet_filter_hook structure).
This function loads the head and runs through the list of hooks, launching the associated functions.
Part of the IPv4 networking logic is implemented in the “netinet/ip_input.c” and “netinet/ip_output.c” source files. This file contains the steps that the kernel module crosses to ensure the support to the packet filters. The steps are:
struct pfil_head inet_pfil_hook;
inet_pfil_hook.ph_type = PFIL_TYPE_AF; inet_pfil_hook.ph_af = AF_INET; pfil_head_register(&inet_pfil_hook);
if (pfil_run_hooks(&inet_pfil_hook, &m, m->m_pkthdr.rcvif, PFIL_IN) != 0) return; /* stop processing the packet */ else /* continue processing the packet */
if (pfil_run_hooks(&inet_pfil_hook, &m, ifp, PFIL_OUT) != 0) return; /* stop processing the packet */ else /* continue processing the packet */
In the “net/if.c” source file there is part of the management of network interfaces. Here the kernel registers other heads with pfil, one for each active interface and a global one for all interfaces.
The global head is declared as follows:
struct pfil_head if_pfil;
and registered as follows:
if_pfil.ph_type = PFIL_TYPE_IFNET; if_pfil.ph_ifnet = NULL; pfil_head_register(&if_pfil);
Note that the field ph_ifnet is NULL because that head is not associated with any specific interface.
The hook execution code of this head can be found in three places:
int in_control(struct socket *so, u_long cmd, void *data, struct ifnet *ifp, struct lwp *l) { switch (cmd) { *.. case SIOCSIFADDR: /* set interface IP address */ pfil_run_hooks(&if_pfil, (struct mbuf **)SIOCSIFADDR, ifp, PFIL_IFADDR); *.. case SIOCAIFADDR: /* add interface IP address */ pfil_run_hooks(&if_pfil, (struct mbuf **)SIOCAIFADDR, ifp, PFIL_IFADDR); *.. case SIOCDIFADDR: /* delete interface IP address */ pfil_run_hooks(&if_pfil, (struct mbuf **)SIOCDIFADDR, ifp, PFIL_IFADDR); *.. } }
static void sppp_set_ip_addrs(struct sppp *sp, uint32_t myaddr, uint32_t hisaddr) { *.. pfil_run_hooks(&if_pfil, (struct mbuf **)SIOCAIFADDR, ifp, PFIL_IFADDR); *.. } static void sppp_clear_ip_addrs(struct sppp *sp) { *.. pfil_run_hooks(&if_pfil, (struct mbuf **)SIOCDIFADDR, ifp, PFIL_IFADDR); *.. }
The “net/if.c” source file contains also the function if.c::if_attach() which is called to attach an interface to the list of the active interfaces. The definition is:
void if_attach(struct ifnet *ifp);
The ifp argument represents the interface to be enabled.
The function initializes and registers one of the field in the struct ifnet, i.e. the if_pfil field of type struct pfil_head, as follows:
ifp->if_pfil.ph_type = PFIL_TYPE_IFNET; ifp->if_pfil.ph_ifnet = ifp; pfil_head_register(&ifp->if_pfil);
After the registration, there is the call to pfil_run_hooks() on the if_pfil because the hooks on this type of head should be invoked whenever the associated interface is attached/detached or reconfigured:
pfil_run_hooks(&if_pfil, (struct mbuf **)PFIL_IFNET_ATTACH, ifp, PFIL_IFNET);
The pf packet filter interacts with pfil in two ways:
The first type of recording is made in the “dist/pf/net/pf_ioctl.c” source file.
The pf_ioctl.c::pf_pfil_attach() function obtains the head pointer and then registers the pf_ioctl.c::pfil4_wrapper() function as a hook on it:
struct pfil_head *ph_inet; ph_inet = pfil_head_get(PFIL_TYPE_AF, AF_INET); pfil_add_hook((void *)pfil4_wrapper, NULL, PFIL_IN|PFIL_OUT, ph_inet);
The other recording type is made in the “dist/pf/net/pf_if.c” source file by the pf_if.c::pfi_initialize() function. Unlike the previous one, there is not the research phase of the head pointer because this is visible through the <net/pfil.h> header file which exports the object declared in the “net/if.c” source file. Therefore, it registers pf_if.c::pfil_ifnet_wrapper and pf_if.c::pfil_ifaddr_wrapper as hooks on the if_pfil head:
pfil_add_hook(pfil_ifnet_wrapper, NULL, PFIL_IFNET, &if_pfil); pfil_add_hook(pfil_ifaddr_wrapper, NULL, PFIL_IFADDR, &if_pfil);
Integrating pfil on Minix is achieved primarily by defining a new compile-time flag named PFIL_HOOKS, which allows to enable/disable packet filtering module, and by the insertion of the “net/pfil.h” and “net/pfil.c” source files in the inet source directory (servers/inet/). It is important to carefully choose where to initialize/register the interface/IPv4 heads and where to execute the hook callbacks in the networking flow. In order to reduce the changes to adapt pf, the best approach that can be followed is to keep the interface offered to it by pfil, using wrapper functions for any conversion between the interface and the real implementation.
The Minix3 base system source code is in the directory /usr/src on a Minix box, all paths in this chapter are relative to this source directory.
Work in progress…
Referring to the previous example, the positioning of the IPv4 head is achieved through the following steps:
servers/inet/generic/ip.c:
#ifdef PFIL_HOOKS #include "pfil.h" #endif ... #ifdef PFIL_HOOKS PUBLIC struct pfil_head inet_pfil_hook; #endif
servers/inet/generic/ip.c:
PUBLIC void ip_init() { int i; /* this declaration already exists*/ *.. #ifdef PFIL_HOOKS inet_pfil_hook.ph_type = PFIL_TYPE_IFNET; inet_pfil_hook.ph_ifnet = NULL; if ( (i = pfil_head_register(&inet_pfil_hook)) != 0) printf("inet: ip_init: WARNING: unable to register pfil hook, error %d\n", i); #endif }
servers/inet/generic/ip_read.c:
#ifdef PFIL_HOOKS #include "pfil.h" #endif #ifdef PFIL_HOOKS EXTERN struct pfil_head inet_pfil_hook; #endif PUBLIC void ip_arrived */ dest= ip_hdr->ih_dst; if (dest == ip_port->ip_ipaddr) { *.. } PUBLIC void ip_arrived_broadcast */ ip_port_arrive (ip_port, pack, ip_hdr); }
servers/inet/generic/ip_write.c:
#ifdef PFIL_HOOKS #include "pfil.h" #endif #ifdef PFIL_HOOKS EXTERN struct pfil_head inet_pfil_hook; #endif PUBLIC int ip_send(fd, data, data_len) int fd; acc_t *data; size_t data_len; { int r; /* this declaration already exists*/ #ifdef PFIL_HOOKS struct mbuf *m; struct ifnet *ifp; #endif /* PFIL_HOOKS */ *.. #ifdef PFIL_HOOKS /* mapping the outgoing packet in the mbuf structure and the * interface info in the ifnet structure */ /* * Run through list of hooks for output packets. */ if ((r = pfil_run_hooks(&inet_pfil_hook, &m, ifp, PFIL_OUT)) != 0) return (r); if (m == NULL) return (r); #endif /* PFIL_HOOKS */ ip_hdr_chksum(ip_hdr, hdr_len); /* this function call already exists*/ *.. }
Referring to the previous example, the positioning of the interface heads is achieved through the following steps:
This period is focused on the study of pfil (the NetBSD packet filter interface) and pf (the NetBSD packet filter), assessing their true portability on the Minix environment. This period is also focused on the analysis of the Minix networking framework, i.e. the inet server source code.
Completion of the wiki chapter: “The NetBSD Packet Filter Interface”.
Branch rebased to r7148. Created the new gsoc_test folder in the branch as standalone environment. Analyzed the dependencies of the NetBSD mbuf structure and adapted its source files in the gsoc_test folder.
Completion of the porting of the pfil framework in the gsoc_test folder, resolving all data dependencies of the structures. Branch rebased to r7268.
Inactivity due to a medical intervention.
Depth study of the Minix ip_send() and the NetBSD ip_output() functions. Completion of the positioning of the pfil_run_hooks() calls in the IPv4 packet processing flow. Branch rebased to r7538.
Merged the changes in inet, adding comments to the inet::ip_arrive(), inet::ip_arrive_broadcast() and inet::ip_send() functions. Branch rebased to r7657.
Planning of the mid-term project with the mentors: implementation of most of the functionality of the firewall sheep/goat project, using the pfil infrastructure. Creation of a new device, /dev/simplepf, with no functionality (i.e. no read(), no write(), no ioctl(), etc.).
Added open(), close and ioctl() support to the new simplepf device. Release of the sheep/goat project for the mid-term evaluation. Reorganization of the pf-related file hierarchy. Branch rebased to r7778. | https://wiki.minix3.org/doku.php?id=soc:2010:firewall | CC-MAIN-2020-05 | en | refinedweb |
one_hot¶
paddle.fluid.layers.
one_hot(input, depth, allow_out_of_range=False)[source]
WARING: This OP requires the last dimension of Tensor shape must be equal to 1. This OP will be deprecated in a future release. It is recommended to use fluid. one_hot .
The operator converts each id in the input to an one-hot vector with a
depthlength. The value in the vector dimension corresponding to the id is 1, and the value in the remaining dimension is 0.
The shape of output Tensor or LoDTensor is generated by adding
depthdimension behind the last dimension of the input shape.
Example 1 (allow_out_of_range=False): input: X.shape = [4, 1] X.data = [[1], [1], [3], [0]] depth = 4 output: Out.shape = [4, 4] Out.data = [[0., 1., 0., 0.], [0., 1., 0., 0.], [0., 0., 0., 1.], [1., 0., 0., 0.]] Example 2 (allow_out_of_range=True): input: X.shape = [4, 1] X.data = [[1], [1], [5], [0]] depth = 4 allow_out_of_range = True output: Out.shape = [4, 4] Out.data = [[0., 1., 0., 0.], [0., 1., 0., 0.], [0., 0., 0., 0.], # This id is 5, which goes beyond depth, so set it all-zeros data. [1., 0., 0., 0.]] Example 3 (allow_out_of_range=False): input: X.shape = [4, 1] X.data = [[1], [1], [5], [0]] depth = 4 allow_out_of_range = False output: Throw an exception for Illegal value The second dimension in X is 5, which is greater than depth. Allow_out_of_range =False means that does not allow the word id to exceed depth, so it throws an exception.
- Parameters
input (Variable) – Tensor or LoDTensor with shape \([N_1, N_2, ..., N_k, 1]\) , which contains at least one dimension and the last dimension must be 1. The data type is int32 or int64.
depth (scalar) – An integer defining the
depthof the one hot dimension. If input is word id, depth is generally the dictionary size.
allow_out_of_range (bool) – A bool value indicating whether the input indices could be out of range \([0, depth)\) . When input indices are out of range, exceptions
Illegal valueis raised if
allow_out_of_rangeis False, or zero-filling representations is created if it is set True. Default: False.
- Returns
The one-hot representations of input. A Tensor or LoDTensor with type float32.
- Return type
Variable
Examples
import paddle.fluid as fluid # Correspond to the first example above, where label.shape is [4, 1] and one_hot_label.shape is [4, 4]. label = fluid.data(name="label", shape=[4, 1], dtype="int64") one_hot_label = fluid.layers.one_hot(input=label, depth=4) | https://www.paddlepaddle.org.cn/documentation/docs/en/api/layers/one_hot.html | CC-MAIN-2020-05 | en | refinedweb |
freitasm: You mean static IP address?
Dochart:freitasm: You mean static IP address?
Can’t you still get a public ip address (dynamic ip address which changes a few times each month) if you want to opt out of CGNAT without having to pay for a static ip.
P.S: sorry if I’m mixing up the terminology.
it appears 2D are statically assigning, likely it's one or the other... would make no sense for them to build out whole new functionality.. just another thing to maintain otherwise.
#include <std_disclaimer>
Any comments made are personal opinion and do not reflect directly on the position my current or past employers may have. | https://www.geekzone.co.nz/forums.asp?forumid=85&topicid=255661&page_no=24 | CC-MAIN-2020-05 | en | refinedweb |
The golden ratio is the larger root of the equation
φ² – φ – 1 = 0.
By analogy, golden ratio primes are prime numbers of the form
p = φ² – φ – 1
where φ is an integer. To put it another way, instead of solving the equation
φ² – φ – 1 = 0
over the real numbers, we’re looking for prime numbers p where the equation can be solved in the integers mod p. [1]
Application
When φ is a large power of 2, these prime numbers are useful in cryptography because their special form makes modular multiplication more efficient. (See the previous post on Ed448.) We could look for such primes with the following Python code.
from sympy import isprime for n in range(1000): phi = 2**n q = phi**2 - phi - 1 if isprime(q): print(n)
This prints 19 results, including n = 224, corresponding to the golden ratio prime in the previous post. This is the only output where n is a multiple of 32, which was useful in the design of Ed448.
Golden ratio primes in general
Of course you could look for golden ratio primes where φ is not a power of 2. It’s just that powers of 2 are the application where I first encountered them.
A prime number p is a golden ratio prime if there exists an integer φ such that
p = φ² – φ – 1
which, by the quadratic theorem, is equivalent to requiring that m = 4p + 5 is a square. In that case
φ = (1 + √m)/2.
Here’s some code for seeing which primes less than 1000 are golden ratio primes.
from sympy import primerange def issquare(m): return int(m**0.5)**2 == m for p in primerange(2, 1000): m = 4*p + 5 if issquare(m): phi = (int(m**0.5) + 1) // 2 assert(p == phi**2 - phi - 1) print(p)
By the way, there are faster ways to determine whether an integer is a square. See this post for algorithms.
(Update: Aaron Meurer pointed out in the comments that SymPy has an efficient function
sympy.ntheory.primetest.is_square for testing whether a number is a square.)
Instead of looping over primes and testing whether it’s possible to solve for φ, we could loop over φ and test whether φ leads to a prime number.
for phi in range(1000): p = phi**2 - phi - 1 if isprime(p): print(phi, p)
Examples
The smallest golden ratio prime is p = 5, with φ = 3.
Here’s a cute one: the pi prime 314159 is a golden ratio prime, with φ = 561.
The golden ratio prime that started this rabbit trail was the one with φ = 2224, which Mike Hamburg calls the Goldilocks prime in his design of Ed448.
Related posts
[1] If p = φ² – φ – 1 for some integer φ, then φ² – φ – 1 = 0 (mod p). But the congruence can have a solution when p is not a golden ratio prime. The following code shows that the smallest example is p = 31 and φ = 13.
from sympy import primerange from sympy.ntheory.primetest import is_square for p in primerange(2, 100): m = 4*p + 5 if not is_square(m): for x in range(p): if (x**2 - x - 1) % p == 0: print(p, x) exit()
3 thoughts on “Golden ratio primes”
SymPy has sympy.ntheory.primetest.is_square that performs those faster algorithms.
John, in your opening paragraph you seem to be tacitly saying that every prime that *divides* a number of the form n^2-n-1 can actually be *written* in the form k^2-k-1 (since the former condition is equivalent to the mod-p solvability of the equation). Is there an easy way to see that this fact is true? Or are you not claiming this?
Cf | https://www.johndcook.com/blog/2019/05/12/golden-ratio-primes/ | CC-MAIN-2020-05 | en | refinedweb |
Lesson 8 - Constant methods in C++
In the previous lesson, Arena with warriors in C++, we finished our object-oriented arena. In today's tutorial, we're going to find out what constant methods are and when to use them.
Constant methods
As the name suggests, constant method is a method that does not change
instance data. This applies for all getters - they only get data, they don't
change anything. Therefore, all getters should be marked as constant. The
Warrior.alive() method is also a kind of getter because it only
determines whether the warrior has enough health. All methods that don't change
data should be marked as constant. We do this simply by adding the
const keyword after the method name (to both the
.h
and
.cpp files). For example, it'd look like this for our
Warrior class:
Warrior.h
#ifndef __WARRIOR_H_ #define __WARRIOR_H_ #include <string> #include "RollingDie.h" using namespace std; class Warrior { private: float health; float max_health; float damage; float defense; RollingDie ¨ public: Warrior(float health, float damage, float defense, RollingDie &die); bool alive() const; float attack(Warrior &second) const; float getHealth() const; float getMaxHealth() const; float getDamage() const; float getDefense() const; }; #endif
Warrior.cpp
#include "Warrior.h" Warrior::Warrior(float health, float damage, float defense, RollingDie &die) : die(die), health(health), max_health(health), damage(damage), defense(defense) {} bool Warrior::alive() const { return this->health > 0; } float Warrior::attack(Warrior & second) const { float defense_second = second.defense + second.die.roll(); float damage_first = this->damage + this->die.roll(); float injury = damage_first - defense_second; if (injury < 0) injury = 0; second.health -= injury; return injury; } float Warrior::getHealth() const { return this->health; } float Warrior::getMaxHealth() const { return this->max_health; } float Warrior::getDamage() const { return this->damage; } float Warrior::getDefense() const { return this->defense; }
Note that even the
attack() method is constant - it does not
change instance data, it just changes parameter data.
Rules
Why are we doing this? The
const keyword will make sure that the
method is properly implemented. If we defined the
setSidesCount()
method for the
RollingDie class and set it as constant, the
compiler would report us the following message (for Visual Studio):
error C2228: left of '.sides_count' must have class/struct/union note: type is 'const RollingDie *const ' note: did you intend to use '->' instead?
The compiler will ensure that the function cannot change anything, and inform other programmers that the data is safe (it can't be changed).
What other rules apply? We can only call constant methods from a constant
method. This means that when we set a getter as constant, we can't call a setter
from it (otherwise the keyword
const wouldn't make much sense since
the method would modify the data).
There's also a third and most important rule: only constant methods can be called on constant objects. For example, for our warrior. Let's assume that the following code should work:
const Warrior warrior(100, 8, 5, die); float damage = warrior.getDamage(); float defense = warrior.getDefense(); float aggressivity_level = damage - defense;
Why would we assume that? Although the warrior is constant, we want to get the damage and defense only to read them - this shouldn't be a problem because the methods don't change the data and the constant isn't broken. But it's us who knows that, but the compiler doesn't know it yet. In order for this code to work, we must set the getters as constant - the compiler will then be certain that the method won't change anything and can be called on a constant object.
Pointers
For pointers and references, the situation becomes a little more complicated.
By adding the
const keyword to the method name, we can imagine that
it marks all the fields as constant. For demonstration, let's consider the
following class:
class User { int age; char* name; void printName() const; };
Inside the
printName() method, the
const will make
the
this pointer of the
User const * const type (as
opposed to
User * const). Just to make sure, we always read
pointers backwards, so
User const * const is a "constant pointer to
a constant user", while
User * const is a "constant pointer to a
user". We also have two syntax options, so the following two samples are
equivalent:
User const * and
const User *.
So we can imagine a constant method as all the fields are constant:
class User { const int age; char * const name; };
Note the type of the
name field. It's a constant pointer (we
can't change the address where it points to), but it's not a pointer to a
constant value - we are still able to change the name. Constant methods do not
guarantee that instance data will not change - it only ensures that fields do
not change.
Problems occur when working with references as well. Let's suppose we want to
return the user's age by reference. It's not usual, but for some reason we want
it. We can't use a reference to
int because the field type is
const int and the types must match. This means that we must use a
constant reference:
class User { int age; char* name; void printName() const; const int& getAge() const; };
Now this code part would work, and when we think about it, it literally didn't work until now - it respects constant values where it makes sense.
That would be all for today's shorter lesson. In the source code, constants were added to the getters and to a few other methods (for which it made sense). Next time, we'll continue with the code, so I recommend downloading the source code below the article. You will be sure that we'll work with the same source code. Next time, in the Static Class Members in C++ lesson, we have static members waiting for us.
Download
Downloaded 0x (1.08 MB)
Application includes source codes in language C++
No one has commented yet - be the first! | https://www.ict.social/cplusplus/course/oop/constant-methods-in-cplusplus | CC-MAIN-2020-05 | en | refinedweb |
Hello,
I am having some troubles with coding from one of Joyce Farrell's books here is a link showing the exact thing to which I am trying to figure out. Exact question
Here is the code I have written thus far.
#include <iostream> #include <iomanip> using namespace std; class BankAccount { private: int accountNum; double accountBal; static const double annualIntRate = 0.03; public: void enterAccountData(int, double); void computeInterest(); void displayAccount(); }; //implementation section: const double BankAccount::annualIntRate = 0.03; void BankAccount::enterAccountData(int number, double balance) { cout << setprecision(2) << fixed; accountNum = number; accountBal = balance; cout << "Enter the account number " << endl; cin >> number; while(number < 0 || number < 999) { cout << "Account numbers cannot be negative or less than 1000 " << "Enter a new account number: " << endl; cin >> number; } cout << "Enter the account balance " << endl; cin >> balance; while(balance < 0) { cout << "Account balances cannot be negative. " << "Enter a new account balance: " << endl; cin >> balance; } return; } void BankAccount::computeInterest() { const int MONTHS_IN_YEAR = 12; int months; double rate = 0; int counter = 0; cout << "How many months will the account be held for? "; cin >> months; counter = 0; do { balance = balance * annualIntRate + balance; counter++; }while(months < counter); cout << "Balance is:$" << balance << endl; } int main() { const int QUIT = 0; const int MAX_ACCOUNTS = 10; int counter; int input; int number = 0; double balance = 0; BankAccount accounts[MAX_ACCOUNTS]; //BankAccount display; counter = 0; do { accounts[counter].enterAccountData(number, balance); cout << " Enter " << QUIT << " to stop, or press 1 to proceed."; cin >> input; counter++; }while(input != QUIT && counter != 10); accounts[counter-1].computeInterest(); system("pause"); return 0; }
Currently this has 5 Errors, I am not sure how to work with the static constant that is asked from "computeInterest()" Classes are new to me and I had been writing structures up until this chapter, so it threw me for a loop. This also causes me to have the error of not knowing how to bring the balance from my one function and compute it within another (I also need to display the account number within the function.)
Thanks for any help in advance. | https://www.daniweb.com/programming/software-development/threads/352925/classes | CC-MAIN-2018-30 | en | refinedweb |
Lesson Interrupts
- Lookup Tables
- Binary Semaphores
- Nested Vector Interrupt Controller (NVIC)
- Lab Assignment: Interrupt + Lookup Tables + Binary Semaphores
Lookup Tables
Objective
To discuss lookup tables and how to use them to sacrifice storage space to increase computation time.
What Are Lookup Tables
Lookup tables are static arrays that sacrifices memory storage in place of a simple array index lookup of precalculated values. In some examples, a lookup table is not meant to speed a process, but simply an elegant solution to a problem.
Lets look at some examples to see why these are useful.
Why Use Lookup Tables
Simple Example: Convert Potentiometer Voltage to Angle
Lets make some assumptions about the system first:
- Using an 8-bit ADC
- Potentiometer is linear
- Potentiometer sweep angle is 180 degrees
- Potentiometer all the way left is 0 deg and 0V
- Potentiometer all the way right (180 deg) is ADC Reference Voltage
- Using a processor that does NOT have a FPU (Floating Point arithmetic Unit) like the Arm Cortex M3 we use in the LPC1756.
double potADCToDegrees(uint8_t adc) { return ((double)(adc))*(270/256); }
Code Block 1. Without Lookup
const double potentiometer_angles[256] = { // [ADC] = Angle [0] = 0.0, [1] = 1.0546875, [2] = 2.109375, [3] = 3.1640625, [4] = 4.21875, [5] = 5.2734375, [6] = 6.328125, [7] = 7.3828125, [8] = 8.4375, [9] = 9.4921875, [10] = 10.546875, [11] = 11.6015625, [12] = 12.65625, [13] = 13.7109375, [14] = 14.765625, [15] = 15.8203125, [16] = 16.875, [17] = 17.9296875, [18] = 18.984375, [19] = 20.0390625, [20] = 21.09375, [21] = 22.1484375, [22] = 23.203125, [23] = 24.2578125, [24] = 25.3125, [25] = 26.3671875, [26] = 27.421875, [27] = 28.4765625, [28] = 29.53125, [29] = 30.5859375, [30] = 31.640625, [31] = 32.6953125, [32] = 33.75, [33] = 34.8046875, [34] = 35.859375, [35] = 36.9140625, [36] = 37.96875, [37] = 39.0234375, [38] = 40.078125, [39] = 41.1328125, [40] = 42.1875, [41] = 43.2421875, [42] = 44.296875, [43] = 45.3515625, [44] = 46.40625, [45] = 47.4609375, [46] = 48.515625, [47] = 49.5703125, [48] = 50.625, [49] = 51.6796875, [50] = 52.734375, [51] = 53.7890625, [52] = 54.84375, [53] = 55.8984375, [54] = 56.953125, [55] = 58.0078125, [56] = 59.0625, [57] = 60.1171875, [58] = 61.171875, [59] = 62.2265625, [60] = 63.28125, [61] = 64.3359375, [62] = 65.390625, [63] = 66.4453125, [64] = 67.5, [65] = 68.5546875, [66] = 69.609375, [67] = 70.6640625, [68] = 71.71875, [69] = 72.7734375, [70] = 73.828125, [71] = 74.8828125, [72] = 75.9375, [73] = 76.9921875, [74] = 78.046875, [75] = 79.1015625, [76] = 80.15625, [77] = 81.2109375, [78] = 82.265625, [79] = 83.3203125, [80] = 84.375, [81] = 85.4296875, [82] = 86.484375, [83] = 87.5390625, [84] = 88.59375, [85] = 89.6484375, [86] = 90.703125, [87] = 91.7578125, [88] = 92.8125, [89] = 93.8671875, [90] = 94.921875, [91] = 95.9765625, [92] = 97.03125, [93] = 98.0859375, [94] = 99.140625, [95] = 100.1953125, [96] = 101.25, [97] = 102.3046875, [98] = 103.359375, [99] = 104.4140625, [100] = 105.46875, [101] = 106.5234375, [102] = 107.578125, [103] = 108.6328125, [104] = 109.6875, [105] = 110.7421875, [106] = 111.796875, [107] = 112.8515625, [108] = 113.90625, [109] = 114.9609375, [110] = 116.015625, [111] = 117.0703125, [112] = 118.125, [113] = 119.1796875, [114] = 120.234375, [115] = 121.2890625, [116] = 122.34375, [117] = 123.3984375, [118] = 124.453125, [119] = 125.5078125, [120] = 126.5625, [121] = 127.6171875, [122] = 128.671875, [123] = 129.7265625, [124] = 130.78125, [125] = 131.8359375, [126] = 132.890625, [127] = 133.9453125, [128] = 135, [129] = 136.0546875, [130] = 137.109375, [131] = 138.1640625, [132] = 139.21875, [133] = 140.2734375, [134] = 141.328125, [135] = 142.3828125, [136] = 143.4375, [137] = 144.4921875, [138] = 145.546875, [139] = 146.6015625, [140] = 147.65625, [141] = 148.7109375, [142] = 149.765625, [143] = 150.8203125, [144] = 151.875, [145] = 152.9296875, [146] = 153.984375, [147] = 155.0390625, [148] = 156.09375, [149] = 157.1484375, [150] = 158.203125, [151] = 159.2578125, [152] = 160.3125, [153] = 161.3671875, [154] = 162.421875, [155] = 163.4765625, [156] = 164.53125, [157] = 165.5859375, [158] = 166.640625, [159] = 167.6953125, [160] = 168.75, [161] = 169.8046875, [162] = 170.859375, [163] = 171.9140625, [164] = 172.96875, [165] = 174.0234375, [166] = 175.078125, [167] = 176.1328125, [168] = 177.1875, [169] = 178.2421875, [170] = 179.296875, [171] = 180.3515625, [172] = 181.40625, [173] = 182.4609375, [174] = 183.515625, [175] = 184.5703125, [176] = 185.625, [177] = 186.6796875, [178] = 187.734375, [179] = 188.7890625, [180] = 189.84375, [181] = 190.8984375, [182] = 191.953125, [183] = 193.0078125, [184] = 194.0625, [185] = 195.1171875, [186] = 196.171875, [187] = 197.2265625, [188] = 198.28125, [189] = 199.3359375, [190] = 200.390625, [191] = 201.4453125, [192] = 202.5, [193] = 203.5546875, [194] = 204.609375, [195] = 205.6640625, [196] = 206.71875, [197] = 207.7734375, [198] = 208.828125, [199] = 209.8828125, [200] = 210.9375, [201] = 211.9921875, [202] = 213.046875, [203] = 214.1015625, [204] = 215.15625, [205] = 216.2109375, [206] = 217.265625, [207] = 218.3203125, [208] = 219.375, [209] = 220.4296875, [210] = 221.484375, [211] = 222.5390625, [212] = 223.59375, [213] = 224.6484375, [214] = 225.703125, [215] = 226.7578125, [216] = 227.8125, [217] = 228.8671875, [218] = 229.921875, [219] = 230.9765625, [220] = 232.03125, [221] = 233.0859375, [222] = 234.140625, [223] = 235.1953125, [224] = 236.25, [225] = 237.3046875, [226] = 238.359375, [227] = 239.4140625, [228] = 240.46875, [229] = 241.5234375, [230] = 242.578125, [231] = 243.6328125, [232] = 244.6875, [233] = 245.7421875, [234] = 246.796875, [235] = 247.8515625, [236] = 248.90625, [237] = 249.9609375, [238] = 251.015625, [239] = 252.0703125, [240] = 253.125, [241] = 254.1796875, [242] = 255.234375, [243] = 256.2890625, [244] = 257.34375, [245] = 258.3984375, [246] = 259.453125, [247] = 260.5078125, [248] = 261.5625, [249] = 262.6171875, [250] = 263.671875, [251] = 264.7265625, [252] = 265.78125, [253] = 266.8359375, [254] = 267.890625, [255] = 268.9453125, [256] = 270 }; inline double potADCToDegrees(uint8_t adc) { return potentiometer_angles[adc]; }
Code Block 2. With Lookup
With the two examples, it may seem trivial since the WITHOUT case is only "really" doing one calculation, mulitplying the uint8_t with (270/256) since the compiler will most likely optimize this value to its result. But if you take a look at the assembly, the results may shock you.
Look up Table Disassembly
00016e08 <main>: main(): /var/www/html/SJSU-Dev/firmware/Experiements/L5_Application/main.cpp:322 [254] = 268.9411765, [255] = 270 }; int main(void) { 16e08: b082 sub sp, #8 /var/www/html/SJSU-Dev/firmware/Experiements/L5_Application/main.cpp:323 volatile double a = potentiometer_angles[15]; 16e0a: a303 add r3, pc, #12 ; (adr r3, 16e18 <main+0x10>) 16e0c: e9d3 2300 ldrd r2, r3, [r3] 16e10: e9cd 2300 strd r2, r3, [sp] 16e14: e7fe b.n 16e14 <main+0xc> 16e16: bf00 nop 16e18: c3b9a8ae .word 0xc3b9a8ae 16e1c: 402fc3c3 .word 0x402fc3c3
Code Block 3. Dissassembly of Look up Table
Looks about right. You can see at 16e0a the software is retrieving data from the lookup table, and then it is loading it into the double which is on the stack.
Double Floating Point Disassembly
00017c64 <__adddf3>: __aeabi_dadd(): 17c64: b530 push {r4, r5, lr} 17c66: ea4f 0441 mov.w r4, r1, lsl #1 17c6a: ea4f 0543 mov.w r5, r3, lsl #1 17c6e: ea94 0f05 teq r4, r5 17c72: bf08 it eq 17c74: ea90 0f02 teqeq r0, r2 17c78: bf1f itttt ne 17c7a: ea54 0c00 orrsne.w ip, r4, r0 17c7e: ea55 0c02 orrsne.w ip, r5, r2 17c82: ea7f 5c64 mvnsne.w ip, r4, asr #21 17c86: ea7f 5c65 mvnsne.w ip, r5, asr #21 17c8a: f000 80e2 beq.w 17e52 <__adddf3+0x1ee> 17c8e: ea4f 5454 mov.w r4, r4, lsr #21 17c92: ebd4 5555 rsbs r5, r4, r5, lsr #21 17c96: bfb8 it lt 17c98: 426d neglt r5, r5 17c9a: dd0c ble.n 17cb6 <__adddf3+0x52> 17c9c: 442c add r4, r5 17c9e: ea80 0202 eor.w r2, r0, r2 17ca2: ea81 0303 eor.w r3, r1, r3 17ca6: ea82 0000 eor.w r0, r2, r0 17caa: ea83 0101 eor.w r1, r3, r1 17cae: ea80 0202 eor.w r2, r0, r2 17cb2: ea81 0303 eor.w r3, r1, r3 17cb6: 2d36 cmp r5, #54 ; 0x36 17cb8: bf88 it hi 17cba: bd30 pophi {r4, r5, pc} 17cbc: f011 4f00 tst.w r1, #2147483648 ; 0x80000000 17cc0: ea4f 3101 mov.w r1, r1, lsl #12 17cc4: f44f 1c80 mov.w ip, #1048576 ; 0x100000 17cc8: ea4c 3111 orr.w r1, ip, r1, lsr #12 17ccc: d002 beq.n 17cd4 <__adddf3+0x70> 17cce: 4240 negs r0, r0 17cd0: eb61 0141 sbc.w r1, r1, r1, lsl #1 17cd4: f013 4f00 tst.w r3, #2147483648 ; 0x80000000 17cd8: ea4f 3303 mov.w r3, r3, lsl #12 17cdc: ea4c 3313 orr.w r3, ip, r3, lsr #12 17ce0: d002 beq.n 17ce8 <__adddf3+0x84> 17ce2: 4252 negs r2, r2 17ce4: eb63 0343 sbc.w r3, r3, r3, lsl #1 17ce8: ea94 0f05 teq r4, r5 17cec: f000 80a7 beq.w 17e3e <__adddf3+0x1da> 17cf0: f1a4 0401 sub.w r4, r4, #1 17cf4: f1d5 0e20 rsbs lr, r5, #32 17cf8: db0d blt.n 17d16 <__adddf3+0xb2> 17cfa: fa02 fc0e lsl.w ip, r2, lr 17cfe: fa22 f205 lsr.w r2, r2, r5 17d02: 1880 adds r0, r0, r2 17d04: f141 0100 adc.w r1, r1, #0 17d08: fa03 f20e lsl.w r2, r3, lr 17d0c: 1880 adds r0, r0, r2 17d0e: fa43 f305 asr.w r3, r3, r5 17d12: 4159 adcs r1, r3 17d14: e00e b.n 17d34 <__adddf3+0xd0> 17d16: f1a5 0520 sub.w r5, r5, #32 17d1a: f10e 0e20 add.w lr, lr, #32 17d1e: 2a01 cmp r2, #1 17d20: fa03 fc0e lsl.w ip, r3, lr 17d24: bf28 it cs 17d26: f04c 0c02 orrcs.w ip, ip, #2 17d2a: fa43 f305 asr.w r3, r3, r5 17d2e: 18c0 adds r0, r0, r3 17d30: eb51 71e3 adcs.w r1, r1, r3, asr #31 17d34: f001 4500 and.w r5, r1, #2147483648 ; 0x80000000 17d38: d507 bpl.n 17d4a <__adddf3+0xe6> 17d3a: f04f 0e00 mov.w lr, #0 17d3e: f1dc 0c00 rsbs ip, ip, #0 17d42: eb7e 0000 sbcs.w r0, lr, r0 17d46: eb6e 0101 sbc.w r1, lr, r1 17d4a: f5b1 1f80 cmp.w r1, #1048576 ; 0x100000 17d4e: d31b bcc.n 17d88 <__adddf3+0x124> 17d50: f5b1 1f00 cmp.w r1, #2097152 ; 0x200000 17d54: d30c bcc.n 17d70 <__adddf3+0x10c> 17d56: 0849 lsrs r1, r1, #1 17d58: ea5f 0030 movs.w r0, r0, rrx 17d5c: ea4f 0c3c mov.w ip, ip, rrx 17d60: f104 0401 add.w r4, r4, #1 17d64: ea4f 5244 mov.w r2, r4, lsl #21 17d68: f512 0f80 cmn.w r2, #4194304 ; 0x400000 17d6c: f080 809a bcs.w 17ea4 <__adddf3+0x240> 17d70: f1bc 4f00 cmp.w ip, #2147483648 ; 0x80000000 17d74: bf08 it eq 17d76: ea5f 0c50 movseq.w ip, r0, lsr #1 17d7a: f150 0000 adcs.w r0, r0, #0 17d7e: eb41 5104 adc.w r1, r1, r4, lsl #20 17d82: ea41 0105 orr.w r1, r1, r5 17d86: bd30 pop {r4, r5, pc} 17d88: ea5f 0c4c movs.w ip, ip, lsl #1 17d8c: 4140 adcs r0, r0 17d8e: eb41 0101 adc.w r1, r1, r1 17d92: f411 1f80 tst.w r1, #1048576 ; 0x100000 17d96: f1a4 0401 sub.w r4, r4, #1 17d9a: d1e9 bne.n 17d70 <__adddf3+0x10c> 17d9c: f091 0f00 teq r1, #0 17da0: bf04 itt eq 17da2: 4601 moveq r1, r0 17da4: 2000 moveq r0, #0 17da6: fab1 f381 clz r3, r1 17daa: bf08 it eq 17dac: 3320 addeq r3, #32 17dae: f1a3 030b sub.w r3, r3, #11 17db2: f1b3 0220 subs.w r2, r3, #32 17db6: da0c bge.n 17dd2 <__adddf3+0x16e> 17db8: 320c adds r2, #12 17dba: dd08 ble.n 17dce <__adddf3+0x16a> 17dbc: f102 0c14 add.w ip, r2, #20 17dc0: f1c2 020c rsb r2, r2, #12 17dc4: fa01 f00c lsl.w r0, r1, ip 17dc8: fa21 f102 lsr.w r1, r1, r2 17dcc: e00c b.n 17de8 <__adddf3+0x184> 17dce: f102 0214 add.w r2, r2, #20 17dd2: bfd8 it le 17dd4: f1c2 0c20 rsble ip, r2, #32 17dd8: fa01 f102 lsl.w r1, r1, r2 17ddc: fa20 fc0c lsr.w ip, r0, ip 17de0: bfdc itt le 17de2: ea41 010c orrle.w r1, r1, ip 17de6: 4090 lslle r0, r2 17de8: 1ae4 subs r4, r4, r3 17dea: bfa2 ittt ge 17dec: eb01 5104 addge.w r1, r1, r4, lsl #20 17df0: 4329 orrge r1, r5 17df2: bd30 popge {r4, r5, pc} 17df4: ea6f 0404 mvn.w r4, r4 17df8: 3c1f subs r4, #31 17dfa: da1c bge.n 17e36 <__adddf3+0x1d2> 17dfc: 340c adds r4, #12 17dfe: dc0e bgt.n 17e1e <__adddf3+0x1ba> 17e00: f104 0414 add.w r4, r4, #20 17e04: f1c4 0220 rsb r2, r4, #32 17e08: fa20 f004 lsr.w r0, r0, r4 17e0c: fa01 f302 lsl.w r3, r1, r2 17e10: ea40 0003 orr.w r0, r0, r3 17e14: fa21 f304 lsr.w r3, r1, r4 17e18: ea45 0103 orr.w r1, r5, r3 17e1c: bd30 pop {r4, r5, pc} 17e1e: f1c4 040c rsb r4, r4, #12 17e22: f1c4 0220 rsb r2, r4, #32 17e26: fa20 f002 lsr.w r0, r0, r2 17e2a: fa01 f304 lsl.w r3, r1, r4 17e2e: ea40 0003 orr.w r0, r0, r3 17e32: 4629 mov r1, r5 17e34: bd30 pop {r4, r5, pc} 17e36: fa21 f004 lsr.w r0, r1, r4 17e3a: 4629 mov r1, r5 17e3c: bd30 pop {r4, r5, pc} 17e3e: f094 0f00 teq r4, #0 17e42: f483 1380 eor.w r3, r3, #1048576 ; 0x100000 17e46: bf06 itte eq 17e48: f481 1180 eoreq.w r1, r1, #1048576 ; 0x100000 17e4c: 3401 addeq r4, #1 17e4e: 3d01 subne r5, #1 17e50: e74e b.n 17cf0 <__adddf3+0x8c> 17e52: ea7f 5c64 mvns.w ip, r4, asr #21 17e56: bf18 it ne 17e58: ea7f 5c65 mvnsne.w ip, r5, asr #21 17e5c: d029 beq.n 17eb2 <__adddf3+0x24e> 17e5e: ea94 0f05 teq r4, r5 17e62: bf08 it eq 17e64: ea90 0f02 teqeq r0, r2 17e68: d005 beq.n 17e76 <__adddf3+0x212> 17e6a: ea54 0c00 orrs.w ip, r4, r0 17e6e: bf04 itt eq 17e70: 4619 moveq r1, r3 17e72: 4610 moveq r0, r2 17e74: bd30 pop {r4, r5, pc} 17e76: ea91 0f03 teq r1, r3 17e7a: bf1e ittt ne 17e7c: 2100 movne r1, #0 17e7e: 2000 movne r0, #0 17e80: bd30 popne {r4, r5, pc} 17e82: ea5f 5c54 movs.w ip, r4, lsr #21 17e86: d105 bne.n 17e94 <__adddf3+0x230> 17e88: 0040 lsls r0, r0, #1 17e8a: 4149 adcs r1, r1 17e8c: bf28 it cs 17e8e: f041 4100 orrcs.w r1, r1, #2147483648 ; 0x80000000 17e92: bd30 pop {r4, r5, pc} 17e94: f514 0480 adds.w r4, r4, #4194304 ; 0x400000 17e98: bf3c itt cc 17e9a: f501 1180 addcc.w r1, r1, #1048576 ; 0x100000 17e9e: bd30 popcc {r4, r5, pc} 17ea0: f001 4500 and.w r5, r1, #2147483648 ; 0x80000000 17ea4: f045 41fe orr.w r1, r5, #2130706432 ; 0x7f000000 17ea8: f441 0170 orr.w r1, r1, #15728640 ; 0xf00000 17eac: f04f 0000 mov.w r0, #0 17eb0: bd30 pop {r4, r5, pc} 17eb2: ea7f 5c64 mvns.w ip, r4, asr #21 17eb6: bf1a itte ne 17eb8: 4619 movne r1, r3 17eba: 4610 movne r0, r2 17ebc: ea7f 5c65 mvnseq.w ip, r5, asr #21 17ec0: bf1c itt ne 17ec2: 460b movne r3, r1 17ec4: 4602 movne r2, r0 17ec6: ea50 3401 orrs.w r4, r0, r1, lsl #12 17eca: bf06 itte eq 17ecc: ea52 3503 orrseq.w r5, r2, r3, lsl #12 17ed0: ea91 0f03 teqeq r1, r3 17ed4: f441 2100 orrne.w r1, r1, #524288 ; 0x80000 17ed8: bd30 pop {r4, r5, pc} 17eda: bf00 nop
Code Block 4. Arm Software Floating Point Addition Implementation
This isn't even the full code. This is a function that our calculation function has to run each time it wants to add two doubles together. Also, note that it is not just a straight shot of 202 instructions, because you can see that there are loops in the code where ever you see an instruction's mnemonic that starts with the letter b (stands for branch).
Other Use Cases
- Correlate degrees to radians (assuming degrees are whole numbers)
- Table of cosine or sine given radians or degrees
- In the radians case, you will need to create your own trivial hashing function to convert radians to an index
- Finding a number of bits SET in a 32-bit number
- Without a lookup table time complexity is O(n) where (n = 32), the number of bits you want to look through
- With a lookup table, the time complexity is O(1), constant time, and only needs the followin operations
- 3 bitwise left shifts operations
- 4 bitwise ANDS operations
- 4 load from memory addresses
- 4 binary ADD operations
- Total of 15 operations total
/* Found this on wikipedia! */ /* Pseudocode of the lookup table 'uint32_t bits_set[256]' */ /* 0b00, 0b01, 0b10, 0b11, 0b100, 0b101, ... */ int bits_set[256] = { 0, 1, 1, 2, 1, 2, // 200+ more entries /* (this code assumes that 'int' is an unsigned 32-bits wide integer) */ int count_ones(unsigned int x) { return bits_set[ x & 255] + bits_set[(x >> 8) & 255] + bits_set[(x >> 16) & 255] + bits_set[(x >> 24) & 255]; }
Code Block 5. Bits set in a 32-bit number (Found this on wikipedia (look up tables))
There are far more use cases then this, but these are a few.
Lookup Table Decision Tree
Lookup tables can be used as elegant ways to structure information. In this case, they may not provide a speed up but they will associate indexes with something greater, making your code more readable and easier to maintain. In this example, we will be looking at a matrix of function pointers.
Example: Replace Decision Tree
See the function below:
void makeADecisionRobot(bool power_system_nominal, bool no_obstacles_ahead) { if(power_system_nominal && no_obstacles_ahead) { moveForward(); } else if(power_system_nominal && !no_obstacles_ahead) { moveOutOfTheWay(); } else if(!power_system_nominal && no_obstacles_ahead) { slowDown(); } else { emergencyStop(); } }
Code Block 6. Typical Decision Tree
void (* decision_matrix)(void)[2][2] = { [1][1] = moveForward [1][0] = moveOutOfTheWay, [0][1] = slowDown, [0][0] = emergencyStop, }; void makeADecisionRobot(bool power_system_nominal, bool no_obstacles_ahead) { decision_matrix[power_system_nominal][no_obstacles_ahead](); }
Code Block 7. Lookup Table Decision Tree
The interesting thing about the decision tree is that it is also more optimal in that, it takes a few instructions to do the look up from memory, then the address of the procedure [function] is looked up an executed, where the former required multiple read instructions and comparison instructions.
This pattern of lookup table will be most useful to us for the interrupts lab assignment.
Binary.
Nestedcontroller "GCC interrupt attribute" to study this topic further. On SJ-One board, which uses LPC1717.
/** * CPU interrupt vector table that is loaded at the beginning of the CPU start * location by using the linker script that will place it at the isr_vector location. * CPU loads the stack pointer and begins execution from Reset vector. */ isr_forwarder_routine, // 37, 0x94 - EINT3 1. Software Interrupt Vector Table
NOTE: that a vector table is really just a lookup table that hardware utilizes.
Two Methods to setup an ISR on the SJOne
DO NOT DO THIS, unless you really know what you are doing. The ISR forwarder works with FreeRTOS to distinguish CPU utilization between ISRs and tasks.
I highly discourage modifying the startup.cpp and modifying the vector tables directly. Its not dynamic is less manageable in that, if you switch projects and the ISR doesn't exist, the compiler will through an error.
IVT modify
/* You will need to include the header file that holds the ISR for this to work */ #include "my_isr.h" runMyISR, // 37, 0x94 - EINT3 <---- NOTICE how I changed the name here 3. Weak Function Override Template
Method 2. ISR Register Function
The EINT3_IRQn symbol is defined in an enumeration in LPC17xx.h. All you need to do is specify the IRQ number and the function you want to act as an ISR. This will then swap out the previous ISR with your function.
This is the best option! Please use this option almost always!
/** * Just your run-of-the-mill function */ void myEINT3ISR(void) { doSomething(); clearInterruptFlag(); } int main() { /** * Find the IRQ number for the interrupt you want to define. * In this case, we want to override IRQ 0x98 EINT3 * Then specify a function pointer that will act as your ISR */ isr_register(EINT3_IRQn, myEINT3ISR); NVIC_EnableIRQ(EINT3_IRQn); }ButtonPressISR(void) { long yield = 0; xSemaphoreGiveFromISR(button_press_semaphore, &yield); portYIELD_FROM_ISR(yield); } void vButtonPressTask(void *pvParameter) { while(1) { if (xSemaphoreTake(button_press_semaphore, portMAX_DELAY)) { /* Process the interrupt */ } } } void main(void) { button_press_semaphore = xSemaphoreCreateBinary(); /* TODO: Hook up myButtonPressISR() using eint.h */ /* TODO: Create vButtonPressTask() and start FreeRTOS scheduler */ }
Code Block 6. Wait on Semaphore ISR design pattern example
Resources
Lab. | http://books.socialledge.com/books/embedded-drivers-real-time-operating-systems/chapter/lesson-interrupts/export/html | CC-MAIN-2018-30 | en | refinedweb |
In this part of my Java Video Tutorial, I will cover GUI Event Handling. If you missed my Java Swing video tutorial, watch that first.
Here I show you how to implement the ActionListener, KeyListener, MouseListener and WindowListener. I also show you some easy ways to use interfaces so that you don’t have to memorize all of the required methods for each interface.
All of the code follows the video. Definitely look at it so that you will find it easier to learn.
If you like videos like this share it
Code from the Video
import java.awt.Dimension; import java.awt.Toolkit; import javax.swing.*; import java.awt.event.*; // Extends JFrame so it can create frames public class LessonTwentyOne extends JFrame{ JButton button1; JTextField textField1; JTextArea textArea1; int buttonClicked; public static void main(String[] args){ new LessonTwentyOne(); } public LessonTwentyOne(){ // Define the size of the frame this.setSize(400, 400); //(); // Create a button with Click Here on it button1 = new JButton("Click Here"); // Create an instance of ListenForEvents to handle events ListenForButton lForButton = new ListenForButton(); // Tell Java that you want to be alerted when an event // occurs on the button button1.addActionListener(lForButton); thePanel.add(button1); // How to add a text field ---------------------- textField1 = new JTextField("Type Here", 15); ListenForKeys lForKeys = new ListenForKeys(); textField1.addKeyListener(lForKeys); thePanel.add(textField1); // How to add a text area ---------------------- textArea1 = new JTextArea(15, 20); // Set the default text for the text area textArea1.setText("Tracking Events\n"); // If text doesn't fit on a line, jump to the next textArea1.setLineWrap(true); // Makes sure that words stay intact if a line wrap occurs textArea1.setWrapStyleWord(true); //); this.add(thePanel); ListenForWindow lForWindow = new ListenForWindow(); this.addWindowListener(lForWindow); this.setVisible(true); // Track the mouse if it is inside of the panel ListenForMouse lForMouse = new ListenForMouse(); thePanel.addMouseListener(lForMouse); } // Implements ActionListener so it can react to events on components private class ListenForButton implements ActionListener{ // This method is called when an event occurs public void actionPerformed(ActionEvent e){ // Check if the source of the event was the button if(e.getSource() == button1){ buttonClicked++; // Change the text for the label textArea1.append("Button clicked " + buttonClicked + " times\n" ); // e.getSource().toString() returns information on the button // and the event that occurred } } } // By using KeyListener you can track keys on the keyboard private class ListenForKeys implements KeyListener{ // Handle the key typed event from the text field. public void keyTyped(KeyEvent e) { textArea1.append("Key Hit: " + e.getKeyChar() + "\n"); } // Handle the key-pressed event from the text field. public void keyPressed(KeyEvent e) { } // Handle the key-released event from the text field. public void keyReleased(KeyEvent e) { } } private class ListenForMouse implements MouseListener{ // Called when a mouse button is clicked public void mouseClicked(MouseEvent e) { textArea1.append("Mouse Panel Pos: " + e.getX() + " " + e.getY() + "\n"); textArea1.append("Mouse Screen Pos: " + e.getXOnScreen() + " " + e.getYOnScreen() + "\n"); textArea1.append("Mouse Button: " + e.getButton() + "\n"); textArea1.append("Mouse Clicks: " + e.getClickCount() + "\n"); } // Called when the mouse enters the component assigned // the MouseListener public void mouseEntered(MouseEvent arg0) { // TODO Auto-generated method stub } // Called when the mouse leaves the component assigned // the MouseListener public void mouseExited(MouseEvent arg0) { // TODO Auto-generated method stub } // Mouse button pressed public void mousePressed(MouseEvent arg0) { // TODO Auto-generated method stub } // Mouse button released public void mouseReleased(MouseEvent arg0) { // TODO Auto-generated method stub } } private class ListenForWindow implements WindowListener{ // Called when window is the active window public void windowActivated(WindowEvent e) { textArea1.append("Window Activated\n"); } // Called when window is closed using dispose // this.dispose(); can be used to close a window public void windowClosed(WindowEvent arg0) { // TODO Auto-generated method stub } // Called when the window is closed from the menu public void windowClosing(WindowEvent arg0) { // TODO Auto-generated method stub } // Called when a window is no longer the active window public void windowDeactivated(WindowEvent e) { textArea1.append("Window Activated\n"); } // Called when the window goes from minimized to a normal state public void windowDeiconified(WindowEvent arg0) { textArea1.append("Window in Normal State\n"); } // Called when the window goes from normal to a minimized state public void windowIconified(WindowEvent arg0) { textArea1.append("Window Minimized\n"); } // Called when the window is first created public void windowOpened(WindowEvent arg0) { textArea1.append("Window Created\n"); } } }
wowww, just waiting for your new video, will watch it today…
thank you….
You’re very welcome. It’s a tutorial packed with information
if possible add some security concerns for web development in java(ie. how to secure from sql injuctions, cross site scripting, how to set up https in tomcat) etc, to make a website secure, like an e-commerce site.
if possible please, do some tutorial for java securities in web devlopement(ie. how to secure site from sql injuctions, cross site scripting, how to setup https in tomcat)etc. like useful for some e-commerce sites..
Your in luck. I’ve already covered that topic using PHP. Every technique is nearly identical using Java
PHP Security
PHP Security Pt 2
PHP Security Pt 3
PHP Security Pt 4 Set Up Captcha
PHP Security Pt 5 SQL Injection
PHP Security Pt 6 Directory Traversal
Web Design and Programming Pt 21 Secure Login Script
Well my good luck works for me..;-)
but the functions you are using are for php, how do i use them in java??
Most of what I do is test data using regular expressions. It should be easy to just use those same codes since regex are identical. I’ll cover sessions, cookies, databases as soon as possible. It’s getting harder to cover the more complicated topics quickly
okay…thanks…
hi derek i have few questions regarding this tutorial
1.)when we create an object like ListenForButton lForButton then why do we have to pass it like button1.addActionListner(lForButton);
2.)why do we create private class abc implements def, can’t we do it by defining a function.plz explain. also tell me if a class is defined into another class does it gets all of the fields and methods of the parent class under which it is enclosed.
button1.addActionListener(lForButton); says that when an event is triggered on button1 that you want the class ListenForButton to be called. Then the method actionPerformed is called and it handles what to do when an event is triggered.
If a class extends another class yes the new class gets all of the methods of the super class.
Does that help?
hi derek, thanks for the video man, i just had one question.
=>what is the difference between keyPressed and Keytyped method.
keyPressed – when the key goes down
keyReleased – when the key comes up
keyTyped – when the unicode character represented by this key is sent by the keyboard to system input
hi derek, can u tell me what is the difference between keytyped and keypressed
keyPressed – when the key goes down
keyReleased – when the key comes up
keyTyped – when the unicode character represented by this key is sent by the keyboard to system input
Hey Derek, what is a FocusListener meant to do?
Sorry, I wasn’t patient enough. I understand it now :).
Sorry I couldn’t get to you quicker, but I’m glad you understand now 🙂
Hey Derek,
Awesome Videos, even though i have a couple of problems with this episode and especially with actionlisteners:
I am using Netbeans, and even if i copy and paste your code, it gives me a lot of warnings and errors. If i write my own program, which is slightly different from yours, i end up getting errors when i try to implement “private class ListenForButton implements ActionListener{}” for instance. It says it is not abstract and cant override some other method.
That is odd. I also had some weird errors when I used NetBeans in the past and that is why I stuck with Eclipse. I’m using regular old Java in these tutorials so they should work on every IDE.
Don’t worry about understanding Action Listeners at this point. I cover them a countless number of times over the course of this tutorial. You’ll understand them with a few more examples.
Hi derek nice tutorials.One question, can i skip the swing tutorials, because later i will learn javafx and i want to continue with the thrid part of the tutorials. Can i continue without the swing tutorials.
Thx
Sure feel free to bounce around in the tutorial however you’d like.
Hi Derek,
In video you put the code in KeyPressed function but in the code here it is given in KeyTyped method. Moreover, I am a bit unclear between the usage of KeyTyped and KeyPressed.
Thanks
Kuldeep
Hi Kuldeep,
keyPressed – when the key goes down
keyReleased – when the key comes up
keyTyped – when the unicode character represented by this key is sent by the keyboard to system input
I have implemented the focus listener and have found may uses for it :), although many, in my mind anyway are web related. Also Happy New Year! Love your videos and keep up the high quality content you produce!
I will definitely be covering how to connect Android apps to remote servers very soon. I’m very happy that you enjoy the videos. Many more are coming 🙂
Hi, Derek. I have to thank you for your work to help the programmers around the world. I’m from China and I have recommended my friends to watch your videos if they want to study how to program. Thank you so much.
Hi Wang, Thank you very much for taking the time to tell me that I’ve helped. I greatly appreciate that! I wish you and your friends all of the best 🙂
Hi Derek!
Still havent’s figured out what FocusListened does… Could you please give some expanation?
Thanks
A focus listener is triggered anytime a component is targeted by mouse, the keyboard, or programmatically | https://www.newthinktank.com/2012/03/java-video-tutorial-21/ | CC-MAIN-2018-30 | en | refinedweb |
Rechercher une page de manuel
gnunet-search
Langue: en
Version: 336474 (ubuntu - 24/10/10)
Section: 1 (Commandes utilisateur)
NAMEgnunet-search - a command line interface to search for content on GNUnet
SYNOPSISgnunet-search [OPTIONS] [+]KEYWORD [[+]KEYWORD]*
gnunet-search [OPTIONS] [+]URI
DESCRIPTION
Search for content on GNUnet. The keywords are case-sensitive. gnunet-search can be used both for a search in the global namespace as well as for searching a private subspace.
- -a LEVEL, --anonymity=LEVEL
- The -a option can be used to specify additional anonymity constraints. If set to 0, GNUnet will try to download the file as fast as possible without any additional slowdown for anonymous routing. Note that you may still have some amount of anonymity depending on the current network load and the power of the adversary. Use at least 1 to force GNUnet to use anonymous routing.
This option can be used to limit requests further than that. In particular, you can require GNUnet to have a certain amount of cover traffic from other peers before sending your queries. This way, you can gain very high levels of anonymity - at the expense of much more traffic and much higher latency. So set this option to values beyond 1 only if you really believe you need it.
The definition of ANONYMITY-RECEIVE is the following: If the value v is 0, anonymous routing is not required. For 1, anonymous routing is required, but there is no lower bound on how much cover traffic must be present. For values > 1 and < 1000, it means that if GNUnet routes n bytes of messages from foreign peers, it may originate n/v bytes of queries in the same time-period. The time-period is twice the average delay that GNUnet deferrs forwarded queries. If the value v is >= 1000, it means that if GNUnet routes n bytes of QUERIES from at least (v % 1000) peers, it may originate n/v/1000 bytes of queries in the same time-period.
The default is 1 and this should be fine for most users. Also notice that if you choose values above 1000, you may end up having no throughput at all, especially if many of your fellow GNUnet-peers do the same.
- -c FILENAME, --config=FILENAME
- use config file (defaults: ~/.gnunet/gnunet.conf)
- -h, --help
- print help page
- -H HOSTNAME, --host=HOSTNAME
- on which host is gnunetd running (default: localhost). You can also specify a port using the syntax HOSTNAME:PORT. The default port is 2087.
- ).
- -o PREFIX, --output=PREFIX
- Writes the encountered (unencrypted) RBlocks or SBlocks to files with name PREFIX.XXX, where XXX is a number. This is useful to keep search results around.
- -v, --version
- print the version number
NOTESAs most GNUnet command-line tools, gnunet-search supports passing arguments using environment variables. This can improve your privacy since otherwise the search terms will likely be visible to other local users. Setting "GNUNET_ARGS" will cause the respective string to be appended to the actual command-line and to be processed the same way as arguments given directly at the command line.
You can run gnunet-search with an URI instead of a keyword. The URI can have the format for a namespace search or for a keyword search. For a namespace search, the format is gnunet://ecrs/sks/NAMESPACE/IDENTIFIER. For a keyword search, use gnunet://ecrs:
gnunet-download -o "COPYING" gnunet://ecrs/chk/HASH1.HASH2.SIZE
Description: The GNU Public License
Mime-type: text/plain Public License" and the mime-type (see the options for gnunet-insert on how to supply meta-data by hand).
FILES
- ~/.gnunet/gnunet.conf
- GNUnet configuration file; specifies the default value for the timeout
REPORTING BUGSReport bugs by using mantis <> or by sending electronic mail to <gnunet-developers@gnu.org>
SEE ALSOgnunet-gtk(1), gnunet-insert(1), gnunet-download(1), gnunet-pseudonym(1), gnunet.conf(5), gnunetd(1)
MultideskOS. C'est ce système qui va traduire nos logiciels pour que le
processeur de votre ordinateur les comprenne.
-- Jayce - Je fais simple pour les neuneus --
Contenus ©2006-2018 Benjamin Poulain
Design ©2006-2018 Maxime Vantorre | http://www.linuxcertif.com/man/1/gnunet-search/ | CC-MAIN-2018-30 | en | refinedweb |
Automatic Notificationkumarab May 12, 2017 2:15 AM
Dears,
I want to send three notification after resolution like 1 to Team Lead, 2nd with resolution remark to user and 3rd with survey detail ...
Now my problem is i want to send this in order any put some delay in notification like one next another.
1. Re: Automatic Notificationandreas.lindner May 12, 2017 8:49 AM (in response to kumarab)
Hi,
that is absolutely possible. Did you notice, that if you add the automatic action "Add Reminder" you always have to define the "Send Date"? That is your advantage. Usually there is the simple calculation that returns the Value = DateTime.UtcNow. But that can be amended. For example:
import System static def GetAttributeValue(Reminder): CurrentTime = DateTime.UtcNow Value = CurrentTime.AddMinutes(30) return Value
That will allow you to set the send date to 30 minutes into the future. The mail engine will consider the send date before sending, so you will be able to use three subsequent "Add Reminder" actions and every one of the actions will have a different send date. Just set a different value for the AddMinutes method in the different "Add Reminder" actions.
Regards
Andreas | https://community.ivanti.com/thread/35714 | CC-MAIN-2018-30 | en | refinedweb |
Rendering to physical sizes, how to let it work on all platforms?
I'm creating an application that should render things to physical sizes, i.e. an intermediate goal would be to render a square that is 4x3 cm on all displays (using both iOS & windows).
(I understand that its not really possible to do this always correct as the real world size of screens varies)
the problem I ran into today is that on iOS there is a 2x factor which I can't identify by using generic calls.
QGuiApplication::primaryScreen()->devicePixelRatio()
returns 1 on a iPad (incorrect? - iOS 9.3) and 2 on a iPhone (correct? - also iOS 9.3)
or am i missing something?
using a QQuickPaintedItem derived class in the paint(QPainter *painter) function:
auto physicalpixelsperinch = painter->device->physicalDpiX() * QGuiApplication::primaryScreen()->devicePixelRatio();
is (more or less) correct for windows and a iPhone, but not for an iPad.
what I am I missing here?
Hi
On Desktop and Android, something like this should work:
import QtQuick.Window 2.2 Rectangle { property real mm: Screen.pixelDensity width: 40*mm height: 30*mm }
The problem is that, on Android, depending on the devices, the hardware vendors dont supply reliable firmware, and usually Screen.pixelDensity doesnt give acurate values. On desktop, I usualy get correct values. Not sure abou t IOS, but please check it and let me know :)
You could check out the pixelToInches function that is included in the V-Play SDK.
@johngod Thank you so much, you're right Screen.pixelDensity would be the complete solution if it was in qml,
sifting trough the qt source i was able that it was derived from:
double pixelpermm = QGuiApplication::primaryScreen()->physicalDotsPerInch() / 25.4 //physicalDotsPerInchX() & physicalDotsPerInchY() also exist
and it seems to be correct on both my iPhone & iPad quite wel (better than all other ways I found so far)
@Lorenz thanks, but for the time being I want to stick to Qt as it is a paid sdk as soon as you go commercial | https://forum.qt.io/topic/79078/rendering-to-physical-sizes-how-to-let-it-work-on-all-platforms | CC-MAIN-2018-30 | en | refinedweb |
zune free dvd converter
free DVD converter for Mac
dvd to dvd Converter
DVD to WMV DVD to WMV Converter
dvd Converter ifo dvd Dual
ipod converter dvd to ipod dvd to mp4
Free dvd to avi converter
Free powerpoint to dvd converter
free ppt to dvd converter
leawo free dvd to apple tv converter
free dvd to ipad converter
dvdvideomedia free dvd to 3gp converter
leawo free dvd to psp converter
MBOX to PDF Converter Online is one of the best solutions that can easily convert MBOX to PDF online embedded all emails and attachments.
mbox to pdf converter online
Zimbra Converter Tool programmed with responsive nature that easily import TGZ file into Thunderbird with complete database without loss of data. Free download to import TGZ file into Thunderbird process that help for users to understand the complete working functionality.
import tgz file into thunderbird
Zimbra Converter Tool programmed with responsive nature that easily import TGZ file into Thunderbird with complete database without loss of data. Free download to import TGZ file into Thunderbird process that help for users to understand the complete working functionality. .
Smartly use IncrediMail to Windows Mail Converter that quickly import emails from IncrediMail to Windows Mail. The IncrediMail Converter is definitely useful that import emails from IncrediMail 2.
then try IncrediMail to Mac Mail Converter Software that could smoothly convert IncrediMail to Mac Mail. It also offers free demo version to convert 25 emails from IncrediMail to Mac Mail at free of cost. .
BurnAware Free is a full-fledged. free burning software which allows users to write all types of files such as digital photos.. .
Filter: All / Freeware only / Title
OS: Mac / Mobile / Linux
Sort by: Download / Rating / Update | http://freedownloadsapps.com/update-free-dvd-converter.html | CC-MAIN-2018-30 | en | refinedweb |
Issues
ZF-7063: Zend_Loader_Autoloader::getClassAutoloaders() incorrectly detects module namespaces...
Description
My application is structured as follows...
application modules admin sales sales-admin
In Zend_Loader_Autoloader (line 308), it detects the namespace incorrectly and returns the wrong autoloader for all classes in sales-admin (instead bringing back those from Sales.
Proposed fix is to replace line 308 if (0 === strpos($class, $ns)) {
with the following if (0 === strpos($class, $ns.'_')) {
This seems to fix things, but I'm not entirely sure if that's going to cover it... maybe a little regex would be more helpful...
Posted by Ben Fox (wildfoxmedia) on 2009-07-14T01:18:37.000+0000
I would just like to add that I am having the same issue with 2 modules/namespaces of my own.
news & news-aggregator
Posted by Hinikato Dubrai (hinikato) on 2009-08-20T16:45:33.000+0000
Yes, I have the same problem too. If two modules begin with the same prefix, then Zend_Loader_Autoloader will return invalid result.
For example, if we have "foo" module and "foo-bar" module, Zend_Loader_Autoloader will return autoloaders for the first module ("foo").
Posted by Hinikato Dubrai (hinikato) on 2009-08-20T17:12:40.000+0000
This is bug example:
Posted by Matthew Weier O'Phinney (matthew) on 2009-08-21T04:30:19.000+0000
This was fixed for 1.9.1 (see ZF-7473) | http://framework.zend.com/issues/browse/ZF-7063 | CC-MAIN-2016-18 | en | refinedweb |
iRenderBufferAccessor Struct ReferenceInterface for renderbuffer accessor.
More...
[3D]
#include <ivideo/rndbuf.h>
Inheritance diagram for iRenderBufferAccessor:
Detailed DescriptionInterface for renderbuffer accessor.
The renderbuffer accesor is similar to the shadervariable accessor system, and is used to delay calculation of the content of renderbuffers.
Definition at line 276 of file rndbuf.h.
Member Function Documentation
Called before associated renderbuffer is fetched from the holder.
The documentation for this struct was generated from the following file:
Generated for Crystal Space 1.0.2 by doxygen 1.4.7 | http://www.crystalspace3d.org/docs/online/api-1.0/structiRenderBufferAccessor.html | CC-MAIN-2016-18 | en | refinedweb |
Timeline …
03/12/10:
- 23:37 Changeset [64663] by
- preserve requested property in upgrade
- 23:34 Changeset [64662] by
- fix option handling in registry::run_target
- 22:55 Ticket #21293 (finch doesn't compile in 1.8) closed by
- fixed
- 22:49 Changeset [64661] by
- factor out code for running targets on portfiles in the registry into new …
- 21:54 Changeset [64660] by
- Total number of ports parsed: 6662 Ports successfully parsed: 6662 …
- 21:14 Ticket #23119 (kdelibs3 build fails when kde4 ports are installed) closed by
- fixed: Replying to ryandesign@…: > If kdelibs3 is incompatible with …
- 21:12 Changeset [64659] by
- kdelibs3, kdelibs4: declare conflicts (#23119)
- 20:59 Ticket #22907 (EMBOSS needs to declare dependencies on the ports it uses) closed by
- fixed: Maintainer timeout. I added some missing dependencies and updated the port …
- 20:58 Changeset [64658] by
- Update to version 6.2.0. Added some missing dependencies. (#22907)
- 20:54 Changeset [64657] by
- Total number of ports parsed: 6662 Ports successfully parsed: 6662 …
- 20:38 Changeset [64656] by
- error handling when running portfiles from the registry
- 19:55 Ticket #23596 (Update NSD port to version 3.2.4) closed by
- fixed: r64655.
- 19:55 Changeset [64655] by
- Update to version 3.2.4. (#23596)
- 19:49 Ticket #23622 (finch update: updates to 2.6.5) closed by
- fixed: r64654.
- 19:47 Changeset [64654] by
- Update to version 2.6.5. (#23622)
- 19:39 Changeset [64653] by
- explicitly run deactivate target in action_uninstall when needed so as to …
- 19:33 Ticket #24034 (Import problem with gtk and pygtk after installing sucessfully py26-gtk ...) closed by
- invalid: I suggest you post on the macports-users list.
- 18:54 Changeset [64652] by
- Total number of ports parsed: 6662 Ports successfully parsed: 6662 …
- 18:28 Changeset [64651] by
- sqlite3: work around build failure on tiger (doesn't have gethostuuid)
- 17:45 Ticket #24036 (New port: p5-set-scalar) created by
- Hi, I'm submitting a new Portfile for the perl module Set::Scalar. jpo
- 17:19 Ticket #18629 (Support RTree in sqlite3 port) closed by
- duplicate: #21410
- 17:16 Ticket #21875 (sqlite3-3.6.18 Enable full-text search module (fts3)) closed by
- duplicate: Superseded by #23350.
- 14:42 Changeset [64650] by
- tell configure if we want 64 bit
- 12:54 Changeset [64649] by
- Total number of ports parsed: 6662 Ports successfully parsed: 6662 …
- 12:38 Changeset [64648] by
- Added portfile for pystache
- 11:38 Ticket #24035 (lurker portfile update) created by
- I am in need of the lurker Portfile to be updated. […] …
- 11:33 Ticket #24034 (Import problem with gtk and pygtk after installing sucessfully py26-gtk ...) created by
- I have installed sucessfully the python26 and py25-gtk after the patch …
- 11:06 Ticket #24033 (atlas-3.8.3 fails to compile on Core i7) created by
- I'm quiet new here, but I have long Linux experience (Gentoo). Atlas fails …
- 10:54 Changeset [64647] by
- Total number of ports parsed: 6661 Ports successfully parsed: 6661 …
- 10:31 Changeset [64646] by
- squid: update to 2.7.STABLE8
- 10:21 Changeset [64645] by
- delete any existing registry1.0 directory during install
- 10:12 Changeset [64644] by
- delete mp_version file in DESTDIR
- 10:04 Changeset [64643] by
- revert r64642, caused breakage
- 10:00 Ticket #24032 (gnuradio 3.2.2+python25 install failure) created by
- Intel MacBook Pro running OS X 10.5.8 XCode version 3.1.2 …
- 09:54 Changeset [64642] by
- fix ui_channels aliasing issue
- 09:52 Changeset [64641] by
- fix multiple portuninstall namespace confusion
- 08:54 Ticket #20626 (patch to allow for proper functioning of pre-/post- ...) closed by
- duplicate: #1068, #4228, and/or #18273
- 08:48 Ticket #19176 (patch to fixup existing uninstall implementation) closed by
- fixed: Applied in r64640.
- 08:47 Changeset [64640] by
- fix flat registry's pkg_uninstall functionality (#19176)
- 08:10 Ticket #18273 (post-activate code is not run if you call port activate) closed by
- fixed: r64638 & r64639
- 08:00 Ticket #4228 (Add A Deactivate Hook) closed by
- fixed: r64638
- 07:59 Ticket #1068 (Pre/Post-install and Post-removal scripts) closed by
- fixed: r64638
- 07:46 Changeset [64639] by
- fix up running of activate target and autoclean
- 06:28 Changeset [64638] by
- make deactivate and uninstall into real targets, have …
03/11/10:
- 21:50 Ticket #22310 (distcc fails to build on Snow Leopard) closed by
- duplicate: #20902
- 21:47 Ticket #24024 (Pallet fails to start (crash)) closed by
- duplicate: #21259
- 21:10 Ticket #24031 (stklos-0.98 invalid URL) created by
- Dependencies download and build fine. Package stklos fails with the …
- 21:08 Ticket #24030 (mlt: update to upstream version 0.5.2) created by
- This also addresses ticket #23878 by explicitly depending on ffmpeg-devel. …
- 17:00 Changeset [64637] by
- devel/icu: Disable ccache, #23931
- 16:26 Ticket #24029 (gnome-doc-utils: xml2po python module in wrong path) created by
- gnome-doc-utils @0.18.1 includes a python module named xml2po which is …
- 16:00 SummerOfCodeOrgApplication edited by
- Updating number of ports (diff)
- 15:54 Changeset [64636] by
- Total number of ports parsed: 6661 Ports successfully parsed: 6661 …
- 15:45 Ticket #24028 (Bigloo3.2a-2 fails to compile) created by
- Here's my build log: […]
- 15:05 Changeset [64635] by
- xorg-util-macros: Bump to 1.6.1
- 14:36 Ticket #23894 (sudo port install zlib fails on Snow Leopard) closed by
- invalid: Replying to raimue@…: > The message "Portfile changed since …
- 14:19 SummerOfCodeOrgApplication edited by
- (diff)
- 13:11 Ticket #24019 (Problem installing gtk2 python26 py26-gtk on 10.6.2 Snow Leopard) closed by
- duplicate: Duplicate of #20799.
- 12:54 Changeset [64634] by
- Total number of ports parsed: 6661 Ports successfully parsed: 6661 …
- 12:28 Changeset [64633] by
- version 3.6.23
- 10:44 SummerOfCodeOrgApplication edited by
- (diff)
- 10:12 SummerOfCodeOrgApplication edited by
- (diff)
- 09:12 SummerOfCode edited by
- Add mentors (diff)
- 09:00 SummerOfCodeOrgApplication edited by
- (diff)
- 08:59 Ticket #24027 (Python bindings for OpenCV) created by
- OpenCV 2.0 includes Python bindings, but they are turned off by the …
- 08:49 Ticket #24026 (py26-igraph too new for c core (igraph 0.5.2)) created by
- The current python bindings [py26-igraph @0.5.3] for igraph are too new …
- 08:23 SummerOfCodeOrgApplication edited by
- More answers… (diff)
- 07:57 SummerOfCodeOrgApplication edited by
- (diff)
- 07:54 Changeset [64632] by
- Total number of ports parsed: 6661 Ports successfully parsed: 6661 …
- 07:33 Changeset [64631] by
- handle empty variant strings correctly in receipt_sqlite
- 07:17 Changeset [64630] by
- list_dependents usage
- 07:10 Changeset [64629] by
- Version bump, svk to 2.2.2
- 07:04 Changeset [64628] by
- upgrade dependents before uninstalling old versions
- 07:02 Ticket #24025 (p5-module-build conflicts with perl5.10) created by
- both ports attempt to install ${prefix}/bin/config_data
- 07:00 Changeset [64627] by
- enable checking dependents on inactive ports, check when uninstalling and …
- 05:42 Changeset [64626] by
- fix deactivation of replaced ports when their files conflict during …
- 05:41 Ticket #24024 (Pallet fails to start (crash)) created by
- I just installed Pallet (via port) on first (and subsequent) load It …
- 04:49 Changeset [64625] by
- 'registry::entry imaged' actually means imaged or installed
- 02:54 Changeset [64624] by
- Total number of ports parsed: 6661 Ports successfully parsed: 6661 …
- 02:48 Changeset [64623] by
- install camlzip shared library in stub-libs correctly so that runtime …
- 02:29 Changeset [64622] by
- build fixes for camlzip: actually install META file, call package camlzip …
- 02:08 SummerOfCode edited by
- Change logo URL, add license information (diff)
- 01:31 SummerOfCode edited by
- (diff)
- 01:14 Ticket #24023 (distcc fails to build +universal on SL) created by
- distcc does not build: universal is: x86_64 and i386 on Snow Leopard …
Note: See TracTimeline for information about the timeline view. | http://trac.macports.org/timeline?from=2010-03-15T00%3A39%3A50-0700&precision=second | CC-MAIN-2016-18 | en | refinedweb |
Page 1 of 2
A set of questions, especially programming questions asked in most of the interviews.Some of the questions are trivial and some are tricky. So get prepared before getting embarrassed in interview.
- How to identify a given positive decimal number as even/odd without using % or / operator ?
A plain trap, even for those experienced people. You may be very good at coding,but if you questioning how on earth you could solve this problem.Then here is a solution. If you remember the good old days of our primary school then the solution is easy,"division is a matter of iterative subtraction".
public class TestEvenOdd { public static void main(String arg[]){ int num=6; int result=num; while(result>=2){ result=result-2; } if(result==1){ System.out.println("The number is odd"); }else{ System.out.print("The number is even"); } } }
- Convert a given string as "11/12/2010" to a Date object.
For those who are new to Java development may think this would be a big programming to solve this.But remember Java is famous for its libraries
import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class StringToDate { public static void main(String args[]) throws ParseException{ SimpleDateFormat sdf=new SimpleDateFormat("dd/MM/yyyy"); String dateString="11/12/2010"; Date d=sdf.parse(dateString); System.out.println(d); } }
- Find out the number of days in between two given dates ?
- How to divide a number by 2 without using / operator ?
- How to multiply a number by 2 without using * operator ?
- How to swap two variables,by using pass by reference method ?
- How to make a list immutable ?
You can make a list unmodifiable by List al = new ArrayList(); List l= Collections.unmodifiableList(al); here the l reference can't modify the list. But changes made to the al variable can still be visible in the l.
- Write a Immutable class.
- Write a program that proves Strings are immutable.
Ans:Though there is no way to find if Strings are immutable through coding, but the code below is an attempt to show if Strings are mutable.Remember the only way to say if Strings are immutable is to see the API.
public class ImmutableTest { public static void main(String ags[]){ String initial = "ABCDEFG"; String after = initial.replace('A', 'Z'); System.out.println("initial = " + initial); System.out.println("after= " + after); } }
- How do you determine if a given class or object implements a given interface through coding.(Without looking at the java file of the class) ?
- Given an complex object and it's method which returns an array of strings but method return type is Object[], write code not more than a single line and without using any String related method , assigns the first String in the returned String array to a String variable ?
Lets suppose the method looks something very trivial like below
public Object[] returnStringAsArray(){ return new String[]{"abc","def"}; }then the code that would call the method and assign the first string to a String variable is
String s=(String)returnStringArray()[0];
- If you assign null to the String variable, and then you print the variable what will be the output ? Justify your answer.
No, the answer is not NullPointerException,It will print null.Many beginners confuse that case like this would lead to the NullPointerExeception.Such exception will arise only if the object reference (which is not pointing to any object ),is used ,to try to access the object's behavior or properties.
- What is Tripleton design pattern , and write a tripleton class ? | http://www.bullraider.com/java/core-java/33-interview-questions | CC-MAIN-2016-18 | en | refinedweb |
How to File an Estate’s Probate Inventory
The probate court will require the executor of an estate to file an inventory of all the decedent’s assets. Preparing this probate inventory should be the executor’s next step after finding the assets and valuing them. Check with your local probate court to verify proper procedures and deadlines for filing the inventory.
Your local probate court has an inventory form for you to use. If all the assets don’t fit, add additional sheets in the same format. Include any assets subject to probate on this inventory, including assets in the decedent’s name alone, held as a tenant in common, joint for convenience only, or payable to the estate. There is usually an inventory filing fee that the estate must pay.
Your court probably has a deadline for filing the inventory. Check to see how flexible this deadline is in practice. You may need extra time to collect and value the assets. This deadline will likely be close to the deadline for filing the estate tax return (nine months after date of death). In some states, the inventory must be filed before you can sell the real estate.
Be sure to use the sales price on your inventory. If you’re selling for less than inventory value, you may have a problem receiving any necessary license from the probate court. The inventory limits your liability as executor to the values shown on the inventory, if you have used market values as of the decedent’s date of death. | http://www.dummies.com/how-to/content/how-to-file-an-estates-probate-inventory.navId-323698.html | CC-MAIN-2016-18 | en | refinedweb |
RESTful File Upload for AppEngine
Google's AppEngine is an awesome platform for simple web apps. Unfortunately one of the more glaring limitations is the lack of filesystem access. Fortunately, their robust data storage API can make up for the omission in many cases.
The Use Case
I wanted to have integrated image hosting for this blog so I wrote a REST handler to upload and serve image files for GAE's Python API.
The Code
Google's
Appengine documentation actually provides the meat of the datastore code.
The remaining know-how comes from the Python API
Webapp framework module.
First, a simple data model, very similar to the AppEngine documentation example:
from google.appengine.ext import db class Image(db.Model): name = db.StringProperty(required=True) data = db.BlobProperty(required=True) mimeType = db.StringProperty(required=True) created = db.DateTimeProperty(auto_now_add=True) owner = db.UserProperty(auto_current_user_add=True)
Now that we have that out of the way, here's the upload (POST handler) code:
import logging from google.appengine.ext import webapp from models.image import Image urlBase = '/imgstore/%s' class ImageHandler(webapp.RequestHandler): def post(self,id): logging.info("ImagestoreHandler#post %s", self.request.path) fileupload = self.request.POST.get("file",None) if fileupload is None : return self.error(400) # it doesn't seem possible for webob to get the Content-Type header for the individual part, # so we'll infer it from the file name. contentType = getContentType( fileupload.filename ) if contentType is None: self.error(400) self.response.headers['Content-Type'] = 'text/plain' self.response.out.write( "Unsupported image type: " + fileupload.filename ) return logging.info( "File upload: %s, mime type: %s", fileupload.filename, contentType ) img = Image( name=fileupload.filename, data= fileupload.file.read(), mimeType=contentType ) img.put() logging.info("Saved image to key %s", img.key() ) #self.redirect(urlBase % img.key() ) #dummy redirect is acceptable for non-AJAX clients, def getContentType( filename ): # lists and converts supported file extensions to MIME type ext = filename.split('.')[-1].lower() if ext == 'jpg' or ext == 'jpeg': return 'image/jpeg' if ext == 'png': return 'image/png' if ext == 'gif': return 'image/gif' if ext == 'svg': return 'image/svg+xml' return None
The upload from an HTML form will be a multipart-mime request. Because of that,
self.request.POST.get("file") must be used to get a dict of request
properties from that portion of the multipart request.
fileupload is
a dict of properties which includes the file name and uploaded data. Note that most
user-agents will send a
Content-Type header for that portion of the request, however
I couldn't figure out how to access it using the Webob API. To solve that, I just
created a
getContentType() method to infer the file type given the uploaded
file name. This also allows you to prohibit unwanted files from being
uploaded.
The one last piece of information needed is the URL mapping to the ImageHandler class in
main.py:
ROUTES = [ ('/imgstore/?([\w]*)/?', imagestore.ImageHandler) # other handlers here... ] def main(): application = webapp.WSGIApplication(ROUTES) wsgiref.handlers.CGIHandler().run(application) if __name__ == "__main__": main()
Now that we're able to upload files, let's access them:
# part of ImageHandler class def get(self,id): logging.info("ImagestoreHandler#get for file: %s", id) img = None try: img = Image.get( id ) if not img: raise "Not found" except: self.error(404) self.response.headers['Content-Type'] = 'text/plain' self.response.out.write( "Could not find image: '%s'" % id ) return logging.info( "Found image: %s, mime type: %s", img.name, img.mimeType ) dl = self.request.get('dl') # optionally download as attachment if dl=='1' or dl=='true': self.response.headers['Content-Disposition'] = 'attachment; filename="%s"' % str(img.name) self.response.headers['Content-Type'] = str(img.mimeType) self.response.out.write( img.data )
A
GET request will have the Image's datastore 'key' property in the URL
like this example. (Note the image is being served by my blog, which is running on AppEngine.)
As a final bonus I've also implemented a 'list' function if an image ID is not
given in the
GET request. You can see the
full
code on GitHub (including authorization, which is covered elsewhere).
Conclusion
This should be everything you need to have a REST-ful Python image handler for AppEngine! Finally, here's a sample upload form to test with. Note that this will only work for relatively small files - Google's DataStore limits entity size to 1 MB, but that's more than enough for web
4 Comments
In that case, you'll want to use the Picasa support that I just added last week :)
I'm also considering general attachment support, which could be interesting to support via Google Documents, especially considering they've added support for any file type.
I might implement it as a datastore or GDocs option, but considering the size limit and the additional capabilities of Picasa and GDocs, it's almost silly to use the local datastore option. I'll support it as more of an exercise I suppose.
Re: RESTful File Upload for AppEngine Jan. 25, 2011 po | http://blog.thomnichols.org/2009/12/restful-file-upload-for-appengine | CC-MAIN-2016-18 | en | refinedweb |
QStringLiteral explained
QStringLiteral is a new macro introduced in Qt 5 to create QString from string literals. (String literals are strings inside "" included in the source code). In this blog post, I explain its inner working and implementation.
Summary
Let me start by giving a guideline on when to use it:
- Most of the cases:
QStringLiteral("foo")if it will actually be converted to QString
QLatin1String("foo")if it is use with a function that has an overload for
QLatin1String. (such as
operator==, operator+, startWith, replace, ...)
I have put this summary at the beginning for the ones that don't want to read the technical details that follow.
Read on to understand how QStringLiteral works
Reminder on how QString works
QString, as many classes in Qt, is an implicitly shared class. Its only member is a pointer to the 'private' data. The QStringData is allocated with malloc, and enough room is allocated after it to put the actual string data in the same memory block.
// Simplified for the purpose of this blog struct QStringData { QtPrivate::RefCount ref; // wrapper around a QAtomicInt int size; // size of the string uint alloc : 31; // amount of memory reserved after this string data uint capacityReserved : 1; // internal detail used for reserve() qptrdiff offset; // offset to the data (usually sizeof(QSringData)) inline ushort *data() { return reinterpret_cast<ushort *>(reinterpret_cast<char *>(this) + offset); } }; // ... class QString { QStringData *d; public: // ... public API ... };
The offset is a pointer to the data relative to the QStringData. In Qt4, it used to be an actual pointer. We'll see why it has been changed.
The actual data in the string is stored in UTF-16, which uses 2 bytes per character.
Literals and Conversion
Strings literals are the strings that appears directly in the source code, between quotes.
Here are some examples. (suppose
action, string, and
filename are QString
o->setObjectName("MyObject"); if (action == "rename") string.replace("%FileName%", filename);
In the first line, we call the function
QObject::setObjectName(const QString&).
There is an implicit conversion from
const char* to QString, via its constructor.
A new QStringData is allocated with enough room to hold "MyObject", and then the string is
copied and converted from UTF-8 to UTF-16.
The same happens in the last line where the function
QString::replace(const QString &, const QString &) is called.
A new QStringData is allocated for "%FileName%".
Is there a way to prevent the allocation of QStringData and copy of the string?
Yes, one solution to avoid the costly creation of a temporary QString object is to have overload for
common function that takes
const char* parameter.
So we have those overloads for
operator==
bool operator==(const QString &, const QString &); bool operator==(const QString &, const char *); bool operator==(const char *, const QString &)
The overloads do not need to create a new QString object for our literal and can operate directly on the raw char*.
Encoding and QLatin1String
In Qt5, we changed the default decoding for the char* strings to UTF-8. But many algorithms are much slower with UTF-8 than with plain ASCII or latin1
Hence you can use
QLatin1String, which is just a thin wrapper around
char *
that specify the encoding. There are overloads taking
QLatin1String for functions that can opperate or
the raw latin1 data directly without conversion.
So our first example now looks like:
o->setObjectName(QLatin1String("MyObject")); if (action == QLatin1String("rename")) string.replace(QLatin1String("%FileName%"), filename);
The good news is that
QString::replace and
operator== have overloads for QLatin1String.
So that is much faster now.
In the call to setObjectName, we avoided the conversion from UTF-8, but we still have an (implicit) conversion from QLatin1String to QString which has to allocate the QStringData on the heap.
Introducing
QStringLiteral
Is it possible to avoid the allocation and copy of the string literal even for the cases like
setObjectName?
Yes, that is what
QStringLiteral is doing.
This macro will try to generate the QStringData at compile time with all the field initialized. It will even be located in the .rodata section, so it can be shared between processes.
We need two languages feature to do that:
- The possibility to generate UTF-16 at compile time:
On Windows we can use the wide char
L"String". On Unix we are using the new C++11 Unicode literal:
u"String". (Supported by GCC 4.4 and clang.)
- The ability to create static data from expressions.
We want to be able to put QStringLiteral everywhere in the code. One way to do that is to put a
static QStringDatainside a C++11 lambda expression. (Supported by MSVC 2010 and GCC 4.5) (
And we also make use of the GCCUpdate: The support for the GCC extension was removed before the beta because it does not work in every context lambas are working, such as in default functions arguments)
__extension__ ({ })
Implementation
We will need need a POD structure that contains both the QStringData and the actual string. Its structure will depend on the method we use to generate UTF-16.
The code bellow was extracted from qstring.h, with added comments and edited for readability.
/* We define QT_UNICODE_LITERAL_II and declare the qunicodechar depending on the compiler */ #if defined(Q_COMPILER_UNICODE_STRINGS) // C++11 unicode string #define QT_UNICODE_LITERAL_II(str) u"" str typedef char16_t qunicodechar; #elif __SIZEOF_WCHAR_T__ == 2 // wchar_t is 2 bytes (condition a bit simplified) #define QT_UNICODE_LITERAL_II(str) L##str typedef wchar_t qunicodechar; #else typedef ushort qunicodechar; // fallback #endif // The structure that will contain the string. // N is the string size template <int N> struct QStaticStringData { QStringData str; qunicodechar data[N + 1]; }; // Helper class wrapping a pointer that we can pass to the QString constructor struct QStringDataPtr { QStringData *ptr; };
#if defined(QT_UNICODE_LITERAL_II) // QT_UNICODE_LITERAL needed because of macro expension rules # define QT_UNICODE_LITERAL(str) QT_UNICODE_LITERAL_II(str) # if defined(Q_COMPILER_LAMBDA) # define QStringLiteral(str) \ ([]() -> QString { \ enum { Size = sizeof(QT_UNICODE_LITERAL(str))/2 - 1 }; \ static const QStaticStringData<Size> qstring_literal = { \ Q_STATIC_STRING_DATA_HEADER_INITIALIZER(Size), \ QT_UNICODE_LITERAL(str) }; \ QStringDataPtr holder = { &qstring_literal.str }; \ const QString s(holder); \ return s; \ }()) \ # elif defined(Q_CC_GNU) // Use GCC To __extension__ ({ }) trick instead of lambda // ... <skiped> ... # endif #endif #ifndef QStringLiteral // no lambdas, not GCC, or GCC in C++98 mode with 4-byte wchar_t // fallback, return a temporary QString // source code is assumed to be encoded in UTF-8 # define QStringLiteral(str) QString::fromUtf8(str, sizeof(str) - 1) #endif
Let us simplify a bit this macro and look how the macro would expand
o->setObjectName(QStringLiteral("MyObject")); // would expand to: o->setObjectName(([]() { // We are in a lambda expression that returns a QStaticString // Compute the size using sizeof, (minus the null terminator) enum { Size = sizeof(u"MyObject")/2 - 1 }; // Initialize. (This is static data initialized at compile time.) static const QStaticStringData<Size> qstring_literal = { { /* ref = */ -1, /* size = */ Size, /* alloc = */ 0, /* capacityReserved = */ 0, /* offset = */ sizeof(QStringData) }, u"MyObject" }; QStringDataPtr holder = { &qstring_literal.str }; QString s(holder); // call the QString(QStringDataPtr&) constructor return s; }()) // Call the lambda );
The reference count is initialized to -1. A negative value is never incremented or decremented because we are in read only data.
One can see why it is so important to have an offset (qptrdiff) rather than a pointer to the string (ushort*) as it was in Qt4. It is indeed impossible to put pointer in the read only section because pointers might need to be relocated at load time. That means that each time an application or library, the OS needs to re-write all the pointers addresses using the relocation table.
Results
For fun, we can look at the assembly generated for a very simple call to QStringLiteral. We can see that there is almost no code, and how the data is laid out in the .rodata section
We notice the overhead in the binary. The string takes twice as much memory since it is encoded in UTF-16, and there is also a header of sizeof(QStringData) = 24. This memory overhead is the reason why it still makes sense to still use QLatin1String when the function you are calling has an overload for it.
QString returnAString() { return QStringLiteral("Hello"); }
Compiled with
g++ -O2 -S -std=c++0x (GCC 4.7) on x86_64
.text .globl _Z13returnAStringv .type _Z13returnAStringv, @function _Z13returnAStringv: ; load the address of the QStringData into %rdx leaq _ZZZ13returnAStringvENKUlvE_clEvE15qstring_literal(%rip), %rdx movq %rdi, %rax ; copy the QStringData from %rdx to the QString return object ; allocated by the caller. (the QString constructor has been inlined) movq %rdx, (%rdi) ret .size _Z13returnAStringv, .-_Z13returnAStringv .section .rodata .align 32 .type _ZZZ13returnAStringvENKUlvE_clEvE15qstring_literal, @object .size _ZZZ13returnAStringvENKUlvE_clEvE15qstring_literal, 40 _ZZZ13returnAStringvENKUlvE_clEvE15qstring_literal: .long -1 ; ref .long 5 ; size .long 0 ; alloc + capacityReserved .zero 4 ; padding .quad 24 ; offset .string "H" ; the data. Each .string add a terminal '\0' .string "e" .string "l" .string "l" .string "o" .string "" .string "" .zero 4
Conclusion
I hope that now that you have read this you will have a better understanding on where to use and not to use
QStringLiteral.
There is another macro QByteArrayLiteral, which work exactly on the same principle but creates a QByteArray.
Update: See also the internals of QMutex and more C++11 features in Qt5.
Woboq is a software company expert in development and consulting around Qt and C++. Hire us!
If you like this blog and want to read similar articles, consider subscribing via our RSS feed, by e-mail or follow us on twitter or add us on G+.
Article posted by Olivier Goffart on 21 May 2012
Read About Woboq, use our Software Development Services, check out our Products, like the Code Browser, or learn new things about software development on our Blog. | http://woboq.com/blog/qstringliteral.html | CC-MAIN-2016-18 | en | refinedweb |
.
package com.leebutts import org.springframework.jdbc.datasource .lookup.AbstractRoutingDataSource import com.leebutts.Environment import org.springframework.context.ApplicationContextAware import org.springframework.context.ApplicationContext import javax.sql.DataSource import org.springframework.jdbc.datasource.DriverManagerDataSource class SwitchableDataSource extends AbstractRoutingDataSource implements ApplicationContextAware { def applicationContext public void setApplicationContext(ApplicationContext applicationContext) { this.applicationContext = applicationContext } protected DataSource determineTargetDataSource() { DriverManagerDataSource ds = super.determineTargetDataSource(); def env = EnvironmentHolder.getEnvironment() if (env && env.passwordRequired && ds) { ds.setPassword(env.password) } return ds } protected Object determineCurrentLookupKey() { def env = EnvironmentHolder.getEnvironment() return env?.id ?: Environment.list()[0]?.id } }SwitchableDataSource is the facade that delegates to the list of standard DriverManager data sources. They are defined in grails-app/conf/spring/resources.groovy using the environment settings from the Environment class. Here's my spring config in resources.groovy:
import com.leebutts.SwitchableDataSource import com.leebutts.Environment import org.springframework.jdbc.datasource.DriverManagerDataSource beans = { parentDataSource(DriverManagerDataSource) { bean -> bean.'abstract' = true; driverClassName = 'com.mysql.jdbc.Driver' username = "root" } Environment.list().each {env -> "${env.prefix}DataSource"(DriverManagerDataSource) {bean -> bean.parent = parentDataSource bean.scope = 'prototype' def port = env.port ?: 3306 url = "jdbc:mysql://${env.host}:${port}/switchingDemo" if (env.user) { username = env.user } if (env.password) { password = env.password } } } def dataSources = [:] Environment.list().each {env -> dataSources[env.id] = ref(env.prefix + 'DataSource') } dataSource(SwitchableDataSource) { targetDataSources = dataSources } }Environment currently uses a static list to hold the environment config. This could be done better via a reloadable properties file or by adding a view/controller to modify the environment settings on the fly. Environment.groovy:
package com.leebutts class Environment { static environments = [] static { environments << [id: 1, name: 'local', prefix: 'local', host: 'localhost'] environments << [id: 2, name: 'UAT', prefix: 'uat', host: 'uat.leebutts.com'] environments << [id: 3, name: 'Testing', prefix: 'testing', host: 'testing.leebutts.com'] environments << [id: 4, name: 'Beta', prefix: 'beta', host: 'beta.leebutts.com', passwordRequired: true] environments << [id: 5, name: 'Prod', prefix: 'prod', host: 'db.leebutts.com', user:'grails', port: 13306, passwordRequired: true] //unique id check environments.each {env -> assert environments .findAll {it.id == env.id}.size() == 1} } static list() { return environments } }SwitchableDataSource needs a way to determine which environment the current request wishes to use. It does this via a ThreadLocal holder EnvironmentHolder.groovy:
package com.leebutts class EnvironmentHolder { private static final ThreadLocal contextHolder = new ThreadLocal(); static void setEnvironment(Map environment) { contextHolder.set(environment); } static getEnvironment() { return contextHolder.get(); } static void clear() { contextHolder.remove(); } }Now that the infrastructure is in place, the next step is to add a controller to allow users to select the environment they wish to use and a filter to set a default environment if one has not yet been chosen. The controller is called via ajax (in my application) but could be used as a standard controller just as easily. It looks up the Environment based on an ID and then tests the connection to make sure the password supplied is valid (if a password is required as specified in the environment config). If a password is being used it takes a copy of the environment config map, adds the password and stores it in the session so that the user doesn't have to re-enter the password on every screen and so that only this user has access to the password. EnvironmentController.groovy:
import com.leebutts.Environment import com.leebutts.EnvironmentHolder import javax.servlet.http.HttpServletResponse import org.codehaus.groovy.grails.commons.ApplicationAttributes import org.codehaus.groovy.grails.web.context.ServletContextHolder class EnvironmentController { def change = { if (params.environment) { def env = Environment.list() .find {it.id == new Integer(params.environment)} if (env) { if (env.passwordRequired) { if (params.password) { //take a copy and add a pword env = addPasswordToEnvCopy(params, env) } else { render 'PASSWORD REQUIRED' response.setStatus( HttpServletResponse.SC_UNAUTHORIZED) return } } //test connection def oldEnv = EnvironmentHolder.getEnvironment() EnvironmentHolder.setEnvironment env def ds = getDataSourceForEnv() try { def con = ds.getConnection() session.environment = env render 'Environment change complete.' } catch (e) { EnvironmentHolder.setEnvironment oldEnv render 'Unable to connect to database: ' + e.message response.setStatus( HttpServletResponse.SC_UNAUTHORIZED) return } } else { render 'No such environment' response.setStatus( HttpServletResponse.SC_BAD_REQUEST) } } else { render 'Missing parameter environment' response.setStatus(HttpServletResponse.SC_BAD_REQUEST) } } private def getDataSourceForEnv() { def servletContext = ServletContextHolder.servletContext def ctx = servletContext .getAttribute( ApplicationAttributes.APPLICATION_CONTEXT) return ctx.dataSource } private Map addPasswordToEnvCopy(Map params, env) { def myEnv = [:] env.each {key, val -> myEnv[key] = val } myEnv.password = params.password return myEnv } }As mentioned, there is also a simple filter for defaulting the environment to the first one in the list if one has not been selected and storing it in the ThreadLocal holder. Filters.groovy:
import com.leebutts.EnvironmentHolder import com.leebutts.Environment class Filters { def filters = { all(uri: '/**') { before = { if (!session.environment) { session.environment = Environment.list()[0] } EnvironmentHolder.setEnvironment(session.environment) } } } }The final step is to add an environment selection form to your layout so that users can choose their environment. views/layouts/main.gsp:
<html> <head> <title>Administration System</title> <link rel="stylesheet" href="${createLinkTo(dir: 'css', file: 'main.css')}"/> <g:layoutHead/> <g:javascript <g:javascript <script type="text/javascript"> function refresh() { window.location.reload(false); } function loading() { document.getElementById('spinner').style.display = 'inline'; document.getElementById('error').style.display = 'none'; } function showError(e) { var errorDiv = document.getElementById('error') errorDiv.innerHTML = '<ul><li>' + e.responseText + '</li></ul>'; errorDiv.style.display = 'block'; } </script> </head> <body> <div class="logo"> <div style="margin-left:10px;"> <h1>Current Environment: ${session.environment?.name ?: 'None'}</h1> <form action=""> <g:select <g:passwordField <g:submitToRemote <br/> <div class="errors" id="error" style="display:none;width:500px;"> </div> <img id="spinner" style="display:none;" src="${createLinkTo(dir: 'images', file: 'spinner.gif')}" alt="Spinner"/> </form> </div> </div> <g:layoutBody/> </body> </html>The finished screen looks something like this:
Sunday, July 13, 2008
New PB at Willowbank yesterday
I went out to Willowbank Raceway yesterday for some 1/4 mile fun. My best time was 13.791, about 1/2 a second quicker than last time thanks to a new exhaust, front mount intercooler and clutch. | http://www.leebutts.com/2008_07_01_archive.html | CC-MAIN-2016-18 | en | refinedweb |
);
}
[download]
Read more at blogs.perl.org
but for those occasions when you want the backing of a meta object protocol,
When is that?
The MOP is useful when you need to perform lots of class introspection. It's therefore a requirement for a lot of class-building extensions - i.e. most of the MooseX namespace, such as MooseX::Clone, MooseX::Privacy, MooseX::MultiMethods, etc.
That is; you probably want to use Moose if there's some MooseX module that catches your eye, or you need to delve into $class->meta; and use Moo. | http://www.perlmonks.org/index.pl/jacques?node_id=1050432 | CC-MAIN-2016-18 | en | refinedweb |
audio_engine_channels(9E)
audio_engine_playahead(9E)
- PC Card driver event handler
#include <sys/pccard.h> int32_t prefixevent_handler(event_t event, int32_t priority, event_callback_args_t *args);
Solaris architecture specific (Solaris DDI)
The event.
The priority of the event.
A pointer to the event_callback_t structure.
Each instance of a PC Card driver must register an event handler to manage events associated with its PC Card. The driver event handler is registered using the event_handler field of the client_req_t structure passed to csx_RegisterClient(9F). The driver may also supply a parameter to be passed to its event handler function using the event_callback_args.client_data field. Typically, this argument is the driver instance's soft state pointer. The driver also registers which events it is interested in receiving through the EventMask field of the client_req_t structure.
Each event is delivered to the driver with a priority, priority. High priority events with CS_EVENT_PRI_HIGH set in priority are delivered above lock level, and the driver must use its high-level event mutex initialized with the iblk_cookie returned by csx_RegisterClient(9F) to protect such events. Low priority events with CS_EVENT_PRI_LOW set in priority are delivered below lock level, and the driver must use its low-level event mutex initialized with a NULL interrupt cookie to protect these events.
csx_RegisterClient(9F) registers the driver's event handler, but no events begin to be delivered to the driver until after a successful call to csx_RequestSocketMask(9F).
In all cases, Card Services delivers an event to each driver instance associated with a function on a multiple function PC Card.
The events and their indications are listed below; they are always delivered as low priority unless otherwise noted:
A registration request processed in the background has been completed.
A PC Card has been inserted in a socket.
A PC Card's READY line has transitioned from the busy to ready state.
A PC Card has been removed from a socket. This event is delivered twice; first as a high priority event, followed by delivery as a low priority event. As a high priority event, the event handler should only note that the PC Card is no longer present to prevent accesses to the hardware from occurring. As a low priority event, the event handler should release the configuration and free all I/O, window and IRQ resources for use by other PC Cards.
The battery on a PC Card is weak and is in need of replacement.
The battery on a PC Card is no longer providing operational voltage.
Card Services has received a resume notification from the system's Power Management software.
Card Services has received a suspend notification from the system's Power Management software.
A mechanical latch has been manipulated preventing the removal of the PC Card from the socket.
A mechanical latch has been manipulated allowing the removal of the PC Card from the socket.
A request that the PC Card be ejected from a socket using a motor-driven mechanism.
A motor has completed ejecting a PC Card from a socket.
A queued erase request that is processed in the background has been completed.
A request that a PC Card be inserted into a socket using a motor-driven mechanism.
A motor has completed inserting a PC Card in a socket.
A hardware reset has occurred.
A request for a physical reset by a client.
A reset request that is processed in the background has been completed.
A reset is about to occur.
A request that the client return its client information data. If GET_CLIENT_INFO_SUBSVC(args->client_info.Attributes) is equal to CS_CLIENT_INFO_SUBSVC_CS, the driver should fill in the other fields in the client_info structure as described below, and return CS_SUCCESS. Otherwise, it should return CS_UNSUPPORTED_EVENT.
Must be OR'ed with CS_CLIENT_INFO_VALID.
Must be set to a driver-private version number.
Must be set to CS_VERSION.
Must be set to the revision date of the PC Card driver, using CS_CLIENT_INFO_MAKE_DATE(day, month, year). day must be the day of the month, month must be the month of the year, and year must be the year, offset from a base of 1980. For example, this field could be set to a revision date of July 4 1997 with CS_CLIENT_INFO_MAKE_DATE(4, 7, 17).
A string describing the PC Card driver should be copied into this space.
A string supplying the name of the PC Card driver vendor should be copied into this space.
A string supplying the name of the PC Card driver will be copied into this space by Card Services after the PC Card driver has successfully processed this event; the driver does not need to initialize this field.
The write protect status of the PC Card in the indicated socket has changed. The current write protect state of the PC Card is in the args->info field:
Card is not write protected.
Card is write protected.
The structure members of event_callback_args_t are:
void *info; /* event-specific information */ void *client_data; /* driver-private data */ client_info_t client_info; /* client information*/
The structure members of client_info_t are:
unit32_t Attributes; /* attributes */ unit32_t Revisions; /* version number */ uint32_t CSLevel; /* Card Services version */ uint32_t RevDate; /* revision date */ char ClientName[CS_CLIENT_INFO_MAX_NAME_LEN]; /*PC Card driver description */ char VendorName[CS_CLIENT_INFO_MAX_NAME_LEN]; /*PC Card driver vendor name */ char DriverName[MODMAXNAMELEN]; /* PC Card driver name */
The event was handled successfully.
Driver does not support this event.
Error occurred while handling this event.
This function is called from high-level interrupt context in the case of high priority events, and from kernel context in the case of low priority events.
static int xx_event(event_t event, int priority, event_callback_args_t *args) { int rval; struct xxx *xxx = args->client_data; client_info_t *info = &args->client_info; switch (event) { case CS_EVENT_REGISTRATION_COMPLETE: ASSERT(priority & CS_EVENT_PRI_LOW); mutex_enter(&xxx->event_mutex); xxx->card_state |= XX_REGISTRATION_COMPLETE; mutex_exit(&xxx->event_mutex); rval = CS_SUCCESS; break; case CS_EVENT_CARD_READY: ASSERT(priority & CS_EVENT_PRI_LOW); rval = xx_card_ready(xxx); mutex_exit(&xxx->event_mutex); break; case CS_EVENT_CARD_INSERTION: ASSERT(priority & CS_EVENT_PRI_LOW); mutex_enter(&xxx->event_mutex); rval = xx_card_insertion(xxx); mutex_exit(&xxx->event_mutex); break; case CS_EVENT_CARD_REMOVAL: if (priority & CS_EVENT_PRI_HIGH) { mutex_enter(&xxx->hi_event_mutex); xxx->card_state &= ~XX_CARD_PRESENT; mutex_exit(&xxx->hi_event_mutex); } else { mutex_enter(&xxx->event_mutex); rval = xx_card_removal(xxx); mutex_exit(&xxx->event_mutex); } break; case CS_EVENT_CLIENT_INFO: ASSERT(priority & CS_EVENT_PRI_LOW); if (GET_CLIENT_INFO_SUBSVC_CS(info->Attributes) == CS_CLIENT_INFO_SUBSVC_CS) { info->Attributes |= CS_CLIENT_INFO_VALID; info->Revision = 4; info->CSLevel = CS_VERSION; info->RevDate = CS_CLIENT_INFO_MAKE_DATE(4, 7, 17); (void)strncpy(info->ClientName, "WhizBang Ultra Zowie PC card driver", CS_CLIENT_INFO_MAX_NAME_LEN) "ACME PC card drivers, Inc.", CS_CLIENT_INFO_MAX_NAME_LEN); rval = CS_SUCCESS; } else { rval = CS_UNSUPPORTED_EVENT; } break; case CS_EVENT_WRITE_PROTECT: ASSERT(priority & CS_EVENT_PRI_LOW); mutex_enter(&xxx->event_mutex); if (args->info == CS_EVENT_WRITE_PROTECT_WPOFF) { xxx->card_state &= ~XX_WRITE_PROTECTED; } else { xxx->card_state |= XX_WRITE_PROTECTED; } mutex_exit(&xxx->event_mutex); rval = CS_SUCCESS; break; default: rval = CS_UNSUPPORTED_EVENT; break; } return (rval); }
csx_Event2Text(9F), csx_RegisterClient(9F), csx_RequestSocketMask(9F)
PC Card 95 Standard, PCMCIA/JEIDA | http://docs.oracle.com/cd/E26502_01/html/E29045/csx-event-handler-9e.html | CC-MAIN-2016-18 | en | refinedweb |
A HUD or any UI components are normally 2D graphics and text displayed on top of the game view. A number of libraries help you to display 2D graphics, for OpenGL there is GLUI and GLUT and for DirectX there is the sprite and font interfaces. To do it yourself the standard way is to create a square made of two triangles defined in screen space (already transformed) and then to texture the square with the 2D graphic you wish to display. Text is normally achieved by creating a texture with all the characters in the font on it and then display a quad on screen for each character and use the texture co-ordinates to reference the correct letter in the font texture. Look at the way it is done in the DirectX SDK samples for an example of this.
Related notes: 2D Elements (Textures, Sprites, Text).
Use vectors. Normalised vectors are great tools. They have a length of 1 so multiplying them by another vector leaves the other vectors size unchanged but alters the direction. If you want to move an object to a particular place you calculate the vector between the two positions, normalise it and add it to the current position.
e.g. If you want to move from position A to position B and both are described with vectors:
D3DXVECTOR3 direction=A - B;D3DXVec3Normalize(&direction,&direction);// to move the object from A you would then do something like:D3DXVECTOR3 newPosition=A + (direction * movementAmount);
Since direction is normalised and has a length of 1 you multiply it by the amount you want the object to move during this calculation , in this case movementAmount.
If you want the camera to follow your character around the world you need to take into account the direction and position of the character to be followed.
You will probably want the camera to be a set distance away from the object and facing the same direction as the object. So the first thing to do is obtain the position and direction of the object. Once you have these you can position the camera a set distance from the object by multiplying the inverse of the object direction vector by the set distance away you want the camera to be:
In code this may look something like:
// objPos - is the position of the object in the world// objDir - is the normalised direction vector of the object in the world// cameraPos and cameraDir are the position and direction of the camera that we want to find// Position the camera 5 world units (dx) away from the object:D3DXVECTOR3 inverseObjDir = -objDir;cameraPos= objPos + (5.0f * inverseObjDir);// Camera direction is just set to the same as the object:cameraDir=objDir;
The above will position the camera at the same height as the object, you may want the camera to always be above the object looking down. In this case you need to raise the camera position up and then calculate a new 'downward facing' camera direction.
To do this you get the vector between the camera position and the object position. This then gives you the correct direction vector.
// We want the camera to be 4 world units above the object it is looking at cameraPos.y+=4.0f; // We have to change the camera direction to look down toward the object D3DXVECTOR3 newDir=objDir-cameraPos; D3DXVec3Normalize(&newDir,&newDir); // now the newDir is the correct camera direction
Relates notes: Camera
Often you need to find out if a point is within a polygon. E.g. when doing collision you may have detected that a ray collides with the plane of a triangle and now you need to determine if the collision point is within the triangle. This is obviously in 2D. The method I have used is from Gems IV. Note: there are a few other methods out there so do a Google if interested - you will find plenty. The description above the code is not mine:
/* The definitive reference is "Point in Polygon Strategies" by Eric Haines [Gems IV] pp. 24-46. outside the jumps will be even. The code below is from Wm. Randolph Franklin <wrf@ecse.rpi.edu> with some minor modifications for speed. It returns 1 for strictly interior points, 0 for strictly exterior, and 0 or 1 for points on the boundary. The boundary behaviour is complex but determined; in particular, for a partition of a region into polygons, each point is "in" exactly one polygon. The code may be further accelerated, at some loss in clarity, by avoiding the central computation when the inequality can be deduced, and by replacing the division by a multiplication for those processors with slow divides. numPoints = number of points poly = array of vectors representing each point x,y = point to test*/bool pnpoly(int numPoints, Vector *poly, float x, float z) { int i, j, c = 0; for (i = 0, j = numPoints-1; i < numPoints; j = i++) { if ((((poly[i].z<=z) && (z<poly[j].z)) || ((poly[j].z<=z) && (z<poly[i].z))) && (x < (poly[j].x - poly[i].x) * (z - poly[i].z) / (poly[j].z - poly[i].z) + poly[i].x)) c = !c; } return (c==1); }
Vector can be your own vector structure / class or D3DXVECTOR3 if you are using DirectX.
There are some issues with different processors relating to timing. Normally timeGetTime works fine on most computers however there are issues on some machines so often QueryPerformanceCounter is used instead. This is a high resolution counter but is not supported on older machines. So the best method is to check if this counter exists, if it does, use it otherwise use timeGetTime. I have a class I use to wrap all this and I have made it available, for reference, via this download: timeUtils.zip. You are advised to create your own so you understand what is going on.
Take a look at this link on Gamasutra which has a number of good articles: Game Physics
Related notes: collisions
Firstly be sure you know what you mean when talking about distance between vectors. Vectors have a direction and a length however vectors are also often used to represent a position only (point vectors). So finding the distance between two vectors normally refers to finding the distance between two points. You can subtract one vector from another and get a new vector but to get the distance between the points you need to determine the length of the new vector.
To find the distance between two points you use the Pythagorus theorem: 'the square on the hypotenuse is equal to the sum of the squares of the other two sides'. So if you have two points P0 and P1 the distance between them is:
float dx=p1.x - p0.xfloat dy=p1.y - p0.y
float distance=sqrt(dx*dx + dy*dy);
Tip: often you just want to compare distances so rather than use the slow sqrt (square root) function you can safely compare the squared distances. It is wise to avoid sqrt where possible in game code.
This used to be a much easier question to answer. In the past I would have said unroll loops (to avoid the loop code overhead), create look up tables for sin, cos, tan etc. (these functions can be slow) plus many other nice tricks. However nowadays with the complexity of modern processors these methods are no longer always correct. PC processors like the Pentium are now better at handling loops and maths functions are very fast compared to what they were. You also have the issue of the graphics card working in parallel to the CPU, you want to try to maximise that parallel effect so neither processor is waiting for the other. On consoles the situation is the same and in some cases worse. The PS2 has two vector units that need to be kept busy in order to maintain high speed.
So nowadays you need really to look at your algorithm for increased speed rather than low level coding tricks. Most importantly you should profile the code to see where the slow points are. Often programmers are wrong about the place they think is slowing the code down and only when you run a profiler can you determine exactly where slow downs occur. You don't even need to buy a profiler you can use your own code to measure the time sections of code take. Of course the best way to optimise slow code is to not call it at all! If you can remove code by redesigning an algorithm this is the biggest gain.
I wrote a program not long ago which was spending ages creating shadows on a terrain. I profiled it so I knew exactly where the problem was and I worked at it for many days reducing the speed by 0.5 % at a time until after a week or two I had reduced it by about 5%. A few weeks later I suddenly realised I could change the algorithm used and use a completely different one which would be quicker, it took a few hours to change but did the same job as before but ran 500% faster! All that time I spent optimising for a few meagre percent would have been better spent redesigning the algorithm.
So my general suggestions for optimising slow code is:
If you get to the final step and really have to look at the code there are a few things to bear in mind:
There are more things you can do but basically the key is to make sure you know where the slow down is and then see if you can change the whole algorithm rather than resort to code level tricks.
The area of a 3D triangle defined by the vertex V0, V1, V2 is half the magnitude of the cross product of the two edge vectors:
0.5 * | V0V1 * V0V2 |
Why would you want to know this? Well it is useful if you want to calculate your Gouraud normals so large connecting triangles have more effect on the normal than the smaller ones. The standard way to calculate a Gouraud normal is to add up all the plane normals of the connecting triangles and divide by how many there were. This works fine in most cases but does not differentiate between large and small triangles - each is equally weighted. You often get a better effect by modifying the influence of each triangle to the normal based on its size.
Easy. 2PI radians = 360 degrees, or PI radians = 180 degrees. So 1 radian is 0.017453The best thing is to set up a macro to do the conversions e.g.
#define PI (3.141592654f)#define DEGTORAD(degree) ((PI / 180.0f) * (degree))#define RADTODEG(radian) ((180.0f /PI) * (radian)) | http://www.toymaker.info/Games/html/techniques.html | CC-MAIN-2016-18 | en | refinedweb |
.
Peter Soetens <peter.soetens at fmtc [dot] be> changed:
What |Removed |Added
--------------------------------------------------------------------------
Status|NEW |ASSIGNED
AssignedTo|orocos- |peter.soetens@fmtc.be
|dev@lists.mech.kuleuven.be |
--- Comment #1 from Peter Soetens <peter.soetens at fmtc [dot] be> 2008-03-17 10:51:49 ---
Created an attachment (id=252)
--> ()
removes the template parameter from RTT classes.
This patch removes the template parameter and assumes that 'int' is used to
read/write to channels.
Only the resolution is an unsigned int, all the other functions use 'int'.
This patch does not fix the OCL Comedi classes.
--- Comment #2 from Peter Soetens <peter.soetens at fmtc [dot] be> 2008-04-20 00:00:42 ---
Created an attachment (id=263)
--> ()
Adapts OCL's AnalogIn/Out use to template-less RTT implementation
This patch fixes all ocl/hardware classes for using the new RTT API.
The template parameter has been dropped. The comedi implementations are
now far more efficient (caching range settings etc.).
What |Removed |Added
--------------------------------------------------------------------------
Attachment #252 is|0 |1
obsolete| |
--- Comment #3 from Peter Soetens <peter.soetens at fmtc [dot] be> 2008-04-20 00:02:14 ---
Created an attachment (id=264)
--> ()
Improved the RTT API as well.
Same as previous RTT patch but the API is overall better. Some methods
(read,write,...) have been deprecated and have been
given a new name (value, rawValue,...). The OCL patch works with this one.
Any objections ?
--- Comment #4 from Klaas Gadeyne <klaas.gadeyne at fmtc [dot] be> 2008-04-21 11:59:04 ---
(In reply to comment #3)
> Created an attachment (id=264)
--> () [details]
> Improved the RTT API as well.
>
> Same as previous RTT patch but the API is overall better. Some methods
> (read,write,...) have been deprecated and have been
> given a new name (value, rawValue,...). The OCL patch works with this one.
>
> Any objections ?
None. The new names are an improvement (although I would maybe prefer
avoid confusion between read/write inputs, but that's probably a matter of
taste), and backwards compatibility seems guaranteed with this patch.
Some small remarks (the whitespace fixes make it hard to read your patch though
:-(
Index: src/dev/AnalogInput.hpp
/**
* Read the raw value of this channel.
*/
- InputType rawValue() const
+ int rawValue() const
{
- InputType r;
- board->read(channel, r);
+ unsigned int r;
+ board->rawValue(channel, r);
return r;
}
Shouldn't the return type of this function be "unsigned int" too?
Similar remark for the rawValue of AnalogOutput.hpp
Furthermore, some methods now have a void return type, while a "real" return
value would make sense, e.g.
/**
* Write the raw value of this channel.
*/
- void rawValue(OutputType i)
+ void rawValue(int i)
{
- if ( i < board->binaryLowest(channel ) )
- i_cache = board->binaryLowest( channel );
- else if ( i > board->binaryHighest( channel ) )
- i_cache = board->binaryHighest( channel ) ;
- else
- i_cache = i;
- board->write(channel, i);
+ board->rawValue(channel, i);
}
where the last line does permit return values. From a first (and probably too
fast) test, it seems such void2type return modifications are even ABI
compatible?
What |Removed |Added
--------------------------------------------------------------------------
Attachment #264 is|0 |1
obsolete| |
--- Comment #5 from Peter Soetens <peter.soetens at fmtc [dot] be> 2008-04-29 23:03:08 ---
Created an attachment (id=270)
--> ()
user read/write again at Analog*Interface level + fix return values as well
This patch solves the issues pointed at by Klaas.
The return values are now 'int' (to indicate success/failure) in case of the
Analog*Interface classes and the value() names have been replaced by the
read/write equivalents again to be more clear.
AnalogInInterface and AnalogOutInterface are compatible (again) when you wish
to inherit from both classes.
The patch is not ABI compatible.
What |Removed |Added
--------------------------------------------------------------------------
Attachment #263 is|0 |1
obsolete| |
--- Comment #6 from Peter Soetens <peter.soetens at fmtc [dot] be> 2008-04-29 23:06:42 ---
Created an attachment (id=271)
--> ()
Adapt to cleanup3 from RTT.
This patch adapts to the final new Analog* API and also places Comedi in the
OCL namespace.
What |Removed |Added
--------------------------------------------------------------------------
Target Milestone|--- |1.6.0
--- Comment #7 from Peter Soetens <peter.soetens at fmtc [dot] be> 2008-04-29 23:29:37 ---
Applied on trunk/rtt:
$ svn ci -m"Fix bug #488: AnalogIn/OutInterface is an atrocity.
> Applied analog-interface-cleanup3.patch
> "
Sending rtt/src/dev/AnalogInInterface.hpp
Sending rtt/src/dev/AnalogInput.hpp
Sending rtt/src/dev/AnalogOutInterface.hpp
Sending rtt/src/dev/AnalogOutput.hpp
Sending rtt/src/dev/io.cpp
Sending rtt/tests/FakeAnalogDevice.hpp
Sending rtt/tests/dev_test.cpp
Transmitting file data .......
Committed revision 29219.
And on trunk/ocl:
$ svn ci hardware/ -m"Fix bug #488: AnalogIn/OutInterface is an atrocity.
All OCL hardware components are adapted (and compile tested).
> "
Sending hardware/axes/dev/AnalogDrive.hpp
Sending hardware/axes/dev/AnalogSensor.hpp
Sending hardware/comedi/dev/ComediDevice.cpp
Sending hardware/comedi/dev/ComediDevice.hpp
Sending hardware/comedi/dev/ComediEncoder.cpp
Sending hardware/comedi/dev/ComediEncoder.hpp
Sending hardware/comedi/dev/ComediPulseTrainGenerator.cpp
Sending hardware/comedi/dev/ComediPulseTrainGenerator.hpp
Sending hardware/comedi/dev/ComediSubDeviceAIn.cpp
Sending hardware/comedi/dev/ComediSubDeviceAIn.hpp
Sending hardware/comedi/dev/ComediSubDeviceAOut.cpp
Sending hardware/comedi/dev/ComediSubDeviceAOut.hpp
Sending hardware/comedi/dev/ComediSubDeviceDIn.cpp
Sending hardware/comedi/dev/ComediSubDeviceDIn.hpp
Sending hardware/comedi/dev/ComediSubDeviceDOut.cpp
Sending hardware/comedi/dev/ComediSubDeviceDOut.hpp
Sending hardware/comedi/dev/ComediThreadScope.hpp
Sending hardware/comedi/dev/comedi_internal.h
Sending hardware/ethercat-demo/EthercatDemonAxesVelocityController.cpp
Sending hardware/ethercat-demo/EthercatDemonAxesVelocityController.hpp
Sending hardware/ethercat-demo/EthercatIO.hpp
Sending hardware/ethercat-demo/dev/AnalogEtherCATInputDevice.hpp
Sending hardware/ethercat-demo/dev/AnalogEtherCATOutputDevice.hpp
Sending hardware/io/IOComponent.hpp
Sending hardware/io/dev/FakeAnalogDevice.hpp
Sending hardware/kuka/Kuka160nAxesVelocityController.cpp
Sending hardware/kuka/Kuka160nAxesVelocityController.hpp
Sending hardware/kuka/Kuka361nAxesTorqueController.cpp
Sending hardware/kuka/Kuka361nAxesTorqueController.hpp
Sending hardware/kuka/Kuka361nAxesVelocityController.cpp
Sending hardware/kuka/Kuka361nAxesVelocityController.hpp
Sending hardware/laserdistance/LaserDistance.cpp
Sending hardware/laserdistance/LaserDistance.hpp
Sending hardware/lias/CRSnAxesVelocityController.cpp
Sending hardware/lias/CRSnAxesVelocityController.hpp
Sending hardware/lias/IP_FastDAC_AOutInterface.cpp
Sending hardware/lias/IP_FastDAC_AOutInterface.hpp
Sending hardware/performer_mk2/PerformernAxesVelocityController.cpp
Sending hardware/performer_mk2/PerformernAxesVelocityController.hpp
Sending hardware/staubli/StaubliRX130nAxesVelocityController.cpp
Sending hardware/staubli/StaubliRX130nAxesVelocityController.hpp
Sending hardware/xyPlatform/xyPlatformAxisHardware.cpp
Sending hardware/xyPlatform/xyPlatformAxisHardware.hpp
Transmitting file data ...........................................
Committed revision 29222.
--- Comment #8 from Peter Soetens <peter.soetens at fmtc [dot] be> 2008-05-04 22:18:00 ---
Created an attachment (id=272)
--> ()
Make analog interface raw type signed
After much [some mental process], I've changed the 'raw' type of the analog
interfaces to 'int' instead of 'unsigned int'. This allows in practice 32bits
signed AD converters and 31bits unsigned AD converters (only returns positive
numbers). This change was done to support two's complement AD converters as
well. In case your 'unsigned' AD converter has 32bits (does that exist?) your
implementation needs to offset it to a signed raw representation. I'm sure I'm
not bullying anyone with this... but you're free to correct me if I'm wrong.
This patch is for RTT (in addition to patch 270)
Peter
--- Comment #9 from Peter Soetens <peter.soetens at fmtc [dot] be> 2008-05-04 22:18:44 ---
Created an attachment (id=273)
--> ()
Updates OCL for signed raw types.
Patch for OCL in addition to patch 271.
--- Comment #10 from Peter Soetens <peter.soetens at fmtc [dot] be> 2008-05-04 22:20:15 ---
Applied on trunk.
$ svn ci rtt/src/ rtt/tests/ -m"Applying patch for bug #488:
AnalogIn/OutInterface is an atrocity.
> Make analog interface raw type signed
> "
Sending rtt/src/dev/AnalogInInterface.hpp
Sending rtt/src/dev/AnalogInput.hpp
Sending rtt/src/dev/AnalogOutInterface.hpp
Sending rtt/src/dev/AnalogOutput.hpp
Sending rtt/src/dev/AxisInterface.hpp
Sending rtt/tests/FakeAnalogDevice.hpp
Transmitting file data ......
Committed revision 29223.
+ sspr@lt00129:~/src/Orocos/trunk
$ svn ci ocl -m"Applying patch for bug #488: AnalogIn/OutInterface is an
atrocity.
> Updates OCL for signed raw types.
> "
Sending ocl/hardware/comedi/dev/ComediSubDeviceAIn.cpp
Sending ocl/hardware/comedi/dev/ComediSubDeviceAIn.hpp
Sending ocl/hardware/comedi/dev/ComediSubDeviceAOut.cpp
Sending ocl/hardware/comedi/dev/ComediSubDeviceAOut.hpp
Transmitting file data ....
Committed revision 29224. | http://www.orocos.org/node/533 | crawl-001 | en | refinedweb |
Before you can use the NetConnection Debugger, you must add a single line of ActionScript to your application (see Figure 5.12). This single line of code adds the required class files to your Flash application to enable the NetConnection Debugger.
To add the class files, follow these steps in the Flash MX authoring environment:
Open your Communication application (myFirstApp.fla) in the Flash MX authoring environment.
Open the Actions panel by selecting Window, Actions (or press F9).
Turn the Actions panel into Expert mode by pressing Ctrl+Shift+E. This allows you to manually add the line of script to your application.
Click the First Frame in the first layer of your movie (or a specified Actions layer that you may have set up) and enter the following line of code in the Actions panel:
#include "NetDebug.as";
Open the NetConnection Debugger in Flash MX by selecting Window, NetConnectionDebugger.
Test your communications movie in Flash MX by selecting Control, Test Movie or pressing Ctrl+Enter.
When the movie runs, the NetConnection Debugger begins to display numerous events on the left side of the panel. This is the Flash player communicating with the server.
The NetDebug.as file was installed in the \Macromedia\Flash MX\Configuration\Include\folder. Any files placed in this folder can be included into Flash MX without specifying a directory path. When engaged, the NetConnection Debugger monitors any AMF activity on your computer. This is helpful if you need to watch exchanges between two Flash players open outside Flash MX (including applications running within a web browser).
Take a moment and scroll through the list of events. The debugger is not interactive, meaning that you cannot affect your movie with anything you do in this panel. To view expanded details, click the Details tab on the right side. Figure 5.13 displays detail of the first Communication Server event, Connect, originating from the Flash player.
Warning
Tracking problems you might have in your code, or trying to sort out unusual server behaviors, will be easier with this tool. The NetDebug class files are not required and should be commented out when you are ready to deploy your application to a production server. The file will add unnecessary file size to your SWF movie. | http://etutorials.org/Macromedia/Macromedia+Flash+Communication+Server+MX/Part+I+10+Quick+Steps+for+Getting+Started/Chapter+5.+STEP+5+Monitoring+and+Managing+the+Server/Developer+Component+NetConnection+Debugger/ | crawl-001 | en | refinedweb |
#include <algorithm>
int lexicographical_compare_3way( iterator start1, iterator end1, iterator start2, iterator end2 );
The lexicographical_compare_3way() function compares the first
range, defined by [start1,end1) to the second
range, defined by [start2,end2).
If the first range is lexicographically less than the second
range, this function returns a negative number. If the first range is
lexicographically greater than the second, a positive number is
returned. Zero is returned if neither range is lexicographically
greater than the other.
lexicographical_compare_3way() runs in linear time. | http://www.cppreference.com/cppalgorithm/lexicographical_compare_3.html | crawl-001 | en | refinedweb |
This document describes how to use XmlSerializer that is part of XmlPull API to generate/write/serialize XML (If you want to do XML parsing read quick introduction to XML pull parsing)
XmlSerializer provides:
Before running sample code make sure to have parser that implements XmlPull API 1.1.x (read relevant part from Quick Introduction)
All XML generating can be done by using XmlSerializer interface. However before we can start writing we need to obtain instance of class that implements this interface.
XmlPull API allows multiple implementations to be used. To achieve this flexibility serializer class is not created directly but by using configurable factory that is responsible for locating and creating implementation. In general that involves following steps:
import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlPullParserFactory; import org.xmlpull.v1.XmlSerializer;and the code to create serializer may look like this:
XmlPullParserFactory factory = XmlPullParserFactory.newInstance( System.getProperty(XmlPullParserFactory.PROPERTY_NAME), null); XmlSerializer serializer = factory.newSerializer();Next step is to set serializer output - in this case it is set to write to standard output but can easily redirected to file or socket:
serializer.setOutput(new PrintWriter( System.out ));and now we can start using
serializerto write XML!
Typical applicaition will write XML declaration and then follow with writing few element start and end tags and their content.
Output must always have at least one start tag:
serializer.startTag(NAMESPACE, "poem");then we cna start writing more start tags, text cotnent, and end tags:
serializer.startTag(NAMESPACE, "title"); serializer.text("Roses are Red"); serializer.endTag(NAMESPACE, "title");where namespace is declared as string constant
private final static String NAMESPACE = "";
it is possible to chain multiple calls:
serializer.startTag(NAMESPACE, "l") .text("Roses are red,") .endTag(NAMESPACE, "l");or put them even in one line:
serializer.startTag(NAMESPACE, "l").text("Violets are blue;").endTag(NAMESPACE, "l");but what make API really flexible and modular is to define functions that outputs well defined parts of XML, for example:
private static void writeLine(XmlSerializer serializer, String line, boolean addNewLine) throws IOException { serializer.startTag(NAMESPACE, "l"); serializer.text(line); serializer.endTag(NAMESPACE, "l"); if(addNewLine) serializer.text("\n"); }and then to write chunkof XML output it is enough to simply call:
writeLine(serializer, "Sugar is sweet,", addNewLine); writeLine(serializer, "And I love you.,", addNewLine);
Serializer will check that end tag name and namespace is the same as of matching start tag (very good to validate that XML output is correct) so to finish writing XML we should close top level start tag:
serializer.endTag(NAMESPACE, "poem");
It is important to inform serializer when XML output is finished so any remianing buffered XML output is send to putput stream and serializer will not allow any more input to do this call endDocument():
serializer.endDocument();
serializer.setPrefix("ns", NAMESPACE);or what namespace should be bound as default namespace (to special empty string prefix):
serializer.setPrefix("", NAMESPACE);
Prefix declaration must be done just before call to start tag and the prefix declaration scope starts on this star tag and finishes when corresponding end tag is reached.
XmlSerializer allows to create any infoset so it is possible to add manually new lines or indentation. for exmaple if would like to have new line after every end tag it is as easy as to call text() with new line:
if(addNewLine) serializer.text("\n");
If serializer supports optional formatting properties and features then they can be used to have output indented automatically. Read more about them:
The finished working sample created that was described is in MyXmlWriteApp.java file in src/java/samples directory.
For more information about XmlPull API please visit.
When new lines are added manually:
java MyXmlWriteApp -n serializer implementation class is class org.kxml2.io.KXmlSerializer <?xml version="1.0"?> <poem xmlns=""> <title>Roses are Red</title> <l>Roses are red,</l> <l>Violets are blue;</l> <l>Sugar is sweet,</l> <l>And I love you.,</l> </poem>
When using one of optional formatting properties to set indentation:
java MyXmlWriteApp -i 4 serializer implementation class is class org.xmlpull.mxp1_serializer.MXSerializer <?xml version="1.0"?> <poem xmlns=""> <title>Roses are Red</title> <l>Roses are red,</l> <l>Violets are blue;</l> <l>Sugar is sweet,</l> <l>And I love you.,</l> </poem> | http://xmlpull.org/v1/download/unpacked/doc/quick_write.html | crawl-001 | en | refinedweb |
The first thing you need to do is to add a participant to your repository (usually rep/participants.xml). Basically this will look like this:
<participant name="scheduler" param="rep/scheduler.xml">ParticipantMemoryScheduler</participant>
Afterwards you have to actually write the scheduler.xml file you referenced above. Again I'll explain this by example:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE scheduler SYSTEM "/dtd/scheduler.dtd">
<scheduler>
<task classname="com.uwyn.rife.mail.executors.DatabaseMailQueueExecutor" frequency="*/5 * * * *">
<option name="datasource"><config param="DATASOURCE"/></option>
<option name="smtp_server"><config param="SMTP_SERVER"/></option>
</task>
<task classname="com.uwyn.rife.search.executors.IndexQueueExecutor" frequency="*/5 * * * *"/>
</scheduler>
This is the scheduler as used by the Bamboo project. So, what does it do?
As you can see, it basically defines a list of tasks. Each task definition consists of the following components:
Now that you've decided how many tasks you have and when they should be executed, there's only one more thing left: You need to define what they are supposed to do. This is done by implementing so called Executors.
There are basically two examples of Executors you can refer to:
Let's start building our first Executor.
First we need to define a class that inherits from com.uwyn.rife.scheduler.Executor:
package com.example;
import com.uwyn.rife.scheduler.Executor;
public class MyTestExecutor extends Executor
{}
Now we have to implement the following method, returing the name of the task:
public String getHandledTasktype() {
return "MyTask";
}
Next thing is we add a method called executeTask() to our Executor which takes one argument of type com.uwyn.rife.scheduler.Task and returns a Boolean value.
public boolean executeTask(Task task)
{
return true;
}
At this point, you should take a look at the Task class (JavaDoc). It's mostly used to get the values for the options we defined above. Here's an example of how that might look:
String datasource_name = null;
try
{
datasource_name = task.getTaskoptionValue("datasource_name");
}
catch (SchedulerException e)
{
Logger.getLogger("com.uwyn.rife.search.executors").severe(ExceptionUtils.getExceptionStackTrace(e));
datasource_name = null;
}
Another thing that you can use the Task object for is to get the frequency as defined in the scheduler.xml file and even more interesting, when the next execution will take place. Take a look:
String freq;
long nextExecution;
freq = task.getFrequency();
nextExecution = task.getPlanned();
That's it, now you're ready to go and write your own Executors. | http://rifers.org/wiki/display/RIFE/Scheduler | crawl-001 | en | refinedweb |
got administrative rights and want to do
it yourself, you can use the
Code Access Security Policy Tool (Caspol.exe)
that ships with the .NET framework (helpful instructions can be found
here and
here).
Ext/Icons
No, this is not possible. In order to edit attachments, you need to save them to a
(temporary) file, edit it using an external application, import it back to KeePass as
attachment, and finally delete the temporary file.
There will no feature be implemented that automates these steps, because of security
problems. To see the problems, let's assume that KeePass would support editing attachments.
When you click a button, KeePass would save the attachment to a file and open it using
its associated external application. When the external application is closed, KeePass would
import the temporary file and delete it securely. But what happens when KeePass is closed
before the external application? KeePass cannot delete the file because it's eventually
locked by the external application. Theoretically KeePass could tell the user this fact
before closing, but what to do when the computer shuts down? Here, there's no time left to
ask the user what to do. The temporary file would have been leaked, i.e. left unencryptedly
on disk, which is obviously very bad.
One could argue that the leakage would only be temporary: at the next start, KeePass
could scan the temporary directory for remaining files and delete them. Anyway, the
files would be freely accessible (unencrypted) by all other applications during a complete
computer shutdown and boot process. If you don't start KeePass on this computer ever again,
the file is leaked forever. As KeePass is designed to be portable, i.e. may be securely
used on many computers, this temporary leakage is unacceptable.
KeeMiniMode=True
KeePass.ini automatically tries to lock its workspace when Windows is locked, with one
exception: when a KeePass sub-dialog (like the 'Edit Entry' window) is currently opened,
the workspace is not locked.
To understand why this behavior makes sense, it is first important to know what happens
when the workspace is locked. When locking, KeePass completely closes the database
and only remembers several view parameters, like the last selected group, the top visible
entry, selected entries, etc. From a security point of view, this achieves best
security possible: breaking a locked workspace is equal to breaking the database itself.
Now back to the original question. Let's assume an edit dialog is open and the
workstation locks. What should KeePass do now? Obviously, it's too late to ask the user
what to do (the workstation is locked already and no window can't be displayed),
consequently KeePass must make an automatic decision. There are several possibilities:
Obviously, none of these alternatives is satisfactory. Therefore, KeePass implements the
following simple and easy to understand behavior:
When Windows is locked and a KeePass sub-dialog is opened, the KeePass workspace
is not locked.
This simple concept avoids all the problems above. The user is responsible for the
state of the program.
Security consequence: the database is left open when Windows locks. Does this matter?
Normally, you are the only one who can log back in to Windows. When someone else logs in
(like administrator), he can't use your programs anyway. By default, KeePass keeps
in-memory passwords encrypted, therefore it does not matter if Windows caches the process
to disk at some time. So, your passwords are pretty safe anyway.
KeePass creates a temporary HTML file when printing password lists and showing
print previews. This file is securely erased (i.e. overwritten multiple times
before being removed from the file system tree). | http://www.keepass.info/help/base/faq_tech.html | crawl-001 | en | refinedweb |
TweenMax (AS3) - TweenLite on Steroids
- Compatibility: Flash Player 9 and later (ActionScript 3.0) (Click here for the AS2 Version | Speed Comparison | Bezier Speed Comparison
FEATURE COMPARISON
USAGE
- Description: Tweens the target's properties from whatever they are at the time you call the method to whatever you define in the variables parameter.
- Parameters:
- target : Object - Target object whose properties we're tweening
- duration : Number - Duration (in seconds) of the tween
- variables : Object - An object containing the end values of all the properties you'd like to have tweened (or if you're using the Tween.easing.Elastic.easeOut. The Default is Regular.easeOut.
-.
- volume : Number - To change a MovieClip's or SoundChannel's volume, just set this to the value you'd like the MovieClip/SoundChannel to end up at (or begin at if you're using TweenMax.from()).
- tint : Number - To change a DisplayObject's tint/color, set this to the hex value of the tint you'd like the MovieClip to end up at(or begin at if you're using TweenMax.from()). An example hex value would be 0xFF0000. If you'd like to remove the color from a DisplayObject, just pass null as the value of tint.
- frame : Number - Use this to tween a MovieClip to a particular frame.
- bezier : Array - Bezier tweening allows you to tween in a non-linear way. For example, you may want to tween a DisplayObject.
-)
- renderOnStart : Boolean - If you're using TweenMax.from() with a delay and want to prevent the tween from rendering until it actually begins, set this special property to true. By default, it's false which causes TweenMax.from() to render its values immediately, even before the delay has expired.
- overwrite : Boolean - If you do NOT want the tween to automatically overwrite any other tweens that are affecting the same target, make sure this value is false.
-
- Description: Exactly the same as Tween).
-/MovieClip. You can optionally force it to immediately complete (which will also call the onComplete function if you defined one)
- Parameters:
- target : Object - Any/All tweens of this Object will be killed.
- complete : Boolean - If true, the tweens for this object will immediately complete (go to the ending values and call the onComplete function if you defined one).
- Description: Provides an easy way to kill all delayed calls to a particular function (ones that were instantiated using the TweenMax:0.5}, {time:1, y:300}]);
- import gs.TweenMax;
- import fl.motion.easing.Back;
- TweenMax.to(clip_mc, 5, {alpha:0.5, x:120, ease:Back.easeOut,Max;
- import fl.motion.easing.Elastic;
- TweenMax.from(clip_mc, 5, {y:"-100", ease:Elastic.easeOut});
-MaxMax:
- myButton.addEventListener(MouseEvent.MOUSE_OVER, onMouseOver);
- myButton.addEventListener(MouseEvent.MOUSE_OUT, onMouseOut);
- var scaleTween:TweenMax;
- TweenMax.from(myButton, 2, {alpha:0, overwrite:false});
- function onMouseOver($e:MouseEvent):void {
- TweenMax.removeTween(scaleTween);
- scaleTween = TweenMax.to(myButton, 0.5, {scaleX:1.2, scaleY:1.2, overwrite:false});
- }
- function onMouseOut($e:MouseEvent):void {
- TweenMax.removeTween(scaleTween);
- scaleTween = TweenMax.to(myButton, 0.5, {scaleX:1, scaleY:1,;
- Why aren't my filters working?
If you're using a filter that has an alpha property, try setting it to 1. The default alpha value is zero, so the filter may be working just fine, but you're not seeing it.
is free. You're welcome to use it for commercial purposes - I only ask that you donate what you think the class is worth in your project(s), and consider joining Club GreenSock which gives you some bonus classes, updates, and more. If you want to use one (or more) of my classes in your commerical software product which would entail distributing the class files, please get my permission first by e-mailing me at jack -at- greensock.com.
Need Help?
Feel free to e-mail me a question..
on April 6th, 2008 at 12:13 pm
Thank you sooooooooo much!!!
That is simply “perfect” ;)
on April 6th, 2008 at 5:02 pm
I’m glad with this release! Thank you very much Jack! :)
pd: bezierThrough is pretty cool, great idea (I never like the bezier system)
on April 7th, 2008 at 5:46 am
Great release - thank you! :) I especially like the new tween sequencing options which will save me a lot of time having to test delay and tween numbers and see which combination fits! Love the pause/resume too. I’ve used TweenLite in all my games to date, and this will replace it without hesitation.
on April 7th, 2008 at 6:51 pm
It’s amazing. Thanks a lot for your work. :-)
on April 8th, 2008 at 3:29 am
Hi Jack,
First of all thanks for this great tweening engine!
Just a notice to anyone who is experiencing problems tweening a “frame” property:
I just upgraded from Tweenlite v 5.87 to the latest Version (6.1) and i found out that it didn’t work anymore.
The problem was that i use TweenLite to tween a setter/getter called “frame” which TweenLite seems to work with internally on the target since version 6.
Best regards,
Thomas
on April 8th, 2008 at 7:53 am
Thanks! These classes are awesome! They have become an invaluable part of my AS3 coding arsenal . . . finding uses in almost every project on which I’m working. I made a donation today to support your work and encourage others to do the same.
on April 8th, 2008 at 1:46 pm
Nice job Jack! Very impressive!
on April 8th, 2008 at 5:03 pm
Unbelievable , great , beautiful work !!
Thank you Jack !! it is what we were waiting for !!
on April 8th, 2008 at 6:10 pm
Absolutely brilliant, Jack.
Much thanks =)
on April 8th, 2008 at 6:15 pm
Absolutely incredible. Thank you so much for all your releases. TweenLite especially has been magical, even in 3D.
on April 8th, 2008 at 9:31 pm
i don’t know what to say…
this is just too good to be true.
thank u so much, jack!
on April 8th, 2008 at 10:12 pm
Thank you so much for all of your hard work and for freely releasing TweenLite, it’s been a tremendous tool for me while learning and advancing my understanding of actionscript! :)
on April 8th, 2008 at 10:38 pm
This is really great. I really like the feature of tweening through beizer points.
on April 9th, 2008 at 12:40 am
Man…. you are THE MAN!
I love your work and as always… its very impressive…. I’ve been tweening with tweenlite like crazy…. but now… its MAX-crazy time!
keep up the great work…
by the way… I love combining your tween engine with my new hobby (Papervision3d)… they work awsome together.
on April 9th, 2008 at 8:23 am
Awsome! I was fidling around, and guess what… bezier tweening is not just for position objects! you can bezier tween anything (i guess) as long as there are two pair of properties of an object. The two below tweens do the same thing.
// there are two children on the stage called mmO and wwO
import gs.TweenMax
import fl.motion.easing.*
var mm=1
var zz=100
var ww=1
mmO.x=wwO.x=mm
mmO.y=wwO.y=zz
TweenMax.to(wwO,2,{x:100,y:100,bezier:[{x:250,y:250}],ease:Linear.easeIn,onUpdate:tr})
TweenMax.to(this,2,{mm:100,zz:100,bezier:[{mm:250,zz:250}],ease:Linear.easeIn,onUpdate:tr})
function tr () {
mmO.x=mm+10
mmO.y=zz+10
}
on April 9th, 2008 at 11:01 am
Have I overlooked any .fla source files that will show usage for things like sequencing with an array, tweening filter properties, etc. other than the ones above? Thanks!
on April 9th, 2008 at 2:29 pm
I’m so glad you brought that up, Stephanie. I just updated the samples that come with TweenMax so that you can see how to tween filters, basic properties, etc. There are now 4 FLA files included in the download.
on April 10th, 2008 at 9:25 am
Hey Jack,
Amazing work. Can’t wait to take the new code for a spin. I’m definitely sending out some donation love your way.
Quick question. Are the filesizes that you quote for each of the libraries cumulative? In other words, if I use TweenMax is it 8k or 17k (8k + 6k + 3k)?
on April 10th, 2008 at 9:35 am
Great question, Paul. The filesizes are TOTAL, not cumulative. So TweenMax combines TweenLite (3k) with TweenFilterLite (another 3k) with some new stuff (2k), adding up to a TOTAL of 8k.
on April 10th, 2008 at 4:46 pm
Omg, you are the god of Tween ^^
Very nice work :) TweenMax its very impressive.
on April 11th, 2008 at 3:11 pm
I agree with everyone else. TweenMax is the absolute greatest - now that it consolidates the other 2 engines, and still VERY small size. As a designer / flash developer, i highly recommend this to everyone! Thank you for all of your hard work. Keep it up!
on April 18th, 2008 at 10:41 pm
I’d like to praise you for THE greateste piece of programming I’ve seen in ActionScript… Small, fast, reliable… What else? ;)
on April 24th, 2008 at 12:01 pm
Again, you rock brother — TweenMax is a God send and just in the nick-o-time especially with the BezierTo and OrientToBezier funcs — fantastic, I’m already use this on Pro Projects right now — and yes I will donate as soon as I can paid from the client :) You deserve it, seriously.
ROCK ON! Ozzy
on April 24th, 2008 at 11:54 pm
TweenMax is awesome!
I made a nifty looping slideshow with crossfades:
import gs.TweenMax;
import fl.motion.easing.*
TweenMax.allTo([mc1, mc2, mc3, mc4], 0, {autoAlpha:0, onCompleteAll:loop, overwrite:false});
function loop(): void{
TweenMax.allTo([mc1, mc2, mc3, mc4], 3, {autoAlpha:1, delayIncrement:3, onCompleteAll:loop, ease:Linear.easeOut, overwrite:false});
TweenMax.allTo([mc1, mc2, mc3, mc4], 1, {autoAlpha:0, delay:3, delayIncrement:3, ease:Linear.easeOut, overwrite:false});
}
on May 5th, 2008 at 3:58 am
Very amazing tweening engine. I replaced it with the Adobe tween class in my current project, and well.. Tweens where smooth again :). I’m going to develop futher with it, hoping to find the perfect tween engine in this.
Keep on the good work! | http://blog.greensock.com/tweenmaxas3/ | crawl-001 | en | refinedweb |
Writing Extensions from Metamod:Source Plugins
From AMWiki
SourceMod's "External Extensions" feature lets developers implement an extension simply by passing in an object instance, rather than implementing a full library file. This is typically done from Metamod:Source plugins which wish to:
- Enable optional, third party extensibility via SourceMod's scripting layer.
- For whatever reason, do not want to move their "standalone" plugin to a full SourceMod extension.
- Or any of the above, such that new features are added in the presence of SourceMod, but the plugin does not require SourceMod to be present.
[edit] Overview
Attaching to SourceMod will be fairly easy for any developer who has authored a Metamod:Source plugin. However, unlike Metamod:Source, SourceMod has fairly stricter design standards and a much richer API set. It is unacceptable to not account for details such as unloading, and special attention must be taken care to free and manage SourceMod resources properly. Remember crashes or Handle leaks will affect all of SourceMod's loaded plugins/extensions, instead of just your plugin.
The general steps are:
- Implement the IExtensionInterface interface, from public/IExtensionSys.h.
- In ISmmPlugin::AllPluginsLoaded(), perform the attach if possible.
- Detect SourceMod loads in IMetamodListener::OnMetamodQuery().
- Store global pointers once bound, such as the self-referencing IExtension *.
- On ISmmPlugin::Unload(), detach from SourceMod.
Note that SourceMod requires each extension to have a unique name. This is not necessarily a file name, although usually it resembles one. This name is to used, in conjunction with include files, to make sure plugin requirements are met when they load.
[edit] Detailed Steps
The information below is for a more detailed overview. The sample SDK provides a full implementation that is recommended over simply copying and pasting the sample code provided here. The sample SDK is explained further on.
[edit] Implementing the Extension
Implementing the actual Extension itself means simply inheriting the IExtensionInterface class as noted earlier. For example:
class MyExtension : public IExtensionInterface { public: virtual bool OnExtensionLoad(IExtension *me, IShareSys *sys, char *error, size_t maxlength, bool late); virtual void OnExtensionUnload(); virtual void OnExtensionsAllLoaded(); virtual void OnExtensionPauseChange(bool pause); virtual bool QueryRunning(char *error, size_t maxlength); virtual bool IsMetamodExtension(); virtual const char *GetExtensionName(); virtual const char *GetExtensionURL(); virtual const char *GetExtensionTag(); virtual const char *GetExtensionAuthor(); virtual const char *GetExtensionVerString(); virtual const char *GetExtensionDescription(); virtual const char *GetExtensionDateString(); };
Most functions are self explanatory. A few important notes:
- OnExtensionLoad is used to provide essential interfaces: IShareSys (acquires/shares objects in the SourceMod heirarchy), and IExtension (self-referencing pointer used for identification and unloading).
- OnExtensionLoad is also used to query for any extra interfaces that the extension requires. For example, if the Handle System is needed, it would be queried and its pointer cached. If it couldn't be found, then OnExtensionLoad would return false to deny loading.
- OnExtensionUnload() is used to free resources. If a resource (interface) is being used from another extension, and that extension is unloaded, separate cases must be taken care of because of dynamic unloadability. These (unusual) cases are explained further in the Writing Extensions article.
- IsMetamodExtension() must return false. No exceptions. Only pure-SourceMod extensions which optionally bind to Metamod:Source can return true here.
Examples:
IShareSys *sharesys = NULL; IExtension *myself = NULL; bool MyExtension::OnExtensionLoad(IExtension *me, IShareSys *sys, char *error, size_t maxlength, bool late) { sharesys = sys; myself = me; /* Get anything important we rely on */ return true; }
[edit] Binding to SourceMod
Binding to SourceMod requires a few steps:
- Acquire the IExtensionManager interface.
- If it exists, bind the extension.
- If not, wait for SourceMod to load.
IExtensionSys.h provides a macro, SOURCEMOD_INTERFACE_EXTENSIONSYS, which can be used via ISmmAPI::MetamodQuery(). If you do not recall, that is the facility Metamod:Source uses for inter-plugin communication. An example implementation of binding to SourceMod might look like:
bool SM_LoadExtension(char *error, size_t maxlength) { if ((smexts = (IExtensionManager *)g_SMAPI->MetaFactory( SOURCEMOD_INTERFACE_EXTENSIONS, NULL, NULL)) == NULL) { UTIL_Format(error, maxlength, SOURCEMOD_INTERFACE_EXTENSIONS " interface not found"); return false; } char path[256]; g_SMAPI->PathFormat(path, sizeof(path), #if defined __linux__ "addons/myplugin/bin/myplugin_mm_i486.so" #else "addons\\myplugin\\bin\\myplugin_mm.dll" #endif ); if ((myself = smexts->LoadExternal(&g_SMExt, path, "myplugin_mm.ext", error, maxlength)) == NULL) { /* Error was supplied by call */ return false; } return true; }
[edit] Detecting SourceMod Loads
This is also fairly easy:
- If not already done: Inherit IMetamodListener, implement OnMetamodQuery().
- If not already done: Call ISmmAPI::AddListener for your IMetamodListener interface.
- Watch for occurrences of SOURCEMOD_NOTICE_EXTENSIONS.
Example of such an implementation:
bool StubPlugin::Load(PluginId id, ISmmAPI *ismm, char *error, size_t maxlen, bool late) { PLUGIN_SAVEVARS(); /* Blah blah blah */ ismm->AddListener(this, this); return true; } void StubPlugin::AllPluginsLoaded() { /* BIND TO SOURCMEOD IF POSSIBLE */ } void *StubPlugin::OnMetamodQuery(const char *iface, int *ret) { if (strcmp(iface, SOURCEMOD_NOTICE_EXTENSIONS) == 0) { /* BIND TO SOURCEMOD */ } if (ret != NULL) { *ret = IFACE_OK; } return NULL; }
It is very important to return NULL even when this interface is detected. Otherwise, you may block other extensions from receiving the callback.
[edit] Detaching from SourceMod
Detaching is essential; if your plugin unloads without detaching, SourceMod will very quickly crash trying to deference your memory. Luckily, doing so is trivial. For example, in your ISmmPlugin::Unload() callback:
bool StubPlugin::Unload(char *error, size_t maxlen) { smexts->UnloadExtension(myself); }
Where smexts is the IExtensionManager pointer, and myself is the IExtension pointer.
[edit] SDK and Sample Implementation
The SourceMod SDK contains a sample implementation in public/mms_sample_ext. It is the Metamod:Source "stub plugin," modified to load as a SourceMod extension.
The following files have been added:
- sm_sdk_config.h - Contains two function for mapping and unmapping SourceMod Core interfaces. Interfaces can be enabled or disabled by toggling comments next to preprocessor macros here.
- sm_sdk_config.cpp - Implementation of sm_sdk_config.h. There is no need to edit this.
- stub_util.h/cpp - Contains a platform-safe wrapper for text formatting.
- sm_ext.cpp/sm_ext.h - Sample implementation IExtensionInterface.h and the binding/detaching code.
Additionally, stub_mm.cpp/stub_mm.h have been modified. IMetamodListener is inherited, and OnMetamodQuery is implemented as described earlier. Also, ISmmAPI::AllPluginsLoaded attempts a SourceMod binding.
Note: sm_sdk_config.h provides SM_AcquireInterfaces. It must be called to acquire the interfaces that are uncommented in the same file, unless you intend to query them manually.
Note: It is highly recommend that developers read the added files, and at the very least, include the sm_sdk_config files, which greatly simplify the acquisition of interfaces.
Note: The Makefiles are provided as a convenience/example, and for our own testing. As our build process requires special vcproj/sln changes (which are not yet documented), no Visual Studio project files are provided for mms_sample_ext. As most developers will already have an MM:S plugin implemented, this should largely be irrelevant. Otherwise, the project files from stub_mm can be used instead.
[edit] Renamed Variables/Macros
The extension SDK has a few renamed macros/variables from the default SDK. This is to prevent potential name clashes for Metamod:Source plugins, which have pre-existing code.
Changed global variables:
- g_pForwards, forwards -> sm_forwards
- g_pHandleSys, handlesys -> sm_handlesys
- g_pSM -> sm_main
- playerhelpers -> sm_players
- dbi -> sm_dbi
- gameconfs -> sm_gameconfs
- memutils -> sm_memutils
- gamehelpers -> sm_gamehelpers
- timersys -> sm_timersys
- threader -> sm_threader
- libsys -> sm_libsys
- plsys -> sm_plsys
- textparsers -> sm_text
- adminsys -> sm_adminsys
- menus -> sm_menus
Changed macros:
- SM_GET_IFACE -> SM_FIND_IFACE_OR_FAIL
- SM_GET_LATE_IFACE -> SM_FIND_IFACE
[edit] Example of a Successful Load
meta load addons/stub_mm Plugin "Stub Plugin" loaded with id 3. sm exts list [SM] Displaying 3 extensions: [01] SDK Tools (1.0.0.1336): Source SDK Tools [02] BinTools (1.0.0.1336): Low-level C/C++ Calling API [03] Stub Plugin (1.0.0.0): Sample empty plugin sm exts info 3 File: myplugin_mm.ext Loaded: Yes (version 1.0.0.0) Name: Stub Plugin (Sample empty plugin) Author: AlliedModders LLC () Binary info: API version 2 (compiled Nov 10 2007) Method: Loaded by Metamod:Source, attached to SourceMod meta unload 3 Plugin 3 unloaded. sm exts list [SM] Displaying 2 extensions: [01] SDK Tools (1.0.0.1336): Source SDK Tools [02] BinTools (1.0.0.1336): Low-level C/C++ Calling API
[edit] Doing Something Useful
SourceMod has over a dozen interfaces for interacting with plugins and greatly simplifying the Half-Life 2 development process. It contains memory abstraction, fast data structures, an abstracted menu and voting system, the ability to create and invoke plugin callbacks ("forwards"), the ability to provide new native functions to plugins, text processing, game data abstraction, threading abstraction, signature scanning, timers, and an object-oriented SQL layer.
For more information, see the Writing Extensions article. Note that the article uses different global names. See the earlier section for finding which names changed. | http://wiki.alliedmods.net/Writing_Extensions_from_Metamod:Source_Plugins | crawl-001 | en | refinedweb |
Had a hell of a time debugging some OpenAMF calls yesterday. Turns out, when Flash deserializes your class, it basically takes a vanilla object, puts properties on it and assigns their values, and then points that instance’s __proto__ property to the prototype of the class you registered via Object.registerClass. The downside to this is it doesn’t run your setter functions on any getter/setters you have set on the class. Naturally, your getters fail immediately because they look to a private equivalent variable which is different, and when you call the setter… it’s really a function.
How Flash manages to keep “firstName” the public property and “firstName” the public getter function in the same namespace is beyond me, but regardless, I’ve tested in Flashcom last night, and the same thing happens there, too, so it appears to be how Flash deserializes your class.
The way we, “solved it” as my manager says, or “worked around it” as I claim, is emulating, EXACTLY the Java class equivalents. So, you have private properties in the Java model class, like:
private String firstName;
And same on the Flash side:
private var firstName:String;
And instead of getter/setter functions in Flash, you just use the get/set function methology:
public function getFirstName():String
{
return firstName;
}
public function setFirstName(val:String):Void
{
firstName = val;
}
I really don’t like this at all, and personally feel that there should either be an event letting you know when the class is deserialized (Flashcom does this for server-side ActionScript classes via the onInitialize event) so you can then run the getter/setters yourself, OR Flash should just intrinsically know there are getter/setters in place, and set the private variables accordingly. This gets sticky though because you’re now having the Flash Player run code on your classes. Thus, I vote for the first.
What is a Vanilla object?
Ice
April 19th, 2005
Vanilla, like:
var o = {};
o.prop = ‘value’;
That’s an AS1 vanilla object. You could also do:
var o:Object = {};
or:
var o:Object = new Object();
Either way, if you trace it out:
trace(o.__proto__ == Object.prototype); // true
What I think Flash does when it’s deserializing your class from the AMF packets is taking this instance, and going:
o.__proto__ = YourClass.prototype;
Where YourClass is what you registered too up top in your code:
Object.registerClass(’YourClass’, YourClass);
If Java sends a ‘YourClass’ class, then Flash then knows to map it to a YourClass, an ActionScript class.
JesterXL
April 19th, 2005
I’ve seen this also in some of the AMFPHP example files. I think a decent workaround is creating an init method for that object, and running it immediately after you receive the object in the result event. This init method can transpose the variables to getters/setters.
Patrick Mineault
April 19th, 2005
It seems your constructor fires after all of your properties have their values set; I wasn’t seeing this in my Flashcom examples last night, but Brian Lesser from the Flashcom list sent me a working example. If it does work, I’ll see if there isn’t a way to set the privates during the constructor, thus having my getters work once the class is ready to be accessed. Stay tuned….
JesterXL
April 19th, 2005
I’m only running into this issue now, so hadn’t seen this thread before, but…
Couldn’t you use the same ‘workaround’ that UIComponent uses for handling clip parameters? That would solve it (and, actually, I think it’s exactly the same problem).
I’ll have to give it a try and post my results…
Jason Nussbaum
February 1st, 2006 | http://jessewarden.com/2005/04/class-deserialization-openamf-flashcom.html | crawl-001 | en | refinedweb |
Fl_Group | +----Fl_Wizard
#include "Fl_Wizard.h"
The
Fl_Wizard widget is based off the
Fl_Tabs
widget, but instead of displaying tabs it only changes "tabs" under
program control. Its primary purpose is to support "wizards" that
step a user through configuration or troubleshooting tasks.
As with
Fl_Tabs, wizard panes are composed of child (usually
Fl_Group) widgets. Navigation buttons must be added separately.
The constructor creates the
Fl_Wizard widget at the specified
position and size.
The destructor destroys the widget and its children.
This method shows the next child of the wizard. If the last child is already visible, this function does nothing.
This method shows the previous child of the wizard. If the first child is already visible, this function does nothing.
Sets or gets the child widget that is visible. | http://www.fltk.org/doc-1.1/Fl_Wizard.html | crawl-001 | en | refinedweb |
generate bindings for the Google Guice library a lot of errors are encountered. It looks like many of them are related to some classes in the library being bound with names starting with a dot. Some examples:
.AbstractIterator
.AbstractMapEntry
.AsynchronousComputationException
The jar file can be found here:
I don't think this class library is "android ready". It misses some classes that are not in android API e.g. javax.inject.Provider (which seems to be JavaEE class):
/home/atsushi/svn/monodroid/tools/msbuild/build/Novell/Xamarin.Android.Bindings.targets: Error: Tool exited with code: 1. Output: Couldn't load class com/google/inject/Provider
Couldn't load class com/google/inject/Scopes$1$1
Couldn't load class com/google/inject/internal/InjectorImpl$4
Couldn't load class com/google/inject/internal/InjectorShell$InjectorFactory
Couldn't load class com/google/inject/internal/InjectorShell$LoggerFactory
Couldn't load class com/google/inject/internal/ProviderMethod
Couldn't load class com/google/inject/internal/ProviderMethodsModule$LogProvider
Couldn't load class com/google/inject/internal/ProviderToInternalFactoryAdapter
Couldn't load class com/google/inject/spi/ProviderLookup$1
Couldn't load class com/google/inject/spi/ProviderWithDependencies
Couldn't load class com/google/inject/spi/ProviderWithExtensionVisitor
Couldn't load class com/google/inject/util/Providers$1
Couldn't load class com/google/inject/util/Providers$2
Couldn't load class com/google/inject/util/Providers$3
Exception in thread "main" java.lang.NoClassDefFoundError: javax/inject/Provider.getDeclaredMethods0(Native Method)
at java.lang.Class.privateGetDeclaredMethods(Class.java:2427)
at java.lang.Class.getDeclaredMethods(Class.java:1791)
at jar2xml.JavaClass.appendToDocument(JavaClass.java:466)
at jar2xml.JavaPackage.appendToDocument(JavaPackage.java:66)
at jar2xml.Start.main(Start.java:157)
Caused by: java.lang.ClassNotFoundException: javax.inject.Provider)
... 17 more
(RoboGuice)
Were you using this jar file exactly? I don't think it's going to work on Android. At least we cannot support what is not covered directly or indirectly in Android API.
Created attachment 1903 [details]
Required jar file
Sorry, I forgot to include javax.inject.jar which is required by Guice.
Thanks, reopening.
The issue I noticed with related to this guice-3.0-no_aop.jar is that it turned out to contain some "public" class whose name begin with '$'. In our toolchain we replace '$' with dot '.' as it usually express a nested type. I have no idea what kind of sources and compiler or any toolchains could generate such a "broken" class, but we'll have to eliminate those classes away from the API generator.
Apart from the issue itself, this problematic package in the jar can be entirely eliminated as there is no public class. To do so, you can add Metadata.xml that contains one simple line:
<metadata>
<remove-node
</metadata>
Created attachment 1925 [details]
build log
Are you able to build the binding after eliminating that package? I still get a bunch of build errors related to missing types after doing so (see attached log file).
Ah, not yet (that's part of why it is kept open). I plan to continue investigating the remaining issue next week. Sorry for the inconvenience.
After some fixes in type resolution, our internal build don't seem to have unresolved issue exposed in this bug repro anymore. The remaining ones look like:
/home/atsushi/デスクトップ/RoboGuice/RoboGuice/obj/Debug/generated/src/Com.Google.Inject.Internal.BindingBuilder.cs(126,33): error CS0102: The type `Com.Google.Inject.Internal.BindingBuilder' already contains a definition for `cb_to_Lcom_google_inject_Key_'
which sounds like a duplicate for bug #5020.
We need some different fix for this bug, apart from the fix for #5020.
With further investigation, I have to say Google Guice cannot be supported with our current policy to exclude java.lang.reflect. Here is why.
1) First, there is an issue that the API description generator somehow misses"variance" of the interface implementation in the target library. Com.Google.Inject.Internal.BindingBuilder contains two "To(Key)" methods, where the one that returns IScopedBindingBuilder is invalid (there is another one which returns BindingBuilder, which is valid). There is another such pair "ToProvider(Key)" which falls into the same result.
This can be workarounded by adding a metadata fixup like below:
<metadata>
<remove-node
<remove-node path="/api/package[@name='com.google.inject.internal']/
class[@name='BindingBuilder']/
method[@name='to'][count(parameter) = 1][@return='com.google.inject.binder.ScopedBindingBuilder']" />
<remove-node path="/api/package[@name='com.google.inject.internal']/
class[@name='BindingBuilder']/
method[@name='toProvider'][count(parameter) = 1][@return='com.google.inject.binder.ScopedBindingBuilder']" />
</metadata>
We'll have to fix this issue. But there is another problem.
2) There is a bunch of classes that depends on java.lang.reflect classes. Here is an example, IBinder:
/home/atsushi/デスクトップ/RoboGuice/RoboGuice/obj/Debug/generated/src/Com.Google.Inject.IPrivateBinder.cs(77,77): Error CS0234: The type or namespace name `IBinder' does not exist in the namespace `Com.Google.Inject'. Are you missing an assembly reference? (CS0234) (RoboGuice)
This com.google.inject.Binder interface could not be imported, due to these issues (reported in the build output):
Unknown parameter type java.lang.reflect.Constructor<S> found in method ToConstructor in type Com.Google.Inject.Binder.ILinkedBindingBuilder
Unknown parameter type java.lang.reflect.Constructor<S> found in method ToConstructor in type Com.Google.Inject.Binder.ILinkedBindingBuilder
Invalid return type com.google.inject.binder.LinkedBindingBuilder<T> found in method Bind in type Com.Google.Inject.IBinder
com.google.inject.Binder implements com.google.inject.binder.LinkedBindingBuilder. And this LinkedBindingBuilder cannot be generated because one of its method, toConstructor(), references java.lang.reflect.Construtcor which *does not exist* in java.lang.reflect.
In *theory*, we cannot provide an automatic bindings for such an *interface* that we cannot bind *any* of the members, because we cannot generate valid Android Callable Wrapper at app build time (javac rejects the ACW that is only an incomplete implementation).
We should add this limitation to our binding troubleshooting document.
I have generated a similar bugzilla
Does this mean that Google Map Utility cannot be supported by Xamarin binding neither ? :-(
Created attachment 6255 [details]
Library.jar for Google Map Utility
No. | https://xamarin.github.io/bugzilla-archives/51/5111/bug.html | CC-MAIN-2019-43 | en | refinedweb |
Talk:Knight's tour
Contents
solutions found fast[edit]
Wow, this was found fast. I was still prepping my first couple implementations.:) --Markjreed 02:09, 30 May 2011 (UTC)
Added my original perl solution and sample output; moved out of draft status. --Markjreed 02:48, 30 May 2011 (UTC)
References[edit]
The following had more than I needed to know about the problem A Simple Algorithm for Knight’s Tours by Sam Ganzfried. --Paddy3118 07:22, 29 May 2011 (UTC)
- (above) broken link. -- Gerard Schildberger (talk) 20:56, 22 July 2019 (UTC)
- (above) referenced document can be found here: A Simple Algorithm for Knight’s Tours by Sam Ganzfried
I discovered this weekend that Warnsdorff sometimes generates incomplete tours. This is discussed in Granzfried (above) and also in Mordecki.
- Counting Knight's Tours through the Randomized Warnsdor� Rule, Cancela & Mordecki, 2006 --Dgamey 11:05, 30 May 2011 (UTC)
- Estimating the efficiency of backtrack programs, Knuth, 1974 --Dgamey 11:36, 30 May 2011 (UTC)
- Knight's Tours, Hill & Tostado, 2004 --Dgamey 19:56, 30 May 2011 (UTC)
I found some additional references that may be of interest including a genetic algorithm, called Ant Colony.
-
- Ant Colony Algorithm
-
--Dgamey 10:10, 2 June 2011 (UTC)
Incomplete Tours and Warnsdorff[edit]
While implementing the Icon/Unicon version over the weekend, I noticed that the algorithm frequently produced incomplete or dead-ended tours. A little investigation proved insightful:
- backtracking unless it can be limited dramatically will be inefficient (Knuth)
- the order the Knight's moves are presented for selection (beyond accessibility) appears to have an effect (Granzfried)
- the algorithm can be probabilistically tuned (Mordecki)
- most papers investigating Warnsdorff indicate that it is imperfect
I haven't measured the hit/miss rate of the Unicon version of the algorithm. There are some aspects that differ from other implementations posted that may be responsible. It would be interesting to compare completion rates of the various implementations. Possible areas of consideration/cause for variance in efficiency:
- using ordered sets to resolve tie breakers. The method (in Unicon) used to generate the 8 possible Knight moves is different and other implementations tend to present them in a given order.
--Dgamey 13:21, 30 May 2011 (UTC)
- I did implement Roths extension, which is to break ties by chosing the point furthest from the centre:
def accessibility(board, P, boardsize=boardsize, roths_extension=True):
access = []
brd = copy.deepcopy(board)
for pos in knightmoves(board, P, boardsize=boardsize):
brd[pos] = -1
if not roths_extension:
access.append( ( len(knightmoves(brd, pos, boardsize=boardsize)),
pos ) )
else:
access.append( ((len(knightmoves(brd, pos, boardsize=boardsize)),
-(complex(*pos) - (boardsize/2. + boardsize/2.j)).__abs__()),
pos) )
brd[pos] = 0
return access
- I didn't really have time to measure its effectiveness though. --Paddy3118 13:27, 30 May 2011 (UTC)
- The Perl solution is deterministic, and produces complete tours for all 64 start squares. So it must be something in the ordering of the move list. --Markjreed 01:54, 31 May 2011 (UTC)
The 7x7 problem[edit]
- Try a 7x7 board. --Paddy3118 03:24, 31 May 2011 (UTC)
- I will. At this point there is something wrong with this solution. I will have to come back to it later (possibly this weekend). This was implemented from the WP description which talks about sets. I think the heart of the problem lies in the used of unordered sets everywhere and I will have to walk through some comparative examples side by side. This wouldn't be the first time I've been burned by a vague WP algorithm description. I'll have to borrow one of the other solutions and add code to show me the order squares get presented. --Dgamey 09:48, 31 May 2011 (UTC)
- Confirmed that I sometimes get incomplete tours on 7x7 with Warnsdorff using the move list order in the Perl code. Leaving the any-size-board generalization out of code on page until I handle that case. --Markjreed 12:47, 31 May 2011 (UTC)
- I believe that you've got to filter the output of the Warnsdorff algorithm in case it fails to do a tour. (That is, apply the “if at first you don't succeed” principle.) I don't know what the probability of failure is though. You might want to add the checks for impossibility (see the WP page) to your code though. –Donal Fellows 13:50, 31 May 2011 (UTC)
- The probability of failure depends on the board size and the tiebreak rule (move consideration order, for a first- or last-wins algorithm); for random move selection, it's about 25% on a 7x7 board. The order that I picked happens to work 100% of the time for an 8x8 board, but a general solution requires a more complex algorithm. The Ganzfried paper cited above includes one such, Squirrel's algorithm, which adjusts the ordering of the moves after certain landmarks in the progress of the tour. --Markjreed 02:29, 1 June 2011 (UTC)
- It should be 100% rate of failure on a 7x7 board! The issue is that a true tour is one that's a circuit that goes back to the initial position. If there's an odd number of squares, a simple parity argument shows that there cannot be solution (there must be different numbers of white and black squares, so a return to the initial location would require a parity violation when completing the loop). Sorry to be so awkward, but this problem's actually very well defined in this area… –Donal Fellows 14:12, 2 June 2011 (UTC)
- I started to measure success/failure on a 7x7 using different tie breakers. Starting with a triangle of squares that provide a minimum under rotation & reflection it really looks like starting position is the predominant factor. I haven't yet tried all cases just in case rotation/reflection does affect the results.
- This shows a summary of results for 5 tries at each starting position:
Results of tests for N=7 : Starting Square | a1 a2 a3 a4 b2 b3 b4 c3 c4 d4 *All* * Count * | 40 40 40 40 40 40 40 40 40 40 400 * Total * | 80.00% 0.00% 70.00% 0.00% 80.00% 0.00% 62.50% 92.50% 0.00% 100.00% 48.50% ExperimentalBreaker | 80.00% 0.00% 70.00% 0.00% 80.00% 0.00% 50.00% 90.00% 0.00% 100.00% 47.00% FirstTieBreaker | 80.00% 0.00% 70.00% 0.00% 70.00% 0.00% 70.00% 100.00% 0.00% 100.00% 49.00% RandomTieBreaker | 90.00% 0.00% 70.00% 0.00% 80.00% 0.00% 50.00% 90.00% 0.00% 100.00% 48.00% RothTieBreaker | 70.00% 0.00% 70.00% 0.00% 90.00% 0.00% 80.00% 90.00% 0.00% 100.00% 50.00%
- The notable thing about the pattern of failure in 7x7 is that tours started every other square fail and this shifts by one every rank. The symmetries of the squares above hold for all tie breakers and the overall pattern of failure is a cross-hatching. Like this:
a b c d e f g +---------------+ 7 | T - T - T - T | 7 6 | - T - T - T - | 6 5 | T - T - T - T | 5 4 | - T - T - T - | 4 3 | T - T - T - T | 3 2 | - T - T - T - | 2 1 | T - T - T - T | 1 +---------------+ a b c d e f g
- Where T indicates that Warndsdorf/Roth found a tour and - indicates a failure to find a tour. A quick estimate of the number of paths to be test for an exhaustive search confirmed that would be impossible. I tried a number of searches to find references to unsolvable knights tours on 7x7 boards and found none. I find myself wonder if there are any solutions on any of those failed squares. --Dgamey 10:59, 6 June 2011 (UTC)
- Looking at two cases where the start was a1 and a3, the a1 failed and a3 start did not (Random Tie Breaker). Both case went through a1 but the one starting in a3 went through a1 on move 37. Looking at the ties, there was no obvious choice that would have produced a tour. The start in a1 would have had to violate the accessibility filter to succeed. That is a1, b3, c1, a2, b4, ... fails vs. a1, b3, c1, a2, c3, ... succeeds. In the later case c3 was chosen not from the ties but from the group with the highest accessibility. I'll have to dig into this a bit more later. What I did add was a log like this showing the move, minimal accessibility, and moves in that group. This is for the failing a1:
Debug log : move#, move : (accessibility) choices 1. a1 : (5) b3 c2 2. b3 : (3) c1 a5 3. c1 : (2) a2 4. a2 : (5) b4 5. b4 : (2) a6
- Thanks. How are you breaking ties? Roth? (Also can you find a solution on 7x7 starting on a2? see above. --Dgamey 13:23, 3 June 2011 (UTC)
C++ formatting[edit]
I edited the C++ to remove some of the changes made. Several are fairly pointless (such as adding const to all the local variables; the compiler is smart enough to figure that out if it even makes a difference), and most were just reformatting it to someone else's formatting preferences (++i vs i++, etc). If there were a sitewide C++ formatting guide (a possibility suggested on the C++ discussion page, but not currently implemented) I (or whoever) can format it to fit that. MagiMaster 03:43, 31 May 2011 (UTC)
- (Note: I didn't write the C++ code.) For trivial cases, const on local variables is unnecessary, but I'm not sure it was worth removing. Using const when a variable shouldn't change is often useful to avoid accidental mutation. (For similar reasons, I tend to write if statements as if(constval cmp nonconst)). Also, the compiler can't assume a local variable can be treated as const unless it can prove so, which goes out the window if a reference (or pointer-to) the variable is passed non-const to a function outside the current linkable object (the compiler can't know that the called function won't mutate the variable), and may also be very difficult under some local non-trivial operations involving its address or created references.
- A perfect compiler which took all logic optimizations to their every possible conclusion could be presumed to be able to treat non-const local variables as const (as long as pointers and references didn't go outside the current linkable object), but for any other compiler it's polite to drop hints.
- I do like the rest of the changes, though. --Michael Mol 16:20, 31 May 2011 (UTC)
- I wrote the original C++ code, and someone that didn't log in or sign edited it. Anyway, if there's a reason for it, I can put the const's back. MagiMaster 19:25, 31 May 2011 (UTC)
- I didn't make the anon edits. I'm just pointing out the distinction between 'unnecessary' and 'pointless'. I also felt a need to step in, because I haven't seen edit wars on RC, and it felt like we might be getting close to such over stylistic issues. So I simply stated my opinion and left it at that; I don't need to be a direct party to an edit war, and such things have traditionally been resolved on RC by talking over the pros and cons. C++ is going to be a tricky language for me to not interfere with, because it's my bread and butter... --Michael Mol 20:11, 31 May 2011 (UTC)
- Maybe if people tried not to do both 'stylistic' changes and fix coding errors in the one edit, then you could concentrate on arguing the merits of stylistic changes within their given context. SOmeone may be able to argue that for the given program, its's not gonna make much difference. On the problem of people not having an account before editing, then maybe a note asking them politely to properly join in the the discussion by giving you a name to converse with might be all it takes? (I, have been known to play fast-n-loose with Pythons 80 char lines rule). --Paddy3118 05:38, 1 June 2011 (UTC)
- I wasn't accusing anyone of anything, just stating why I'd done what I'd done. I don't want to see an edit-war either, so if it happens again, my first suggestion would be a community coding style. I know what my preferences are, but when I teach programming, I stress consistency over any one style, so I have no problem with the idea. (I'm just a TA, so don't take that as me trying to lend weight to my arguments.) If not a style guide, my second suggestion would be to not make purely stylistic changes to existing code. MagiMaster 03:21, 2 June 2011 (UTC)
- Sorry if I sounded a bit short; most of my wiki edits are in a few spare minutes here and there, so after a few rounds of quick edits and rewrites, my prose can ultimately sound worse than it started... I'm familiar with the TA role; Mwn3d is a former TA from RIT, and has been heavily involved with RC for three or four years, now. I think he suggested elsewhere following the model of J/HouseStyle, as far as developing a community style. I'm beginning to see a need for that, I suppose; better to have the debate and discussion over style in one place, than in dozens of places. I suppose the C++ page would be at C++/HouseStyle --Michael Mol 15:30, 2 June 2011 (UTC)
Tiling smaller tours[edit]
This blog post by Joe Leslie-Hurd has a novel technique of stitching together smaller tours to make larger ones. Enjoy. --Paddy3118 (talk) 06:28, 21 July 2015 (UTC) | http://rosettacode.org/wiki/Talk:Knight%27s_tour | CC-MAIN-2019-43 | en | refinedweb |
Hello,
I am trying to read data from .XLSX file using Latest Apache POI libraries 4.0.1. However I amgetting follwoing error when I am trying to getCellType() or cell.getStringCellValue() etc.
However it could read wb.getPhysicalNumberOfRows() , row.getCell(x) properly without error.
error - NoClassDefFoundError: org/openxmlformats/schemas/spreadsheetml/x2006/main/CTExtensionList
Steps followed -
package application;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;;
import org.apache.poi.ss.usermodel.DataFormatter;
InputStream ExcelFileToRead = new FileInputStream("D:\\Test)
{
System.out.print(cell.getStringCellValue()+" ");
}
else if(cell.getCellType() == XSSFCell.CELL_TYPE_NUMERIC)
{
System.out.print(cell.getNumericCellValue()+" ");
}
else
{
}
}
System.out.println();
}
Please let me know how to resolve this error.
regards,
Manali
You are probably missing the ooxml-schemas-1.4.jar file. See item 3 on the following FAQ page for details:
Please add ooxml-schemas-1.3.jar to sopaui_home/bin/ext, restart and try again.
Don't forget to accept as solution and give kudos.
Hi,
I tried by adding ooxml-schemas-1.4.jar file into ext folder but getting same error -
PFA: screenshot of ext folder jars.
regards,
Manali
even with ooxml-schemas-1.3.jar added to ext folder giving same error.
Can u please chk the screenshot provided and suggest if any jar missing or need to remove?
regards,
Manali
Please download POI-3.14 or POI 3.16 and ooxml-schemas-1.3.jar and put inside ext folder.
Please have a look at solution, I have provided and it worked:-...
@mkajale2, you stated that you are using POI 4.0.1 in your original question, according to the Apache POI FAQ:
You should be using ooxml-schemas-1.4.jar
Please review item 3 of the apache POI FAQ linked above, the title of item 3 is:
"I'm using the poi-ooxml-schemas jar, but my code is failing with "java.lang.NoClassDefFoundError: org/openxmlformats/schemas/*something*""
Which matches the error in you original post.
I have latest POI 4.0.1 and ooxml-schemas-1.4.jar so want the solution based on that.
If we have any known technical limitation then I will try out with POI-3.14 or POI 3.16 and ooxml-schemas-1.3.jar as suggested by you.
Plz share if u have faced issue with latest one.
thx -
Manali
Sorry, I missed your original reply, To be honest I'm not sure what to suggest next? I will mention the obvious, are you restarting Ready API after altering the contents of the ext directory?
The one thing that I'm not 100% sure of is whether the ooxml-schemas-1.4.jar file replaces poi-ooxml-schemas4.0.1.jar or sits along side it? The Apache FAQ uses the rather ambiguous text (my emphasis):
"Every so often, you may try to use part of the file format which isn't included in the minimal poi-ooxml-schemas jar. In this case, you should switch to the full ooxml-schemas-1.4.jar."
Does switch mean replace??? Perhaps try removing the file poi-ooxml-schemas4.0.1.jar but this is just a guess. | https://community.smartbear.com/t5/SoapUI-Pro/NoClassDefFoundError-while-reading-XLSX-file-using-XSSF-cls-for/m-p/181291/highlight/true | CC-MAIN-2019-43 | en | refinedweb |
Hi,
Low priority Query - I've found a way around this by adding in a separate groovy step instead - I was just wondering the reason for the behaviour
Original script is as below - and it asserts that the 'entityLogicalName' attribute value is <> 'appointment' - courtesy of @rao
**
*"
so - I decided due to project requirements that I needed to assert that a second attribute value should NOT contain a certain value - I duplicated the def logicalNames, def checkFor and the assertlogicalNames lines for an extra attribute check as below:
def json = new groovy.json.JsonSlurper().parseText(context.response)
def dataDescriptionvalue = json.data.Descriptiondef checkForDescriptionval = 'A list of certificates'def dataTitlevalue = json.data.Title
def checkForTitleval = 'Certificates'
//Negative check - value should not have certificates "!=",
//Positive check - use "==" to match value with certificates
assert dataDescriptionvalue.every {it != checkForDescriptionval}, "Not expecting ${checkForDescriptionval} value for dataDescriptionvalue, but ${checkForDescriptionval} value was found"
assert dataTitlevalue.every {it != checkForTitleval}, "Not expecting ${checkForTitleval} value for dataTitlevalue, but ${checkForTitleval} value was found"
HOWEVER - the second assertion never fires - essentially cos the step fails I suppose.
Can anyone confirm that this is the case (I removed the 'abort test if error occurs' checkbox on the test case) - but the second assertion didn't appear to fire
I did get around this by adding splitting the code to check the 2nd attribute and the associated assertion into a second groovy step - so my test case hierarchy is as follows:
REST Step
GroovyStep - checks the 'Description' attribute and asserts it doesn't contain 'A list of certificates'
GroovyStep - checks the 'Title' attribute and asserts it doesn't contain 'Certificates'
I am just wondering if there's a reason why you can't have another assertion in the same groovy test step? I understand it complicates things in case you get one assertion passing and one failing, but I would've thought it would report both the step failing anyway - just like it should in a manual test if you ever do include 2 assertions/verifications in the same step.....
Cheers!
richie
@richie ,
Couple of things.
1. The code snippet provided earlier is Script Assertion. And that can't into Groovy Step, and that does not work.
2. If the use case is to validate the response, assertion is the right way to check and fail the test step. Use of Groovy step is not correct thing.
3. Depends on the problem, solution varies.
4. If an assertion fails, following code will not be executed at all. There is different way to deal with it.
5. Can't see the such data mentioned in the re-written script in earlier attached json.? | https://community.smartbear.com/t5/SoapUI-Pro/Not-Contains-Assertion-JSON-attribute-value-not-XML/m-p/178625/highlight/true | CC-MAIN-2019-43 | en | refinedweb |
import "go.chromium.org/luci/milo/frontend"
middleware.go routes.go view_build.go view_build_legacy.go view_builder.go view_builder_legacy.go view_builders.go view_config.go view_console.go view_error.go view_frontpage.go view_logs.go view_search.go
BuilderHandler renders the builder page. Does not control access directly because this endpoint delegates all access control to Buildbucket with the RPC calls.
BuilderHandlerLegacy is responsible for taking a universal builder ID and rendering the builder page (defined in ./appengine/templates/pages/builder_legacy.html). We don't need to do an ACL check because this endpoint delegates all ACL checks authentication to Buildbucket with the RPC calls.
BuildersRelativeHandler is responsible for rendering a builders list page according to project. Presently only relative time is handled, i.e. last builds without correlation between builders), and no filtering by group has been implemented.
The builders list page by relative time is defined in ./appengine/templates/pages/builders_relative_time.html.
ConfigsHandler renders the page showing the currently loaded set of luci-configs.
ConsoleHandler renders the console page.
ConsolesHandler is responsible for taking a project name and rendering the console list page (defined in ./appengine/templates/pages/builder_groups.html).
ErrorHandler renders an error page for the user.
GetLimit extracts the "limit", "numbuilds", or "num_builds" http param from the request, or returns def implying no limit was specified.
GetReload extracts the "reload" http param from the request, or returns def implying no limit was specified.
HandleSwarmingLog renders a step log from a swarming build.
ProjectLinks returns the navigation list surrounding a project and optionally group.
Run sets up all the routes and runs the server.
UpdateConfigHandler is an HTTP handler that handles configuration update requests.
Package frontend imports 61 packages (graph) and is imported by 2 packages. Updated 2019-10-14. Refresh now. Tools for package owners. | https://godoc.org/go.chromium.org/luci/milo/frontend | CC-MAIN-2019-43 | en | refinedweb |
import "go.chromium.org/luci/server/auth/signing/signingtest"
Package signingtest implements signing.Signer interface using small random keys.
Useful in unit tests.
Signer holds private key and corresponding cert and can sign blobs with PKCS1v15.
func NewSigner(serviceInfo *signing.ServiceInfo) *Signer
NewSigner returns Signer instance that use small random key.
Panics on errors.
Certificates returns a bundle with public certificates for all active keys.
func (s *Signer) KeyForTest() *rsa.PrivateKey
KeyForTest returns the RSA key used internally by the test signer.
It is not part of the signing.Signer interface. It should be used only from tests.
KeyNameForTest returns an ID of the signing key.
ServiceInfo returns information about the current service.
It includes app ID and the service account name (that ultimately owns the signing private key).
func (s *Signer) SignBytes(c context.Context, blob []byte) (keyName string, signature []byte, err error)
SignBytes signs the blob with some active private key. Returns the signature and name of the key used.
Package signingtest imports 11 packages (graph). Updated 2019-10-14. Refresh now. Tools for package owners. | https://godoc.org/go.chromium.org/luci/server/auth/signing/signingtest | CC-MAIN-2019-43 | en | refinedweb |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.