text stringlengths 454 608k | url stringlengths 17 896 | dump stringclasses 91
values | source stringclasses 1
value | word_count int64 101 114k | flesch_reading_ease float64 50 104 |
|---|---|---|---|---|---|
On 17.8.2016 13:21, David Kupka wrote:
On 08/08/16 13:26, Jan Cholasta wrote:On 4.8.2016 16:32, David Kupka wrote:On 03/08/16 16:33, Jan Cholasta wrote:On 3.8.2016 16:23, David Kupka wrote:On 21/07/16 10:12, Jan Cholasta wrote:Hi,On 20.7.2016 14:32, David Kupka wrote:On 15/07/16 12:53, David Kupka wrote:Hello! After Honza introduced thin client that builds plugins and commands dynamically from schema client became much slower. This is only logical, instead of importing a module client now must fetch the schema from server, parse it and instantiate the commands using the data. First step to speed it up was addition of schema cache to client. That removed the RTT and download time of fetching schema every time. Now the most time consuming task became displaying help for lists of topics and command and displaying individual topics. This is simply because of the need to instantiate all the commands to find the relations between topics and commands. All the necessary bits for server commands and topics are already in the schema cache so we can skip this part and generate help from it, right? Not so fast! There are client plugins with commands and topics. So we can generate basic bits (list of all topics, list of all commands, list of commands for each topic) from schema and store it in cache. Then we need to go through all client plugins and get similar bits for client plugins. Then we can merge and print. Still the client response is not as fast as before and I this it even can't be. Also first time you display particular topic or list takes longer because it must be freshly generated and stored in cache for next use. And this is what the attached patches do. so there is no need to distinguish client plugins and remote plugins. The main idea of this approach is to avoid creating instances of the commands just to get the information about topic, name and summary needed for displaying help. Instead class properties are used to access the information directly in schema.Patch 0112: I think this would better be done in Schema.read_namespace_member, because Schema is where all the state is. (BTW does _SchemaNameSpace.__getitem__ raise KeyError for non-existent keys? It looks like it doesn't.) Patch 0113: How about setting _schema_cached to False in Schema.__init__() rather that getattr()-ing it in _ensure_cached()? Patch 0116: ClientCommand.doc should be a class property as well, otherwise .summary won't work on it correctly. _SchemaCommand.doc should not be a property, as it's not needed for .summary to work on it correctly. Otherwise works fine for me. HonzaUpdated patches attached.Thanks, ACK. Pushed to master: 229e2a1ed9ea9877cb5e879fadd99f9040f77c96I've made and reviewer overlooked some errors. Attached patches fix them.Shame on me. Anyway, 1) When schema() raises SchemaUpToDate, the current code explodes: ipa: ERROR: KeyError: 'fingerprint' Traceback (most recent call last): File "/usr/lib/python2.7/site-packages/ipalib/cli.py", line 1348, in run api.finalize() File "/usr/lib/python2.7/site-packages/ipalib/plugable.py", line 707, in finalize self.__do_if_not_done('load_plugins') File "/usr/lib/python2.7/site-packages/ipalib/plugable.py", line 422, in __do_if_not_done getattr(self, name)() File "/usr/lib/python2.7/site-packages/ipalib/plugable.py", line 585, in load_plugins for package in self.packages: File "/usr/lib/python2.7/site-packages/ipalib/__init__.py", line 919, in packages ipaclient.remote_plugins.get_package(self), File "/usr/lib/python2.7/site-packages/ipaclient/remote_plugins/__init__.py", line 92, in get_package plugins = schema.get_package(api, server_info, client) File "/usr/lib/python2.7/site-packages/ipaclient/remote_plugins/schema.py", line 558, in get_package fingerprint = str(schema['fingerprint']) File "/usr/lib/python2.7/site-packages/ipaclient/remote_plugins/schema.py", line 483, in __getitem__ return self._dict[key] KeyError: 'fingerprint' 2) We read server info every time get_package() is called. It should be cache similarly to how the schema is cached in the api object. 3) Some of the commands are still fully initialized during "ipa help commands". HonzaUpdated patches attached.
Thanks, ACK. Pushed to master: 6e6cbda036559e741ead0ab5ba18b0be0b41621e -- Jan Cholasta -- Manage your subscription for the Freeipa-devel mailing list: Contribute to FreeIPA: | https://www.mail-archive.com/freeipa-devel@redhat.com/msg34873.html | CC-MAIN-2018-51 | refinedweb | 718 | 61.12 |
Executing Shell Commands with Python
Introduction.
Using os.system to Run a Command
Python allows us to immediately execute a shell command that's stored in a string using the
os.system() function.
Let's start by creating a new Python file called
echo_adelle.py and enter the following:
import os os.system("echo Hello from the other side!")
The first thing we do in our Python file is import the
os module, which contains the
system function that can execute shell commands. The next line does exactly that, runs the
echo command in our shell through Python.
In your Terminal, run this file with using the following command, and you should see the corresponding output:
$ python3 echo_adelle.py Hello from the other side!
As the
echo commands prints to our
stdout,
os.system() also displays the output on our
stdout stream. While not visible in the console, the
os.system() command returns the exit code of the shell command. An exit code of 0 means it ran without any problems and any other number means an error.
Let's create a new file called
cd_return_codes.py and type the following:
import os home_dir = os.system("cd ~") print("`cd ~` ran with exit code %d" % home_dir) unknown_dir = os.system("cd doesnotexist") print("`cd doesnotexis` ran with exit code %d" % unknown_dir)
In this script, we create two variables that store the result of executing commands that change the directory to the home folder, and to a folder that does not exist. Running this file, we will see:
$ python3 cd_return_codes.py `cd ~` ran with exit code 0 sh: line 0: cd: doesnotexist: No such file or directory `cd doesnotexist` ran with exit code 256
The first command, which changes the directory to the home directory, executes successfully. Therefore,
os.system() returns its exit code, zero, which is stored in
home_dir. On the other hand,
unknown_dir stores the exit code of the failed bash command to change the directory to a folder that does not exist.
The
os.system() function executes a command, prints any output of the command to the console, and returns the exit code of the command. If we would like more fine grained control of a shell command's input and output in Python, we should use the
subprocess module.
Running a Command with subprocess
The subprocess module is Python's recommended way to executing shell commands. It gives us the flexibility to suppress the output of shell commands or chain inputs and outputs of various commands together, while still providing a similar experience to
os.system() for basic use cases.
In a new filed called
list_subprocess.py, write the following code:
import subprocess list_files = subprocess.run(["ls", "-l"]) print("The exit code was: %d" % list_files.returncode)
In the first line, we import the
subprocess module, which is part of the Python standard library. We then use the
subprocess.run() function to execute the command. Like
os.system(), the
subprocess.run() command returns the exit code of what was executed.
Unlike
os.system(), note how
subprocess.run() requires a list of strings as input instead of a single string. The first item of the list is the name of the command. The remaining items of the list are the flags and the arguments of the command.
Note: As a rule of thumb, you need to separate the arguments based on space, for example
ls -alh would be
["ls", "-alh"], while
ls -a -l -h, would be
["ls", "-a", -"l", "-h"]. As another example,
echo hello world would be
["echo", "hello", "world"], whereas
echo "hello world" or
echo hello\ world would be
["echo", "hello world"].
Run this file and your console's output would be similar to:
$ python3 list_subprocess.py total 80 <a href="/cdn-cgi/l/email-protection.html" class="__cf_email__" data-[email protected]</a> 1 stackabuse staff 216 Dec 6 10:29 cd_return_codes.py <a href="/cdn-cgi/l/email-protection.html" class="__cf_email__" data-[email protected]</a> 1 stackabuse staff 56 Dec 6 10:11 echo_adelle.py <a href="/cdn-cgi/l/email-protection.html" class="__cf_email__" data-[email protected]</a> 1 stackabuse staff 116 Dec 6 11:20 list_subprocess.py The exit code was: 0
Now let's try to use one of the more advanced features of
subprocess.run(), namely ignore output to
stdout. In the same
list_subprocess.py file, change:
list_files = subprocess.run(["ls", "-l"])
To this:
list_files = subprocess.run(["ls", "-l"], stdout=subprocess.DEVNULL)
The standard output of the command now pipes to the special
/dev/null device, which means the output would not appear on our consoles. Execute the file in your shell to see the following output:
$ python3 list_subprocess.py The exit code was: 0
What if we wanted to provide input to a command? The
subprocess.run() facilitates this by its
input argument. Create a new file called
cat_subprocess.py, typing the following:
import subprocess useless_cat_call = subprocess.run(["cat"], stdout=subprocess.PIPE, text=True, input="Hello from the other side") print(useless_cat_call.stdout) # Hello from the other side
We use
subprocess.run() with quite a few commands, let's go through them:
stdout=subprocess.PIPEtells Python to redirect the output of the command to an object so it can be manually read later
text=Truereturns
stdoutand
stderras strings. The default return type is bytes.
input="Hello from the other side"tells Python to add the string as input to the
catcommand.
Running this file produces the following output:
Hello from the other side
We can also raise an
Exception without manually checking the return value. In a new file,
false_subprocess.py, add the code below:
import subprocess failed_command = subprocess.run(["false"], check=True) print("The exit code was: %d" % failed_command.returncode)
In your Terminal, run this file. You will see the following error:
$ python3 false_subprocess.py Traceback (most recent call last): File "false_subprocess.py", line 4, in <module> failed_command = subprocess.run(["false"], check=True) File "/usr/local/python/3.7.5/Frameworks/Python.framework/Versions/3.7/lib/python3.7/subprocess.py", line 512, in run output=stdout, stderr=stderr) subprocess.CalledProcessError: Command '['false']' returned non-zero exit status 1.
By using
check=True, we tell Python to raise any exceptions if an error is encountered. Since we did encounter an error, the
subprocess.run() function gives us immense flexibility that
os.system() doesn't when executing shell commands. This function is a simplified abstraction of the
subprocess.Popen class, which provides additional functionality we can explore.
Running a Command with Popen
The
subprocess.Popen class exposes more options to the developer when interacting with the shell. However, we need to be more explicit about retrieving results and errors.
By default,
subprocess.Popen does not stop processing of a Python program if its command has not finished executing. In a new file called
list_popen.py, type the following:
import subprocess list_dir = subprocess.Popen(["ls", "-l"]) list_dir.wait()
This code is equivalent to that of
list_subprocess.py. It runs a command using
subprocess.Popen, and waits for it to complete before executing the rest of the Python script.
Let's say we do not want to wait for our shell command to complete execution so the program can work on other things. How would it know when the shell command has finished execution?
The
poll() method returns the exit code if a command has finished running, or
None if it's still executing. For example, if we wanted to check if
list_dir was complete instead of wait for it, we would have the following line of code:
list_dir.poll()
To manage input and output with
subprocess.Popen, we need to use the
communicate() method.
In a new file called
cat_popen.py, add the following code snippet:
import subprocess useless_cat_call = subprocess.Popen(["cat"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) output, errors = useless_cat_call.communicate(input="Hello from the other side!") useless_cat_call.wait() print(output) print(errors)
The
communicate() method takes an
input argument that's used to pass input to the shell command. The
communicate method also returns both the
stdout and
stderr when they are set.
Having seen the core ideas behind
subprocess.Popen, we have now covered three ways to run shell commands in Python. Let's re-examine their characteristics so we'll know which method is best suited for a project's requirements.
Which one should I use?
If you need to run one or a few simple commands and do not mind if their output goes to the console, you can use the
os.system() command. If you want to manage the input and output of a shell command, use
subprocess.run(). If you want to run a command and continue doing other work while it's being executed, use
subprocess.Popen.
Here is a table with some usability differences that you can also use to inform your decision:
Conclusion
Python allows you to execute shell commands, which you can use to start other programs or better manage shell scripts that you use for automation. Depending on our use case, we can use
os.system(),
subprocess.run() or
subprocess.Popen to run bash commands.
Using these techniques, what external task would you run via Python? | https://www.codevelop.art/executing-shell-commands-with-python.html | CC-MAIN-2022-40 | refinedweb | 1,531 | 59.8 |
Viewing what's changed in ASP.NET Core 1.0.1
On 13th September, Microsoft announced they are releasing an update to .NET Core they are calling .NET Core 1.0.1. Along with the framework update, they are also releasing 1.0.1 version of ASP.NET and Entity Framework Core. Details about the update can be found in a blog post by Microsoft.
The post does a good job of laying out the process you should take to update both your machine and applications. It also outlines the changes that have occurred, as well as the corresponding security advisory.
I was interested to know exactly what had changed in the source code between the different releases, in ASP.NET in particular. Luckily as all ASP.NET Core development is open source on GitHub, that's pretty easy to do!:)
Comparing between tags and branches in GitHub
A feature that is not necessarily that well known is the ability to compare between two tags and branches using a url of the form:{username}/{repo}/compare/{older-tag}...{newer-tag}
This presents you with a view of all the changes between the two provided tags. Alternatively, navigate to a repository, select branches, click the compare button and select the branches or tags to compare manually.
In the rest of the post, I'll give a rundown of the significant changes in the ASP.NET Core and EF Core libraries.
Changes in ASP.NET MVC
Most. You can see the full diff here.
The first notable change is the handling of FIPS mode in the SHA256 provider. A static helper class,
CryptographyAlgorithms, shown below, has been added to handle the case that you are running on a Windows machine with FIPS mode enabled. FIPS mode stands for 'Federal Information Processing Standard' and defines a set of approved cryptographic algorithms for US government computers - see here for a more detailed description. If you're not running applications on US federal computers, this change probably won't affect you.
using System.Security.Cryptography; namespace Microsoft.AspNetCore.Mvc.TagHelpers.Internal { public static class CryptographyAlgorithms { #if NETSTANDARD1_6 public static SHA256 CreateSHA256() { var sha256 = SHA256.Create(); return sha256; } #else public static SHA256 CreateSHA256() { SHA256 sha256; try { sha256 = SHA256.Create(); } // SHA256.Create is documented to throw this exception on FIPS compliant machines. // See: catch (System.Reflection.TargetInvocationException) { // Fallback to a FIPS compliant SHA256 algorithm. sha256 = new SHA256CryptoServiceProvider(); } return sha256; } #endif } }
The second significant change is in MvcViewFeaturesMvcCoreBuilderExtensions. This class is called as part of the standard MVC service configuration for registering with the dependency injection container. The file has a single changed line, where the registration of
ViewComponentResultExecutor is changed from singleton to transient.
I haven't dug into it further, but I suspect this is where the privilege elevation security bug mentioned in the announcement arose. This really shows how important it is to configure your service lifetimes correctly. This is especially important when adding additional dependency to an already existing and configured class, to be ensure you don't end up with captured transient dependencies.
The final main change in the MVC repository fixes this issue whereby a DELETE route is incorrectly matched against a GET method. The commit message for the commit fixing the issue gives a great explanation of the problem, which boiled down to an overloaded
== operator giving incorrect behaviour in this method. The fix was to replace the implicit
Equals calls with
ReferenceEquals.
Changes in AntiForgery
Much like the MVC repository, the AntiForgery repository uses a SHA256 algorithm. In order to not throw a
TargetInvocationException when calling
SHA256.Create() on FIPS enabled hardware, it falls back to the
SHA256CryptoServiceProvider. Again, if you are not running on US Federal government computers then this probably won't affect you. You can view the diff here.
Changes in KestrelHttpServer
There is a single change in the Kestrel web server that fixes this bug, whereby replacing the
Request.Body or
Response.Body stream of the
HttpContext causes it to be replaced for all subsequent requests too. This simple fix solves the problem by ensuring the streams are reset correctly on each request:
Other changes
I've highlighted the changes in ASP.NET Core 1.0.1, but there are also a tonne of minor changes in the Entity Framework Core library, too many to list here. You can view the full change list here. Finally, the CoreCLR runtime has fixed these three bugs (here, here and here), and the templates in the dotnet CLI have been updated to use version 1.0.1 of various packages.
Summary
This was just a quick update highlighting the changes in ASP.NET Core. As you can see, the changes are pretty minimal, like you'd expect for a patch release. However the changes highlight a number of bugs to keep an eye out for when writing your own applications - namely incorrect service lifetimes and potential bugs when overloading the
== operators. | http://andrewlock.net/viewing-whats-changed-in-asp-net-core-1-0-1/ | CC-MAIN-2016-50 | refinedweb | 822 | 58.18 |
⚠️ Sometimes, it happens that graphQL don't find your intl data located in
intl , run the command
gatsby clean to remove the cache 🙂
Prerequisite
- The first part of the tutorial have to work! We previously linked Gatsby and Contentful together 🙂
React-intl setup
First, you have to install the plugin based on react-intl which offers you to translate your website.
⚠️ I'm French so, I define the other locale to
fr put your own instead!
- Install your plugin :
npm install --save gatsby-plugin-intl
- Now, configure your config file :
gatsby-config.js
{ resolve: `gatsby-plugin-intl`, options: { // language JSON resource path path: `${__dirname}/src/intl`, // supported language languages: [`en`, `fr`], // language file path defaultLanguage: `en`, // option to redirect to `/en` when connecting `/` redirect: true, }, },
- You can create the
intlfolder into the
srcand create two files corresponding to your locales
// src/intl/en.json { "title": "Gatsby English", "description": "Project description", "author": "@louisbertin", "hello": "Hi people!", "welcome": "Welcome to your new Gatsby site.", "title_page2": "Page two", "hello_page2": "Hi from the second page", "go_page2": "Go to page 2", "welcome_page2": "Welcome to page 2", "go_back": "Go back to the homepage", "footer_build": "Built with", "notfound": { "header": "NOT FOUND", "description": "You just hit a route that doesn't exist... the sadness." } }
// src/intl/fr.json { "title": "Gatsby French", "description": "Project description", "author": "@louisbertin", "hello": "Salut les gens!", "welcome": "Bienvenue sur votre nouveau site Gatsby", "title_page2": "Page deux", "hello_page2": "Salut depuis la seconde page", "go_page2": "Aller à la page 2", "welcome_page2": "Bienvenue sur la page 2", "go_back": "Retour à la page d'accueil", "footer_build": "Construit avec", "notfound": { "header": "NOT FOUND", "description": "Vous voulez accéder à une route qui n'existe pas..." } }
Build multilingual blog
- To use all keys located in
intlfolder you have to change all your react components and pages to work with react-intl. I'll give you an example with the index page.
// pages/index.js import React from "react" import { graphql } from "gatsby" import Layout from "../components/layout" import SEO from "../components/seo" import { injectIntl, Link, FormattedMessage } from "gatsby-plugin-intl" const IndexPage = ({ data, intl }) => ( <Layout> <SEO title={intl.formatMessage({ id: "title" })} /> <h1> <FormattedMessage id="hello" /> </h1> <p> <FormattedMessage id="welcome" /> </p> <br /> <Link to="/page-2"> <FormattedMessage id="go_page2" /> </Link> </Layout> ) export const query = graphql ` query ContentFulPosts($locale: String) { allContentfulPost(filter: { node_locale: { eq: $locale } }) { nodes { contentful_id title path } } } ` export default injectIntl(IndexPage)
and with a component page 🙂
import React from "react" import PropTypes from "prop-types" import { useStaticQuery, graphql } from "gatsby" import Header from "./header" import "./layout.css" import { injectIntl, FormattedMessage } from "gatsby-plugin-intl" const Layout = ({ children, intl }) => { const data = useStaticQuery(graphql` query SiteTitleQuery { site { siteMetadata { title } } } `) return ( <> <Header siteTitle={data.site.siteMetadata.title} /> <div style={{ margin: `0 auto`, maxWidth: 960, padding: `0px 1.0875rem 1.45rem`, paddingTop: 0, }} > <main>{children}</main> <footer> © {new Date().getFullYear()}, <FormattedMessage id="footer_build" />{" "} {` `} <a href="">Gatsby</a> </footer> </div> </> ) } Layout.propTypes = { children: PropTypes.node.isRequired, } export default injectIntl(Layout)
- Before retrieving the data, you have to create the blog post template. This template has to fetch the current locale to get the correct data.
import React from "react" import { graphql } from "gatsby" import Layout from "../components/layout" const BlogPost = ({ pageContext, data }) => ( <Layout> <h1>{data.contentfulPost.title}</h1> </Layout> ) export const query = graphql ` query ContentFulPost($slug: String, $locale: String) { contentfulPost(path: { eq: $slug }, node_locale: { eq: $locale }) { path node_locale title } } ` export default BlogPost
- Now, it's time to use gatsby-node file to generate posts pages for each locale!
const path = require(`path`) // pages locale exports.onCreatePage = ({ page, actions }) => { const { createPage, deletePage } = actions deletePage(page) // You can access the variable "locale" in your page queries now createPage({ ...page, context: { ...page.context, locale: page.context.intl.language, }, }) } // blog posts MyQuery { allContentfulPost { edges { node { path } } } } ` ).then(result => { if(result.errors) { throw result.errors } // Create blog post pages. result.data.allContentfulPost.edges.forEach(edge => { const path = edge.node.path createPage({ // Path for this page — required path: path, component: blogPostTemplate, context: { slug: path, }, }) }) }) }
- Then, update graphQL query on index to display the right post
export const query = graphql ` query ContentFulPosts($locale: String) { allContentfulPost(filter: { node_locale: { eq: $locale } }) { nodes { contentful_id title path } } }
- Finally, you can access your posts and multilingual seems to work.. but to test everything we need to have a language switcher! So, create a component called
Language.jsand place it in the
componentsfolder of your project
import React from "react" import { IntlContextConsumer, changeLocale } from "gatsby-plugin-intl" const languageName = { en: "English", fr: "Français", } const Language = () => ( <div> <IntlContextConsumer> {({ languages, language: currentLocale }) => languages.map(language => ( <a key={language} onClick={() => changeLocale(language)} style={{ color: currentLocale === language ? `yellow` : `white`, margin: 10, textDecoration: `underline`, cursor: `pointer`, }} > {languageName[language]} </a> )) } </IntlContextConsumer> </div> ) export default Language
You can call the language component in the Header component for example and everything should work!
In the next post
In the next post I will explain how to deploy your multilingual blog on Netlify!
By the way, you can find my code on Github!
Discussion
I originally left a comment here regarding translated slugs, but removed it in lieu of finding somewhat of a working solution. I thought I'd follow up on this in case anyone is stuck or possibly has a better one.
The Problem
In this context, the slug is assumed to be the same for each locale. For example:
But, what if you want the slugs themselves to be translations of each other?
You can set this field up for localization in Contentful, but the issue I found with this is that it will generate each page in each language under every locale:
Meaning, if I were to visit
/fr/english-page/I'd be seeing English content, which is not ideal. Naturally, if they share the same slug this wont happen, but what we actually want here is:
The Solution
The basic gist of the solution to this for me was to be able to determine that the page being created was of a specific language. First thing was to pass in the
node_localeof the page to the context:
Now in
onCreatePagewe know the locale. In addition to this,
page.context.intlcan provide us the language, meaning if we compare these two as follows we will be able to determine if the locale and language of the page match:
This will filter out the pages for each locale, but there's still an issue with this. It also filters out
/,
/dev-404-page/etc. Quick and dirty solution for this problem:
Conclusion
This is what worked for me given a time constraint as it was a requirement to have translated slugs for the project, though the implementation is imperfect since in the case the slug is the same, it wont create a page for that locale. Good example of this would be if you had multiple English locales, meaning the slug actually wouldn't be different. Wondering if there's a better way to handle this?
Thank you for this man. I was struggling a lot with this. I upgraded it a bit since I'm using the category pages too.
I had to add locale and type to post and category context
and category respectively
Hi Seán, thanks a lot for your workaround!
Did you come across a solution for the case slug are actualle equal on purpose or because even translated they give the same (e.g. France is France in English and in French, Portugal as well).
That would be awesome!
I'm using
gatsby-plugin-intlaswell. How do you go about mapping through an array that is translated?
Example:
Component where I want to map:
Hi!
I have created the same kind of data in my
intlfile :
If I try to
console.log(intl.messages)in one of my components I can see that
react-intlnot return an array of string but it creates multiple keys based on the number of items in the array :
So, you can create an array based on the object keys :
It returns :
Now you can loop through this array and display all your data 🙂
Or.. if you know the number of items in your list (not recommended but faster) :
Thank you for the answer! I ended up doing something similar: spectrum.chat/gatsby-js/general/us...
Thanks for this post, very nice and not a lot explained on the web!
Concerning the warning in the intro, do you know what
gatsby cleancommand exactly do? I've already meet this issue with Contentful multilanguage.
Thanks a lot!
gatsby cleanis a command line dedicated to remove
./cachefolder and wipe out your
./publicfolder.
You can find more informations about this command on the official Gatsby documentation 🙂
gatsbyjs.org/docs/gatsby-cli/#clean
gatsbyjs.org/docs/debugging-cache-...
Thank you for this post - it is very helpful. I am working on my project and e.g. I have en and ar and en is the default language. If I call changeLocale('en') on /en/about I'd like to go to /about not /en/about. Is that possible?
Hi, thanks for the post! I did something similar and tried with the same language component but I noticed that if add for instance /fr in the address on the browser and then click english, it doesn't work and I see (locally) GET localhost:9000/page-data/en/fr/pag... 404, like gatsby tries to fetch data for en/fr because it preprends en but doesn't remove fr. But if I go to localhost:9000/ then it works fine.
This behavior happens in a prod conf with gatsby build and serve, but works fine with gatsby develop. Have you encountered that too?
Thank you! Your tutorial helped me A LOT! I think that this actually is the easiest way to do i18n in a Gatsby project I've found so far. I've successfully used it in two of my projects so far.
Thank you! Good to hear!
I gonna make post about the same subject in the following weeks with an improved method. Stay tuned! 😉 | https://practicaldev-herokuapp-com.global.ssl.fastly.net/louisbertin/multilingual-website-with-gatsby-and-contentful-part-2-25pf | CC-MAIN-2021-04 | refinedweb | 1,659 | 54.63 |
XDR library also provides primitive routines for C floating-point types.
bool_t xdr_float(xdrs, fp) XDR *xdrs; float *fp; bool_t xdr_double(xdrs, dp) XDR *xdrs; double *dp;
The first parameter, xdrs, is an XDR stream handle. The second parameter is the address of the floating-point number that provides data to the stream or receives data from it. Both routines return TRUE if they complete successfully, and FALSE otherwise.
Note - Because the numbers are represented in IEEE floating point, routines might fail when decoding a valid IEEE representation into a machine-specific representation, or the reverse.
The..
The external representation of the bytes is the same as their internal representation.
The primitive xdr_bytes() converts between the internal and external representations of byte arrays:
bool_t xdr_bytes(xdrs, bpp, lp, maxlength) XDR *xdrs; char **bpp; u_int *lp; u_int maxlength;
The usage of the first, second, and fourth parameters is identical to the first, second, and third parameters of xdr_string(). The length of the byte area is obtained by dereferencing lp when serializing; *lp is set to the byte length when deserializing.
The.
A structure with this information and its associated XDR routine could be coded as in the following code example.
Example A-7 Array Example #1., handles are opaque. The xdr_opaque() primitive is used for describing fixed-sized opaque bytes.
bool_t xdr_opaque(xdrs, p, len) XDR *xdrs; char *p; u_int len;
The parameter p is the location of the bytes, len is the number of bytes in the opaque object. By definition, the actual data contained in the opaque object is not machine portable. XDR library supports discriminated unions. A discriminated union is a C union and an enum_t value that selects an “arm” of the union.
struct xdr_discrim { enum_t value; bool_t (*proc)(); }; bool_t xdr_union(xdrs, dscmp, unp, arms, defaultarm) XDR *xdrs; enum_t *dscmp; char *unp; struct xdr_discrim *arms; bool_t (*defaultarm)(); /* may equal NULL */
First the routine translates the discriminant of the union located at *dscmp. The discriminant is always an enum_t. Next the union located at *unp is translated. The parameter arms (0). If the discriminant is not found in the arms array, then the defaultarm() procedure is called if it is nonnull.}, {__dontcare__, NULL} /* always terminate arms with a NULL xdr_proc */ } bool_t xdr_u_tag(xdrs, utp) XDR *xdrs; struct u_tag *utp; { return(xdr_union(xdrs, &utp->utype, &utp->uval, u_tag_arms, NULL)); }
The routine xdr_gnumbers() was presented record stream is an XDR stream built on top of a record-marking standard that is built on top of the UNIX file or 4.2 BSD connection interface.
#include <rpc/rpc.h> /* xdr is part of rpc */ xdrrec_create(xdrs, sendsize, recvsize, iohandle, readproc, writeproc) XDR *xdrs; u_int sendsize, recvsize; char *iohandle; int (*readproc)(), (*writeproc)();
The routine xdrrec_create() provides an XDR stream interface that allows for a bidirectional, arbitrarily long sequence of records. The contents of the records are meant to be data in XDR form. The stream's primary use is for interfacing RPC to TCP connections. However, it can be used to stream data into or out of normal UNIX files.
The parameter xdrs is similar to the corresponding parameter described previously. The stream does its own data buffering similar to that of standard I/O. The parameters sendsize and recvsize determine the size in bytes of the output and input buffers respectively. If their values are zero (0), then predetermined defaults are used.
When a buffer needs to be filled or flushed, the routine readproc() or writeproc() is called respectively. The usage and behavior of these routines are similar to the UNIX system calls read() and write(). However, the first parameter to each of these routines is the opaque parameter iohandle. The other two parameters, and nbytes and the results, byte count, are identical to the system routines. If xxx() is readproc() or writeproc(), then it has the following form:
/* returns the actual number of bytes transferred. -1 is an error */int xxx(iohandle, buf, len) char *iohandle; char *buf; int nbytes;
The XDR stream provides a means for delimiting records in the byte stream. Abstract data types needed to implement the XDR stream mechanism are discussed in XDR Stream Implementation. The protocol RPC uses to delimit XDR stream records is discussed in Record-Marking Standard.
The primitives that are specific to record streams are:
bool_t xdrrec_endofrecord(xdrs, flushnow) XDR *xdrs; bool_t flushnow; bool_t xdrrec_skiprecord(xdrs) XDR *xdrs; bool_t xdrrec_eof(xdrs) XDR *xdrs;
The routine xdrrec_endofrecord() causes the current outgoing data to be marked as a record. If the parameter flushnow is TRUE, then the stream's writeproc() is called. Otherwise, writeproc() is called when the output buffer is full.
The routine xdrrec_skiprecord() causes an input stream's position to be moved past the current record boundary and onto the beginning of the next record in the stream.
If no more data is in the stream's input buffer, then the routine xdrrec_eof() returns TRUE. That does not mean that no more data is in the underlying file descriptor. | http://docs.oracle.com/cd/E26502_01/html/E35597/xdrnts-7.html | CC-MAIN-2015-35 | refinedweb | 827 | 53.51 |
The Walking Dead EP24: Bursting with Flavor!
Reason the Crawford people are dumb #582:The doctor broke off the deal with Molly because The Authority was keeping close tabs on the medicine supply. So apparently they were keeping careful inventory of insulin? Why? You don’t allow diabetics in the group, remember? By design, your group should never ever need insulin. This is like a nunnery keeping and tracking a supply of condoms. If you’re not going to use the meds yourselves, why not trade it with others? Oh. You don’t trade with outsiders, either. I guess that would be reason #583.
I am kind of frustrated that we can’t get a clear picture of what rules Crawford is operating on. Vernon’s group seem to indicate that Crawford would hunt them all down and kill these otherwise healthy humans because they might die of cancer later. But then Anna’s second conversation with the doctor indicates that she’s free to leave Crawford. Later Molly said they, “Came and took my sister away.” Okaaay. Did they take and kill her, or did they just boot her out of Crawford? Which is it? Is Crawford a bunch of predatory murderers, or are they just elitist and isolationist? This distinction is really important when evaluating their society, and the game doesn’t give us a clear answer.
Having said all that, I think Crawford is plausible enough. They’re a stretch, but historically we’ve seen much worse. If the writers are going to toy with the “Humans are the real monsters” theme, I find it a lot more palatable when they keep the “monsters” outside the party. The stupidity of Crawford was less infuriating to me than the stupidity of teaming up with Lily and Larry and letting them run things.
Also, note how the choices made by players kind of refute the whole “Humans are the real monsters” theme. Looking at the various end-of-episode scores, we see that players overwhelmingly chose the path of mercy whenever it was available to them, even when the game incentivized the path of callous pragmatism. Yes, this took place within the context of a videogame where players didn’t have to personally experience the hunger, pain, sickness, and hardship of Doing The Right Thing, but I think it shows there is enough idealism out there to make Crawford the exception and not the rule in the wasteland.
Far be it for me to try and defend Crawford but I think the IDEA was that they don’t allow people who can’t pull their weight NOW. They are trying to get this Zombie thing under control. Clear their down, build a permanently safe area and THEN start having kids and having medicine to deal with them, etc.
So they are stockpiling supplies for another day. Of course, I have no idea if insulin goes “bad” or anything like it.
Insulin needs to be refrigerated.
And how long does it last when refrigerated? A month? A year?
Either way, if it goes bad, then Molly’s idea to keep using it on the low is about as stupid and Crawford stockpiling it or even taking inventory (it’ll go bad anyways, who cares?).
Molly’s only keeping it on the down-low because of Crawford’s stupid nonsensical policies. It’s not her fault the only shelter in the area was owned by power-hungry dicks.
Right, but if insulin goes bad, what is her plan when all the insulin goes bad?
I don’t think she could have a plan. Where could you ever find refrigerated insulin in a powerless zombie apocalypse?
According to this and some other first page Google results, once it’s opened, insulin should last thirty days, and that’s at room temperature, provided it’s below 30 degrees C. However, that’s just the guideline for the modern world where getting more isn’t exceedingly difficult. Refrigerated it should last for years, whereas at room temperature it will lose about 1% of its potency per month, which would create problems judging dosages, especially considering how hot it can get in Georgia. But you can’t be too picky during the zombie apocalypse, so you just have to do an extra step of maths. But technically speaking, it seems like scavenged insulin could last a couple of years and still be viable in life-or-death situations if you do the maths carefully.
Having a dad who’s a diabetic, I can say that opened insulin past the 30 day point does loss a fair bit of potency and the dosage needed to maintain a healthy blood-sugar level goes up by a few units. Still, the insulin is generally packaged in small bottles with enough to last for slightly more then 30 days of use. So if your incredibly lucky and found a whole shipment of refrigerated unopened insulin then the insulin might last you a few years, but that not the only supplies needed for a diabetic.
Needles would be an issue and while you could probably get by reusing needles a few time, its likely going to increase your chance of catching an infection. Then there’s the testing supplies; the pen needles for drawing blood, test strips to collect the blood, both of which we’ll have to be used at least 2 to 3 times a day and they are not reusable nor commonly carried in pharmacies. You also have to worry about battery power for the measuring device, although if your refrigerating your insulin then power probably isn’t an issue you have. Finally there’s food, because when your low you’ll need sugar fast and post apocalypse that could be a real problem.
Basically, if the apocalypses comes, diabetes is pretty much a death sentence. Still, I’m unaware of any other medical uses for insulin so I’m not sure why Crawford would bother with it nor what the issue would be using it to prolonging her life a little other then Crawford is evil. I mean who are they saving it for, the next diabetic who comes by?
Well, a generator could be used to keep a fridge running fairly well. Would buy some serious time.
Also, and this is crazy talk here, but I’ve yet to see a single one of these post apocalyptic societies take a trip to the library. There’s knowledge there!
Sure, it would take us a while to get there, but the method of creating insulin isn’t lost to use forever. All we need to do is have a working fridge and enough supply until we figure out how to make more. So diabetes certainly makes life difficult but no impossible post Zombies…
Btw, more than chemistry (Napalm would come in HANDY against Zombies) but there’s all sorts of specialized fields that would become REAL useful for every member of an anti zombie society to learn. Agriculture, masonry, metallurgy…
Seriously, forge up a katana and some chain mail? Boom, anti Zombie force. Always surprised no one raids a museum for equipment in zombie scenarios…
I could see people having generators up to run some basic appliances for a while in the apocalypse, but without more fuel being shipped to I imagine they’ll eventually run dry. Still, maybe you do have the capacity to keep insulin properly stored for a few years making it is a whole other story. You’d either need a lab set up to mutate and then grow the insulin producing E. Coli and the proper chemicals to collect it or you’d need to be running a large pig slaughterhouse to collect their pancreases, neither of which seem like a likely set up for early post zombie societies. Then of course the test strips themselves require quite a bit of industry to manufacture. They need both gold and someone to code them to read to the specific glucose meter. Not one of those specializations I’d imagine that would be in high demand come zombies.
Maybe if there wasn’t complete societal collapse and there were large areas and counties that managed to keep the zombies so there’d be enough infrastructure left, but if all that’s left are small settlements like Crawford then I’d say a diabetics time is measured in weeks and months at best.
I don’t know, I get the feeling we’d be setting up farms within a year or two of everything falling apart…
Alrighty, a few issues.
First off, I am diabetic. Speaking from firsthand info here.
The way I do things, I pretty much contradict everything you just said. I don’t refrigerate my insulin (and it’s well past its date at that–the bottle I just pulled from my pocket “expired” July of 2012), I re-use needles 10-12 times before throwing them away (without cleaning with alcohol at that) and I rarely use the glucometer (I have a developed sense for where my blood sugar is, generally good to within 20-30 mg/dL). Despite this, my A1c numbers are always good..
Now, diabetics are funny animals. Many things work for some people and not for others. Because of this, doctors and pharmaceutical companies tend to be VERY conservative in what they tell people to do. Someone less cynical than me might think that they want everyone as healthy as possible, but my experience tells me that it’s 99.9% CYA maneuvers to shift liability to the patient when something goes awry.
The biggest problem for diabetics are: first, supplies–yes, insuling stays good for a few years, but I use a good deal of it, and there’s just no way to produce it without an industry to support it, even extracting from animals would just not be practical.
Second, and more importantly, planning–I know from experience that living on day at a time just does not work as a diabetic. Keeping blood sugars under control requires planning for a general activity level and carbohydrate intake. Any deviation from plan results in extra food consumption or extra insulin consumption at minimum. More likely it will result in either incapacitation at a critical moment (because blood sugar will drop when you are the most active) or dehydration (because the body dumps water when blood sugar is high).
In a world where healthy people these shortcomings are easily enough to kill.
Well I’ll concede to your firsthand knowledge of diabetes. Mine is only observed from family members and actually your usage of needles is more accurate to how my dad does it, I’m not sure why I suggested a needle change would be needed for each injection.
None of those sound very post-apocalyptically useful.
If I had to guess: Herr Dictator/Mayor Uber-Survivalist is, himself, a a diabetic and wants the stuff for himself.
There’s a problem with any plan that involves generators.
And that’s only relevant if you can keep scavenging it. And then that assumes that wherever you were scavenging it from was keeping it under optimal conditions.
Possibly, or Crawford just decided that hey, insulin is medicine therefor well hoard a whole bunch of it for all the healthy people in our hardcore survivalist society that kicks out any sick and weak…
That’s not any smarter. As Shamus said, you’re eventually going to want some young bucks to handle the hard lifting once your bones grow old and cricket-y.
Also, let’s say you raise these children to only allow people who can pull their own weigh. Once YOU get old, say goodbye. After all, the elderly need too much to take care of.
You misunderstand me. I think the plan was to get things settled and THEN start having kids and allowing whoever to stay under any circumstances. The whole “only people who are useful” rule would be a temporary one just while the Zombies are everywhere and running wild.
It’s not exactly a BAD idea per se, just short sighted. I mean, diabetics CAN pull their weight for an example. And if you’re trying to defend an area, sometimes numbers counts for more than quality.
Still, minimizing pregnancies, for example, SHOULD be a priority for at least the first few years. A small society like this, surrounded by enemies on all sides needs every available hand working as opposed to tending to their children.
Of course without the pill, and with condoms growing more and more useless by the minute, forced abortions are pretty much the only way to go. Which would probably alienate a lot of people and cause them to leave ANYWAYS, which costs you the manpower you were trying to keep in the first place.
The more I think about it, the more Crawford sounds like a commentary on libertarianism.
I’m curious how you reach that conclusion. Isn’t the primary principle of libertarian-ism just let people do their thing and all will be well? Seems like the opposite of the dictatorship to me.
Not, you know, textbook libertarianism, but real-world, fuck-you-got-mine “libertarianism” where long-term consequences are ignored for short-term gains.
Nice strawman you got there.
Got any examples to the contrary?
(serious question, I can’t think of any)
This doesn’t follow.
You can argue that Libertarianism would lead to some sort of cutthroat Darwinian dystopia. However, this society wasn’t run by or devised by anyone who espoused individual freedom. The people rallied around a supreme leader right from the start, and it’s never hinted that they ever considered anything else.
It’s like if a bunch of religious nuts began killing people and I argued that, “See, this shows the atheism is bad because atheists always kill people the way these religious nuts killed people.” It’s not even a strawman. It’s an own-goal reverse strawman.
This is not to say that there isn’t room to criticize LT ideas, but if that’s what they were aiming for in this story they missed so bad they ended up making the opposite point.
A proper critique of LT ideas would be something like:
Larry the asshole leaves Crawford to go scavving. He shoots off his firearms and ends up attracting a lot of zeds. Then he retreats back behind the wall and leaves the guards to deal with the mob. He doesn’t share the supplies he gets, but he leaves a bunch of danger for everyone else to deal with. When confronted, he argues that, “You can’t tell me what to do! I’m free to come and go as I please!”
Add a few people like that together and NOW you’ve got a proper thought experiment on what might happen when individual liberty runs against the common good.
The problem you have there is people like, say, Ron Paul saying they oppose the Civil Rights Act, and in particular the ban on refusing service based on a person’s race, purely because it’s an affront to the business owner’s liberty, just like not allowing the leader of the Crawford settlement to make rules about mandatory abortions would technically be abridging his right to govern as he sees fit.
We can argue past each over about what Libertarianism is supposed to be in the ideal versus the truly horrifying shit Libertarians actually say they stand for on specific issues, but I think the decisions people who identify as Libertarian make are more important than their rhetoric.
… I’m sorry, what? How on earth are people going to know what you mean by ‘libertarian’ (other than people you dislike, apparently) unless you use the commonly accepted definition of what that is?
Freedom is an interesting concept, and I do like the treatment Pratchett gives it in the discworld novels – freedom is yours, but you have to accept the consequences of the actions that you are free to take.
I judge Libertarian by what people who call themselves Libertarian actively promote through their actions, because the idea that Libertarianism can be isolated and examined separately from the behaviour of Libertarians just results in No True Scotsman rubbish.
But. . .it CAN be isolated and examined separately. There is no ideal under the sun that hasn’t been abused by it’s adherents, and attacking an idea solely (note I said SOLELY) on that premise is insufficient to condemn it as an ideal. Perhaps it’s merely an ideal that is poorly represented or implemented at a given point in history.
Or it may be one that is fundamentally flawed (for example ignoring human nature), in which case it should be attacked and dismantled by presenting arguments from that direction.
It could be a strawman shared by the writers.
Yep, cause people who hold individual liberty as their most important value just love a society run by a single authoritarian leader who imposes strict behavioural rules.
Crawford is the very picture of “powerful leader dictates the sacrifices that everyone must make for the common good.” The idea of a forced abortion in a libertarian society is ludicrous. Libertarianism is usually criticized as “Do whatever you like, as long as you don’t infringe on the lives or property of others”. This is the OPPOSITE of that.
If you wanted to critique Libertarianism, then you’d probably go for themes of “tragedy of the commons” or selfishness.
I have no problem with the idea of a Libertarian saying that a condition of living in “his” settlement is mandatory abortions and leaving is perfectly in-keeping with Libertarianism, since the common response to question about how we’ll ensure decent working and living conditions in a Libertarian society is that we’ll just “go elsewhere” if it’s rough and that “the market will provide”. I’m just glad most Libertarians are an ocean away from me and my loved ones.
This is getting dangerously political.
One thing that I’ve just thought of: This abortion would be being carried out in a Nurse’s Office. That’s barely a step away from a backy alley abortion, so the fatality rate is going to be pretty high. Not to mention (spoilered for creepy as fuck)
the issue of whether the dead foetus turns, though I suppose an induced labour followed by smashing it’s head in would work if it’s late enough to barely survive, but I’m freaked just thinking about that so the idea that someone would actually think that was a good idea to inflict on a pregnant woman is mind-numbing.
“I have no problem with the idea of a Libertarian saying that a condition of living in “his” settlement is mandatory abortions and leaving is perfectly in-keeping with Libertarianism, ”
Such a thing would be an anathema to a Libertarian. That’s fine. I don’t care what you believe about the set of ideas, but this is isn’t just a misconception, this is an inversion of the ideas they espouse and cherish.
The problem there is that you have Libertarians saying precisely that people should be allowed to make such decisions on behalf of those they have power over, such as Ron Paul saying Roe v Wade should be repealed and abortion should be regulated or banned, and Bob Barr, 2008 Libertarian Presidential candidate, calling abortion murder and supporting its criminalisation.
So saying Libertarians don’t support societies being able to make truly odious rules that restrict individual liberties is simply counter-factual when the people they choose as their pick to run America support just that. If it was anathema to them, they’d have drummed these people out, not picked them to run the show.
The ideas can be whatever the Libertarians want them to be, their actions and their choices are unambiguous and frightening and I see no evidence that Libertarianism isn’t exactly as bad as I’ve been lead to believe by the words coming out of their mouths.
I don’t mean to make a straw man of your argument, but doesn’t it boil down to:
1) libertarian means X
2) game has society with rules Opposite-of-X
3) game does not mention libertarian ideology
4) some libertarians are hypocrites
therefore, game is a commentary on libertarianism
?
It would be one thing if we reversed proposition #3: if the leader actively espoused libertarian rhetoric, there might be a way to reach the conclusion. But… unless I’ve made a hash of your argument, I’m not seeing it.
(I would also like to note: Crawford has communal (state controlled, in this case) property, which is so anathema to libertarians that I don’t expect you can find even political hypocrites espousing it – so even if you can conclude the rules on dealing with sick people are compatible with libertarianism as practiced (though certainly not as defined) – you still have a long way to go to Crawford = Galt’s Gulch)
That was Zerotime’s argument. My argument is simply that a Libertarian society, based on the shit Libertarians say, would enable and support people wanting to make those kinds of rules, contrary to the idea that Libertarians are somehow viscerally opposed to such restrictions on individual liberty when they seem so happy to cast their votes in favour of just such restrictions on a persons bodily autonomy and put forward candidates espousing it.
Then this episode isn’t a deconstruction of Libertarianism, it’s simply revealing your own ignorance and prejudice against people who hold certain ideas.
Ron Paul is a Rebublican, famous for being the “most libertarian” of the Republicans. Check the various Libertarian think-tanks. (I know there are a bunch, but Reason Online is the only one I know off the top of my head. Maybe Cato?) In my reading, I’ve found them to be: Pro-choice, anti-war, open-borders, anti-drug prohibition, generally not very religious, perhaps trending slightly towards atheism. Ron Paul isn’t a Libertarian, and his stance on abortion is one of the very key issues where he differs from Libertarians. It would be like me saying that I dislike Democrats because Roosevelt enacted internment camps, ignoring how much actual Democrats hate the policy.
This is why I let this conversation roll as long as it has. This is something that breaks my heart: “Other people are all evil.”
I read Libertarians, and they say “communists all want to take our freedoms and rule over us and turn this country into Soviet Russia!”
I read Communists and they say, “Libertarians just want the old and poor to starve!”
I know Libertarins. I know Communists. I know Democrats and Republicans. Furthermore, I read blogs written by all of the above. Without exception, they are all decent people who genuinely don’t wish harm on others and who believe that their views and policies would make for the best possible society.
I don’t care what you believe or how you vote, but I beg you: Realize the “other guy” isn’t a monster or a villain. He’s YOU, working with with a different set of information.
Actually Shamus, THIS IS EXACTLY WHY YOU BAN POLITICS ON THIS SITE.
You get too upset, it doesn’t change anyone’s mind, and it doesn’t have anything to do with why people visit the site.
Damnit, you’re right again.
Shamus, you should probably listen to this Shamus dude more often. He seems pretty bright.
Yeah. As much as I love talking about politics, I dislike mixing them with my Happy Fun Times.
I tell you this Shamus dude is a smart guy for not mixing politics with gaming.
Unless of course you yourself are a monster. In which case, take solidarity in all of us being monsters together ^_^
So I’m starting to think you should run for office Shamus…
Yes, it’s good to remember that other people aren’t intrinsically evil. I’m a bisexual and an atheist, and I’ve had to deal with plenty of shit because of both of those things, as have people close to me, and I also have experience of people with poor opinions of people like me being turned around by just being generally excellent to them.
I’ve been getting a little mad and I’m not really coherent enough at this point to make any further comments so I’m gonna call it a night.
Having been a pretty active participant in the circles one would generally describe as Libertarian, I feel pretty confident saying you’re wrong in this. It doesn’t violate the “Non-Agression Principle” to threaten to turn someone out to a near-certain death on a certain condition. Sure, not all of them would agree, but there would be those who would make such a case.
This is to say nothing of the fact that Crawford regularly engages in the looting of other people’s property. Not to mention that they apparently abduct people from said property as well (some of the numbers on the door symbols indicates healthy/non-healthy people). Most libertarians aren’t exactly fans of theft and drafting.
I don’t know where you’re getting the thing about “drafting” from. Crawford doesn’t seem like the kind of place to try literally taking slaves—in the middle of the apocalypse, and with the rules about each citizen having to earn their keep? The diagrams with numbers I thought were supposed to communicate each citizen’s contribution to Crawford (ineligible people found (and killed?), eligible citizens brought to Crawford, and Walkers killed). As for the looting: the vast majority of it is dead people’s property, and is therefore nobody’s. So there’s plenty about Crawford that fits within libertarian ideology, broadly speaking.
Impaling the “unfit” on spikes at the barricade as a warning is a definite no-no, though.
There is a case to be made that Crawford is a critique of Libertarian and/or Right-wing ideologies by the authors. For instance, when you meet Molly she refers to its policy as “survival of the fittest,” a phrase associated both with evolution and, more intimately, with the idea of Social Darwinism. Later, in her videotaped conversation with the doctor, the doctor says
To which Molly replies:
Again, it’s not explicit Libertarianism, and most Libertarians wouldn’t agree with Crawford, but I think the game is putting forth the argument that certain values will lead to this kind of behavior in such extreme situations.
Edit: This was partly a response to silver Harloe below. I should have split this in two.
It’s the wording on the note that makes me think it was abduction. It reads “number of people brought back to Crawford” rather then something like “number of people who choose Crawford” or anything that indicates choice in the matter.
The fact that there is no one who seems to be living outside of Crawford (besides the cancer survivors) seems to also indicate force. I’m sure there would be plenty of people unwilling to go to their town after hearing about it or seeing their zombie wall, especially if they had ineligible family members or friends.
Crawford is not a political commentary on anything, and it’s so broad you could honestly use its positions to justify criticism of any belief. A libertarian, for example, might see it as a commentary on the effect of statism on individual morality, as Oberson has installed a despotic regime that enforces strict laws that directly influence individual morality and shift it away from non-aggression. This is an argument that libertarians regularly use in regards to how the American government has normalized atrocities in their foreign policy through propaganda. Nitpicking little bits of quasi-political remarks is purely interpretative.
“I have no problem with the idea of a Libertarian saying that a condition of living in “his” settlement is mandatory abortions…”
Nevertheless, you can’t approach a game which includes one society and conclude the society is libertarian BECAUSE it’s a dictatorship with communal property and a big list of things you don’t have a right to do or be — everything about Crawford is exactly opposite of libertarian.
IF the game had specifically brought it up as something said dictator espouses (if those posters with the rules said: “there are no rules. do what you want. but if you want to stay in MY house, you better not be too young, too old, sick, etc”) — then you might conclude it’s a commentary on libertarianism (though I’d still argue that’s a stretch since we aren’t shown the parts where people had those freedoms and didn’t choose the asshat extra rules) — but as it is, the only evidence here suggests the commentary is on short-sighted survivalists with a fetish for total control (themselves probably straw men of real survivalists).
If this is a commentary on libertarianism then the ringing of the church bells by Molly was a commentary on religion.
It’s an absurd argument that ignores the fundamentals of what those words actually mean.
Oh, let me try.
Lilly is a commentary on Nazis and how they were bad. Larry was a commentary on how Bioware seems to write every character with some form of daddy issues.
“”Also, let’s say you raise these children to only allow people who can pull their own weigh. Once YOU get old, say goodbye. After all, the elderly need too much to take care of.””
then you get Little Lamplight, and cuftburt will have to kill every living thing in it, ‘cus seriously Little Lamplight is worse then The Fade, at least The Fade had deamons
Now Crawford is being truly evil. In the end, his goal was to create Little Lamplight.
“Also, let’s say you raise these children to only allow people who can pull their own weigh. Once YOU get old, say goodbye. After all, the elderly need too much to take care of.”
Well,a true altruist would embrace such a life.”Once I get too old son,shoot me in the head and burn my corpse.”Such a society would actually do very well in a post-apocalyptic world.The problem is,very few people in our world would think like that.
How do you do that, when anyone living is a potential future zombie?
Oh, I know! By killing everyone who’s still alive, or throwing them out before they turn. Looks like Crawford were on the right path.
Btw, on the subject of player morality, I hate sounding like a broken record, but I think this is another result of not having consequences to your actions.
All things being the same, people will generally pick the “good” choice. But if things WEREN’T the same, if players genuinely thought their well being, or the well being of Clem, were on the line, I think their choices might have been a bit more varied.
I think so too. Odds are most people had their illusion of choice shattered after Episode 3. Once that happened, the choices no longer had any weight to them.
Right.
Also killing Ben doesn’t work very well as a “hardcore survivalist” choice because it doesn’t actually help you survive in any way…
Nothing helps you survive in any way nor does it help anyone survive. If the game wants to kill off a cast member, it will do it no matter how needless or stupid.
If Ben came back as a zombie, would that mean that he could make the stupidest possible choices for them instead? Seems like that would be a pretty huge net gain.
“Ben, this is hard for me to ask of you, but it’s for the good of the group. We need you to help the zombies now.”
signed, Everyone
This. I might have let Ben fall if saving him would have a negative effect, but I know that the zombies aren’t going to catch me if I save him because there’s still one more episode.
It does because it takes less time than pulling him up, and we’re being rushed by zombies.
A lot of people didn’t kill Larry or both St. Johns, though, even though a lot of people still believed in the choices then – and those choices were further along the “monster” spectrum (with the exception of killing Ben).
That being said, I think a few videos of the monstrosities committed in history argue – not so much that humans are monsters – but that the ones who aren’t will be murdered very quickly.
But that’s the point. Not killing Larry doesn’t hurt you, killing Larry doesn’t help you. There is no difference. It doesn’t affect the player in any way.
So people make a decision based on right and wrong as opposed to survival instinct.
Most people killed the first Saint Johns Brother out of anger and let the second live because Clem ninja’ed in. I wonder, if players had a reason to genuinely believe that either of the brothers may come back to haunt them, or endanger Clementine if they would be so quick to appease her morality.
Why wouldn’t they? Back in episode two the illusion hadn’t been broken for most people – the St. Johns certainly had the potential to come back and bite you.
I dunno… I was pretty certain that the brothers were never coming back to the game at that point. But I guess it’s possible some people didn’t.
To be fair, I was playing without the UI, which might help dispel their illusion…
Do you mean that the UI helps preserve the illusion, or helps dispel it?
(Mainly the UI notifications are there to just fuck with you :/ )
Yes, I do believe the UI helps keep up the illusion. I had them off, so I may have had an easier time dispelling it than most because of it.
FWIW, I knew about the illusion from the beginning, and knew that /of course/ no one was in any actual danger, but in Episode 2 I still killed Larry because the scene was excellent enough to present the *perception* of danger. Even though I knew Clem wasn’t in danger via the game’s story, I thought that she was via /the presented situation/. A sort of application of doublethink, perhaps, but I have no problem with that – it’s how I view immersion.
Except when it comes to the first choice of Episode 3. Most people left the woman to be eaten so they could have more time. Using the percentages shown in the image on episode 18 of SW has it at 59% those leaving her to be eaten alive.
The one choice in the game that you a given a clear benefit for being “evil,” early enough for players not to be certain it won’t matter, and people picked “evil.” I feel it proves my point more than hurts it.
This is an excellent point.
And as you said in another comment: The morality would be even more interesting if it mattered more.
I killed both St. Johns. When I killed the second brother, my main thought was, “If I let this guy live he might try to hunt us down later.” Of course, my other thought was, “It wouldn’t be right for me to leave this guy to eat OTHER innocent people.” So the message is kind of muddled here.
Then there’s taking the supplies at the end of Ep 2. I didn’t touch them, because I felt like we were stealing. (If we waited a bit and nobody came back, then we would have just been “looting”.) This is another spot where “evil” has benefit, but the “evil” is kind of ambiguous, and so is the benefit.
Still, it would be interesting to see how the numbers would work out if they offered the player, “Would you harm or steal from a non-threatening third party to help Clementine?”
The game-makers are faced with an interesting problem. They have no way to program in all the multitude of variables and ideas people have (the car choice at the end of episode 2 is the biggest most jarring example). They have no way of knowing the player’s logic when making a decision. If the player is forced to make a decision they don’t want and is punished, they get angry. If the player sees a smarter way out that isn’t evil, but can’t take it, and is punished, they get angry. If the player thinks their choice ought to work, but it doesn’t for some arbitrary reason, thy get angry.
If the ruthless but practical choice always resulted in the better outcome, then throwing on “but AT WHAT COST” feels stupid and hollow, because you clearly did the right thing! There’s few ways to have the evil side turn out better without inadvertently advocating evil. On the flip side, if being evil only sometimes turned out better, it feels just as arbitrary as it not mattering at all.
Not to say there’s no way to do it – but I have the feeling the Walking Dead creators intended the illusion of choice to be a part of what they were saying. Lee even straight up says it in the first episode: “You think you have a choice. But when you look back at it, you really didn’t.”
I think the main problem with punishing evil while making it plausibly rewarding is that you need some kind of reputation system to make it work. For example, if you’re perfectly happy to rob people, leave strangers to die so you can get away, then you get to keep everything you loot or steal but you’ll never be able to trade with anyone or get medical help or basically get any advantage that depends on people trusting you not to slit their throats for a tin of beans. You might be forced to go around fortified areas, or try to sneak past hostile patrols that rightly view as a threat.
But it’s difficult to have a truly universal reputation system that doesn’t devolve into either people complaining there’s an unrealistic omniscience judging them, people complaining that everybody seems to have a hive mind(could be interesting if you could try to start over/fall from grace and have your rep catch up with you), or people noting that the morality system doesn’t have a lot of teeth when it doesn’t track what you do alone in the dark.
In THIS game? You guys are thinking too hard.
Bad thing about picking the good choice? Clem suffers.
Bad thing about picking the bad choice? Clem hates you.
NOW you can test someone’s moral fiber.
Doesn’t have to be EVERY choice, but have a few with varying levels of suffering and hatred and I’ll bet those split would be a LOT more even.
^ Above are the words of a very smart person
Seriously there would have been no message more interesting if you’d done all these hard horrible things to help Clem survive and then you turn around at the end of the game unhappy with what you’ve had to do, but glad that you did for Clem – and then you see that she’s been completely destroyed mentally.
Although a problem with this whole line of conversation is we’re dividing choices up into good and evil, when actually I believe almost 100% of people were choosing the ‘good’ choice in this game and just disagreed on what that was. The women was already dead, by sacrificing a few minutes of pain before death you have the opportunity of feeding your friends and family for a few more days. You exposing Clem to evil, but if she’s going to survive in this world, then her innocence can’t.
The ultimate proof that there is good in people, is almost everyone playing this game had empathy for Clem and were willing to do everything possible, including possibly getting blood on their hand to help another person and give that person a chance to live
The indy game
Ijidoes something like this. You can play it like any other side-scroller and win, but by the end Iji’s a bitter survivor who hasn’t really come to terms with what she’s lost. Or you can take the more difficult approach by not going out of your way to kill every enemy in your path, and getting a less Pyrrhic victory.
“The ultimate proof that there is good in people, is almost everyone playing this game had empathy for Clem”
Not really. Having empathy for people within your inner circle is easy – what defines you is how you treat outsiders.
I heard good things about Iji, tried to play it but I couldn’t quite stick through.
As far as your last things goes, then we all fail miserably. I don’t actually believe humans are good people, if aliens were to visit our planet I could imagine a scenario where they thworple with disgust at the fact we continually priortise things like nice looking carpets, shoes, pictures, games over people dying miserably of starvation. You can practically count the number of people on one hand who’ve had genuine empathy for other people.
But we’re not all bad either, Clem is helpless, unrelated and non-useful and we’re willing to prioritise her over even ourselves.
A bit of hell a touch of heaven. Overall the balance probably falls the wrong way but we’ve got something to try and improve and work on at least and our minds wouldn’t be able to handle dealing with the negative
I hardly considered sparing the St Johns to be a “good” or “merciful” choice :/
Their mum got Mark’s-Revenge’d, the first was crippled in a bear trap, the second beaten to a pulp, and it was pretty clear that storm + zombies were coming to wreck their shit even more. They were already effectively dealt with. ‘Sparing’ them was really just walking away because I didn’t want to waste any more thought on them, letting them be killed on the walker’s time, not Lee’s :/
And I very definitely told Clem afterwards that they likely got walker’d, which is worse than death.
Clem is kind of the game’s moral barometer and she sees killing them as “bad.”
I really dislike that they did that. Why would you get someone choose not to kill someone and then reward them with a shot of those people getting zombied?
I was trying to be nice and I ended up being the most hilariously sadistic person possible. First I attacked the one brother, let him get scythed in the shoulder and then left him to be eaten by zombies, then I killed their mother. Then I went outside, bit the crud out of the third brother, lied to him that his whole family was dead so he could spend his last few minutes in mental agony as well as physical agony and then refused to give him the respect or end he craved as I walked away, calmly ignoring his screams as the zombies came to eat his sobbing form.
I couldn’t have been more evil if I was actively trying to hurt them
Bwahaha. See, I liked it zooming out.
[Insert 'newdarkcloud calling me #YOUMONSTER' here.]
I don’t think it needs to be said. XD
No one knew before they made the decision which ones would give a benefit and which ones wouldn’t. Saying people picked the evil choice that gives a benefit doesn’t mean anything – they didn’t know it would matter any more than they knew Larry or the St. Johns would matter.
Actually, the shoot the girl thing is the one choice where the consequence is telegraphed: Kenny flat out tells you, if we leave her out screaming she will keep them off our backs.
Consider, the St. John brothers killed someone you know, tried to kill you and Clem and everyone in the group. Their bear trap killed two other people and got you stuck with Ben and their trap caused Larry’s heart attack. They are evil, a nuisance, and the most antagonistic characters in the game. And the grand majority of people spared one of them!
Meanwhile we have this lone, innocent woman being slowly tortured to death. And the same people who spared Andy decided to leave her to one of the most painful deaths imaginable (slowly eaten alive).
In any more compass, Andy deserves death more than she deserves to be tortured. And yet, most people spared one and not the other. Think about that for a second…
To be fair, I spared the girl because I didn’t think it was my place to go around saying “Whelp, you’re bit, I guess I’ll just shoot you.” I admit that’s not the way the game framed it, but I just didn’t feel right about making that kind of decision.
And later, after I thought about it, I think I feel okay with this call, even if it did result in a bad outcome in this situation. Maybe she was in the middle of saving her own “Clem”, and I’m ending her quest before her charge is safe? It’s reasonable to assume she’s with a group, and that group might show up at any time, and that group might not see me shooting her as a humanitarian thing to do. Maybe she was on her way to deliver some crucial message that would help others. Maybe there are people who would like to say goodbye to her. She deserved her chance to get away from the zombies and finish up with her life.
It would be one thing if she was screaming to be mercy-killed. THEN it would be a tough call for me. But I wouldn’t feel right about deciding to end a stranger’s life because I presume to know when they should live or die.
Having said all that – it was a VERY interesting choice, and I’m thinking you’re onto something here. Unlike the choice to help the suicidal girl in Episode 1, this is a decision where you have a stake in the outcome, which makes it more potent.
You do have a tendency to make non game decisions in games. You look at the situation outside of the game and come up with a gajillion scenarios. This isn’t how most people look at these things.
And, well, to be fair. Looking at your conversations on the suicide girl, I’m gonna go off on a limb and say that euthanasia isn’t a concept you are super comfortable doing. So probably not easy to see it as the “right” choice when possible to look at it another way.
In the game’s defense though, it DOES frame the situation as clearly as it can without completely dispelling immersion. None of the characters ever even mention the idea that maybe, just maybe, she could be saved (btw, we’ve fought more Zombies than were there. We were armed. No one even THOUGHT about it?!?) and the game does make you hear her scream in pain as you rummage through things to drive the point home.
So while I can accept that some of that percentage didn’t TAKE it as the “evil” choice, I think most people did.
And this is one of those things where the game almost gets it. I would truly love a game that would make players genuinely question their morals and have no true right answers.
Imagine if being completely “hardcore survivalist” keeps Clem super safe, but she hates your guts, so she doesn’t listen to your advice which causes her to be put in danger later since she defies you and refuses to touch a gun? But if you are super good Clem is put in danger and suffers NOW, even if she listens and is ready for the dangerous stuff later.
Now we have a situation where players aren’t simply stacking the good options for good endings then replaying with bad choices for bad endings, but genuinely weighing their options. This gets extra interesting when all the consequences AREN’T clearly known and understood.
And the fun part about consequences is that you don’t NEED every choice to have a serious, important, major consequence. But if you even have SOME, now the player simply doesn’t know. Especially if one or two have long reaching consequences (have a seemingly meaningless choice in chapter 1 have a consequence in 2) and now the player is ALWAYS wondering which choices matter and which don’t and seriously considering each one, even when they DON’T matter.
I do have some things to say on this choice/consequence thing, but I’ve been holding back (yes, this is my holding back. Sue me =P) for the final chapter because I don’t feel like striking every god damned line on the post. But I do think it’s the largest, most glaring flaw in this game and I don’t believe it deserves all the game of the year awards it got because of it. I fear the sequel will be the same damned thing because I’ve yet to see a critic complain about it in any major way.
I am, but your argument keeps contradicting itself. You say that the tortured girl is indicative of people’s morality, because it was beneficial. But Larry and the St. Johns aren’t (even when those two were earlier in the game, and thus more likely to have the illusion of choice intact), because it’s not beneficial. Except you don’t know which will be beneficial until after you make the choice. That argument only works if you assumed everyone looked on Gamefaqs and knew ahead of time which decisions would matter – or that they were “obvious” to everyone because they were obvious to you.
It’s how the situation is framed. Larry and the brother’s it’s framed as a morality choice: What do you think is right?
With the girl, the game flat out tells you what happens. Lee mentions how much she will suffer and Kenny points out her screams will keep the Zombies away from you. The game gives you a clear cut good/evil choice (well, their definitions of good and evil) and then gives you a reward/punishment for said choice (if you’re good, you get less supplies).
Note that all three situations are completely choiceless. Larry always dies, the brothers are never seen again, the amount of supplies are irrelevant. But with the girl, the game flat out tells you that you will gain something for letting her suffer. And this is the one choice where the “evil” side outweighs the “good” side.
I don’t see this as coincidence.
I cannot agree that Larry was a morality choice. One option is clearly bad – even Kenny is shocked by it – and almost everyone who said they killed him did so because it provided the illusion of benefit (the removal of a threat).
Consider the tortured woman:
-I shot her because I was aiming for the zombies on her and the game killed her instead.
-Shamus didn’t kill her because he didn’t think it was his place.
-Josh on SW didn’t shoot her because they hesitated too long and the game defaulted to “don’t shoot”.
-Some people didn’t fire because you’re not just endangering yourself, you’re endangering Kenny, who was shot and clearly had trouble walking a few minutes earlier – he can’t run, so that’s just as cruel a move as letting the girl suffer.
-Some people didn’t fire because they agreed with Kenny.
-Some people didn’t fire because they felt the situation was contrived and were pissed off.
If you want to argue people are evil, we have scientific studies for it, but I think your arguing the game shows it requires everyone to see the choices the way you did and think the same things you did.
But the game doesn’t frame it as a cost benefit, it frames it as a Lily versus Kenny thing. Kenny argues it is hopeless, Lily argues it isn’t, the player chooses who to believe. If Kenny is right then his course of action is right and Lily’s course of action will harm you, if Lily is right then HER course of action is right and Kenny’s course of action will harm you.
It isn’t “what helps me more?” it is “Who do I believe?” People sided with Kenny because they thought there was no way to revive Larry, people sided with Lily because they thought they COULD revive Larry. In both scenarios the player never believes he is in danger. Both sides here knee jerked into the “good” choice for different reasons.
The girl is different. The game gives you very clear instructions. Do a bad thing for gain, or do a good thing at a cost. And most people took the gain, knowing the was the “evil” choice. Not overwhelmingly so, but more than any other choice in the game.
And my argument isn’t that people are evil. It’s that it’s easy to be good when it doesn’t hurt you. When it DOES, people think twice about it…
But in order for that argument to work, you have to argue that everyone saw the framing exactly as you did, everyone saw the cost/benefit of the choices exactly as you did, and everyone saw right and wrong exactly as you did.
You shot the girl because you thought it was the more moral course. Shamus didn’t shoot the girl because he felt that was the more moral course. Arguing that the majority took the evil route is putting words in the mouth of everyone who played – or worse, doing so off a misleading statistic. Recall how many players “sided” with Larry without meaning to, or somehow lied to Hershal despite their best efforts.
Sure, there are ambiguities in these choices, but wouldn’t that happen in ALL of them? You could reason (and some people have) that killing St John brothers was a mercy and leaving them alive was the worst. And yet most people left them alive (what the game considers the “good” choice).
We aren’t talking about individuals here, we are talking about the aggregate. Not EVERY SINGLE PERSON who made these choices made them for the reasons the developer wanted.
But it is interesting that despite all the myriad of ways you can look at it, every choice in the game had more people leaning towards “good” than “bad” except the ONE choice where they are given something in return for being “bad”…
What about Lily? Most people didn’t leave her, and they were punished for it (she stole the RV). The RV doesn’t matter, but neither do the supplies.
You keep arguing based on the outcome of the decisions, which were obvious to you, but not everyone else.
But the game doesn’t telegraph that keeping Lily would punish you nor that helping Lily would help you.
None of the straight “moral” choices telegraph any advantageous or disadvantageous outcome for you EXCEPT the girl. And that’s the ONE choice that people picked the “immoral” choice the most.
First off, you’re wrong, because most people stole from the car.
Second off, you keep arguing off a telegraphed choice that, post facto, turns out to actually give a game mechanic benefit. But people made other decisions based off something they thought would give a benefit, it just turns out they didn’t. You immediately say they didn’t count because you think they weren’t telegraphed. Other people thought they were, they just turned out to be wrong.
I think you are overfocusing on a single decision, because only that decision had any proof positive consequence after it was made. But that means nothing. Your argument boils down to “only this decision fits my criteria, so its the only one that counts.” I could name any other decision in the game, and it won’t matter because no other decision actually gave any benefit whatsoever.
You’re arguing off a self-picked sample size of one.
You know I had this whole long post about it but… I’m looking at the stats they released and 60% of people SHOT the girl. Players DID take the choice that hurts them because it was “good.”
“-Josh on SW didn’t shoot her because they hesitated too long and the game defaulted to “don’t shoot”.”
That’s what happened to me too. (Though less ‘hesitated’ and more ‘I’m trying to aim at you, quit running around’ because I had no idea if aiming mattered :/ (Apparently it doesn’t.))
I spared the screaming woman in episode 3 because I thought “what if I miss?” She’s gotta be at least 20 yards away. This isn’t like Halo where you have a reticle in the scope and the bullets travel in a perfect straight line ignoring gun pull, wind, and human instability. Headshots are not easy to make. The woman is clearly in a bad spot- surrounded, maybe bitten already- but maybe she’s clean and will find an opening to escape. If I shoot her in the hip, she will DEFINITELY be eaten to death by zombies.
This could go the other direction, too. There are no consequences, so why not be evil.
You know, the Cuftburt approach.
On the larger point, Spock always had the best answer to how people will respond in stressful situations: “Each according to his own abilities.” Most people can be evil, most people can be good -some people are personally so driven to one side or the other, but not many -and it depends on the circumstances and surroundings.
But Cuftburt wasn’t their first playthrough.
People forget that Josh actively plays chaotic stupid for the sake of entertaining us.
Most players will see the “good” ending first, and “evil” ending second. It’s just one of those things, if all things are the same, people will stay “moral.” You can thank Saturday morning cartoons for that.
You want to test someone’s morality you gotta give them an incentive. How much will you suffer to be good? How much of your morality will you give up for your safety? For your family’s safety? Is your honor more important than your daughter’s life?
It’s easy to be moral when the choice is simply “do you want to be good or bad?” It’s harder when it’s “will you kill an innocent to save someone you love? Two? Three? Where do you stop? DO you stop?”
Day Z is a pretty good counterexample in terms of the “Humans are the real monsters” argument, I’d say, though it suffers from the ” it’s a video game, there are no consequences” syndrome the other way round.
How exactly is it a counterexample? Helping or meeting other people has no actual gameplay benefits and only exposes you to the possibility of getting killed because the other guy might want your stuff, prompting everybody to preemptively shoot on sight assuming they’re not just bored and griefing others already.
I like the idea of DayZ and I’m sure someday someone will make a really good game using similar mechanics, but DayZ itself is essentially a really slow, boring game of ARMA Free-For-All with some crappy survival mechanics tacked onto it. I’ll go as far as to say, there isn’t even that much to purely like about DayZ, people just never tried ARMA2 and its mods then collectively went ‘HEY I REALLY LIKE HOW HARSH AND UNFORGIVING THOSE MECHANICS ARE!’.
Blunder Boy Ben is at it again. If he’s not sabotaging your chances by removing conspicuously placed hatchets, he’s doing it by confessing to Kenny at the absolute worst possible time.
I really wish Ben wasn’t such a liability. I get that’s 18 and inexperienced and likely I’d be the same way, but come on can they make him at least do something right.
“Huge Fuck Up” isn’t a particularly endearing personality trait in a zombie apocalypse.
The trouble is everyone in your group has been a liability and done really stupid things – from sabotaging the electric fence keeping your own group safe (which accomplished nothing, because Lee did nothing about what he found), only having one guard up when we know there are bandits trying to kill us (its the only way Ben could have sold us out without anyone knowing), from Kenny and Lily having no plan and fighting over it constantly, Duck running over and killing someone else’s kid, and yes, even Clementine (who could have easily run after Ben, because they were both in the same cloud of zombies, and that whole “Oh yeah a guy has been stalking us for a week and I didn’t tell you.”)
This could all have been averted by Lee putting a hand over Ben’s mouth or punching him.
But aside from Duck, none of these have consequences except in the most nebulous fashion. And both the teleporting bandits and the axe are so contrived that, at this moment, you realize that Ben is no more incompetent than anyone else – he’s just unlucky and the writers are hamhandedly out to get him. Which is a shame, because right up until this point he was a great character for what they were trying to accomplish. His screw ups were grey and partially caused by our antagonistic group dynamic. Now it’s just stupid. A great big black hole of stupid that is pretty much the worst part of the entire game.
Unless you don’t save him, really, at which point you get to see
Kennny die over a walky-talky you didn’t need.
This makes me a lot more sympathetic to Ben. Seriously, everyone else walks past that door, and it’s blatently obvious that there are zombies on the other side.
Ben walks by, the zombies take a powder just long enough for him to take the hatchet and talk to Lee.
And then the zombies break through just as he realizes his mistake.
God hates him (well, the writers).
Yeah no, I get relating to and sympathizing with Ben but that should not lead to pretending he’s better than he is. Ben consistently makes poor decisions and in critical situations either does nothing or makes them even worse. Other group members make mistakes, but generally even Kenny and Lilly are trying to help in the really life or death situations.
You compare him to Clementine and Duck, but they’re half his age. Of course as has been discussed here whether you find Ben sympathetic or not depends on whether you view him as an adult or a child. In my view adolescence and teenager’s being useless are modern inventions of a society that can afford to treat teenagers with kid gloves. A zombie apocalypse can’t afford that same leniency. Further if you want to compare him to Clementine then Clementine comes out clearly ahead, as she always tries to help when she can and when forced to grow up by the apocalypse does learn to shoot and to help out the group, why can’t Ben?
What I found disappointing about Ben was not his mistakes, but how he didn’t seem to try and stop making them. Just listen to his dialogue in this episode for an example, where you tell him not to tell kenny right now, effectively telling him to behave with maturity and put survival ahead of his own emotions, his response is just “fuck you man.” That’s Ben’s response to everything, he rationalizes and justifies and wallows in his own immaturity. You have a point that the authors conspire against him in some ways, but his reactions as a character are still his own failings.
I didn’t hate him though, and I would still have saved him despite all that, but then he told me to let go and I respected his decision, and frankly agreed with him that it was the most good he could do, which is admittedly a horrible thing to think. So maybe I’m the real monster.
Consistently? He made a deal with bandits which more than likely bought the group enough time to fix the RV and may very well have saved all of their lives. He left Clem behind so Chuck had to sacrifice himself and he took the machete off the seemingly clear door (which, btw, none of us bothered to lock the FIRST time we went through. Because there were no Zombies banging on it THEN either).
Out of those 3 mistakes I only attribute one to Ben specifically (leaving Clem behind) and that’s just a kid panicking.
Kenny left Shawn behind and will leave Lee behind in two or three other occasions if he doesn’t like you…
I agree making a deal with the bandits is the right call, not telling anyone isn’t, though let’s not restart that argument. removing a machete is pretty silly visible zombies or no, and you’re forgetting his letting Clementine leave without even seeming to notice and his insisting the group stop and talk about his deal with the bandits with zombies just outside banging on the door. I was mostly on Kenny’s good side but I’ll take your word for what he does, Kenny being a bad person doesn’t vindicate Ben in any way though.
It’s hard to blame Ben for removing the machete with no visible Zombies around when WE got into the place without locking the door EITHER. WE operate under the “well, if the Zombies aren’t ACTIVELY trying to get in, there’s no reason to close the door” stupidity, but we crucify the kid for applying the same reasoning (remember, we are the ones who went into the garage and LEFT THE DOOR OPEN behind us, despite there being Zombies there. That’s twice in one episode we do the SAME THING Ben does). It’s stupid, but it is as stupid as everyone else in this group.
And Clem is a ninja. She gets away from everyone, magically. Hell, even Lee… Remember when she just snuck into the house without permission?
I use Kenny as an example because he is the biggest pusher for the “kill Ben” side and Ben’s one true mistake (panicking and leaving Clem behind, which caused someone’s death) is identical to Kenny’s one mistake (and if he hates you, multiple mistakes).
“It’s hard to blame Ben for removing the machete with no visible Zombies around when WE got into the place without locking the door EITHER.”
I’d be surprised if you could lock the door without a key. It’s a school – you’re going to have a ton of kids around, not all of whom can be trusted not to screw around like that.
We used the machete right? Imagine if we spent that first half hour of our time in the school, when nothing was attacking us, finding some OTHER material to put in the handle to close it. Maybe just break the leg off a chair?
Hell put the machete there. At least then when Ben takes it off we can actually blame him for undoing something smart we did, as opposed to making the same dumb mistake we all did.
But he didn’t make the same mistake. The group found an unbarred door, and left it unbarred. Ben found a barred door, and unbarred it. And considering that Kenny and Brie needed to come back through that door, it wasn’t completely unreasonable to keep it unbarred rather than leaving an unreliable piece of zombie bait in front of the glass doors to open it when they got back. Barring it when they expected it to be unbarred, or unbarring it when people expected it to be barred, could have and did get people killed.
Ben taking the hatchet was only possible because zombies act freaking weird in this episode. Where did that group near nurse room came from? Why did they walk directly where Christa and Vernon were, instead of walking aimlessly around the corridor? Why zombies near the garage were suddenly smart enough to crawl under that door? For the same reasons they stopped pounding on that door long enough for Ben to pick up this hatchet, because plot said so. It was stupid of Lee to leave behind his weapon like that, it was stupid for Kenny not to take a weapon and having to borrow it from Lee, it was stupid for Lee not to pick up his spike remover immediately after fight with Molly (they are all extremely careless when it comes to keeping survival equipment), and it was stupid for all of them to fail to warn everyone else where the zombies are. Everybody acts stupid here, but plot decides to cash in it’s stupid chips only when Ben does something.
I think you had a very different version of Kenny than I did…
That being said, that’s the point. Right up until now, all his mistakes (by which I mean “two”) were grey and nuanced, and are most certainly comparable to other things that characters have done. Ben ran from Clementine? So what? Kenny is a man twice Ben’s age, and he leaves Lee to die constantly, drops Lee every time Lee needs a hand up, belligerently picks fights with Molly, Andrew St. John, and Larry (not to mention loses every single one, which gets him shot). Lilly screams at Carley for even daring to go outside to save our lives, and screams some more for not leaving Ben to die.
Ben screwed up with the bandits and got people killed? Because our single guard on night watch would stop them? And he clearly should have told us, so Lily could shoot him in the head!
Ben took the hatchet off the door? Oh, like that time Lee broke open the pharmacy security! Or maybe that time intentionally sabotaged the electric fence keeping his own group safe, so he could look in a warehouse and see something he did nothing about!
But those were different? Yes, they were. Ben’s actions had consequences, no one else did. That’s the difference. It’s not so much “Ben is vindicated” so much as “why is Ben the only one being picked on?”
Yeah I get that you don’t like people picking on Ben but you’re arguments are a bit off. Yes the other characters were a liability at some point but they also contribute to the group: Kenny’s an ass if you don’t agree with him but at least he fix the RV and go out scavenging with Lee. Lilly is a paranoid nutcase but she have to make hard choices as leader when no one wanted to, she also make sure that the group have target practice to get them familiar with the gun. The problem with Ben is that he’s not only mess up but he have done nothing to help the group.
Ben made the deal with the bandit to buy the group time right? Why didn’t he talk it over with the group BEFORE making the deal then? Its not like the bandits told him to keep it to himself, in fact they were surprise that the group didn’t knew. And removing the hatchet was to help Kenny break the door right? So you’re telling in that entire building, Ben just have to take to hatchet that’s barring the bloody door? Couldn’t he look around a bit more since they have to wait for Lee and Molly to get back anyway?
I agree that this is contrived and stupid, which is why I said “up until this point”. But its also when it becomes apparent that the writers are yelling at you to hate him in the most hamhanded manner possible, because only his actions have any consequences. He “only ever hurts the group” because everyone else gets a free pass. If Kenny had gotten Clem or Lee killed in any number of the multiple occasions he put them in danger, would people really be arguing “but he fixed the RV that one time!” What if Lee had gotten people killed with the electric fence? “But I just wanted to help! I’m useful! Look, I cut that man’s leg off and killed him and got Katjaa attacked by a zombie! And I fixed the swing!”
I shouldn’t have included the examples of people doing the same as Ben with the hatchet, because I think the hatchet is so stupid it breaks suspension of disbelief. But I do feel like yes, Lee did exactly the same thing – he broke the pharmacy gate so he could get out of the pharmacy (with an axe he’d gotten outside of the pharmacy), and then set off the alarm and directly got someone killed because the gate was broken. Really? You had all the time in the world, you could leave the pharmacy, you had cars, you couldn’t think of anything better? You didn’t think to brace the door after you broke the gate? You didn’t even tell anyone? But no one cares because the game made you do it.
The bits with the bandits were good because he acted under a logic that was understandable but went bad. The bit with the axe is terrible and gamebreaking because its so stupid it breaks faith in the writers, and relies on a utter contrivance (the zombies went away and just calmly waited until Ben takes the axe, then break in without any noise to prompt them). We forgive stupid contrivances like zombies teleporting into the hall or being smart enough to climb ladders because they have no consequences. Okay, exciting chase scene, obligatory sewer, whatever. Nothing changed. But if a stupid contrivance happens and people die and we have people yelling to kill some kid, you better believe I’m going to look back and start scrutinizing all the other contrivances and stupidity in this game. And the more you look at it, the more you realize everyone else should be like Ben, Ben’s just Ben because the writers hate him.
Clearly the next episode should be titled; ‘Still not pregnant.’ :)
Nah, clearly that should be Rutskarn’s title in the credits for the next episode.
From what I gathered from this picture located in the classroom, Crawford’s policies were to take anyone who fit Crawford’s standards from their squats and kill the ones who did not. I may be reading it wrong, but it looks like there was at least a squad dedicated to these types of raids.
How did they find ONE eligible citizen and yet bring TWO to Crawford?
That’s the just the legend to show the layout, 1, 2, 3, left to right, so you know which matches up with what.
Nah, it was one INELIGIBLE person and 2 accepted. I noticed after I posted but my post was awaiting moderation so no editing…
My problem with “Humans are the real monsters” aesops is that the “real monsters” are almost always the author’s caricature of whatever social group he/she’s not a fan of, with the good guys being “the people I agree with.” Most often, it’s written to imply that southerners/rural types/flyover country denizens – you know, the unwashed rubes who might be enlightened by the moral – are two steps away from pure evil. If that.
Thankfully, Walking Dead (the game) mostly stays clear of that nonsense. With the notable exception of Cannibal Tom, Dick, and Mary. Crawford isn’t really an indictment of any given group – or if anything, it’s of educated, we-know-what’s-best elites. Much easier to stomach.
Devil’s Advocate: So it’s okay when it’s about a group of people YOU don’t like being idiots?
To me personally, sure. In a general sense, no.
But again, Crawford’s indeterminate – it could just as easily be evil conservatives or Randians as liberals, and as such it’s easy to draw one’s own satisfactory conclusions.
You sort of have that Aesop from this game, but I feel like it was overshadowed by “The Dead Always Win.” The fact that everyone’s dead when you get to Crawford kind of sunk that in for me.
“Humans are the real monsters” is less of a philosophical idea or a thought experiment and more of a “I HAVE EMOTIONS, WHO NEEDS FACTS” kind of statement. It’s melodramatic, and not realistic.
Ultimately humans, to paraphrase Commander Shepard, survive or die, and survival depends on practical real-world solutions. Beyond that, people have limited knowledge and aren’t actually infallible. And beyond THAT, it doesn’t take much (in relative terms) for a single individual to ruin it for everyone, and “I was just following orders” actually seems to be a valid defense, as research indicates that the hardwired functions in social animals such as humans actually make disobeying orders from people you see as your superiors a very difficult mental challenge.
Moreover, the worse the situation, the more necessary practicality becomes.
Imagine a total societal collapse like a zombie apocalypse or other such obviously fictional nonsense. Now imagine some time passing and THEN encountering a sufficiently (in terms of that situation) well-off society based on Nazi values. What does this say about nationalsocialism? Nothing. All it says that at least one key individual in that group knows what they are doing, because otherwise that society wouldn’t be there in any mentionable capacity. They might be flying Nazi flags and sieging their heils all day long, but they are – by necessity – practical first and Nazis second.
There might’ve been numerous Nazi groups before, possibly more ideologically pure, but they died or gave up their ideals under the pressure of reality.
Mad Max, etc. style bandits might make for good film, but caricature villains cannot survive in reality unless they can afford it due to leeway built by real-world solutions.
Considering that, in practice Crawford is less “humans are the real monsters” and more “these idiots didn’t know what they were doing and the results are as obvious as they were predictable”. It’s hard to call something a monster when it’s angrily biting its own tail.
Even with the wars of the 20th century the majority of it can be explained (thought not really excused) by circumstance and human fallibility. Even all the cruelty adjacent to WW2.
And while this is just my view, I find that the most unconscionable behavior related to these wars comes from, as a group, “intellectuals” who never participated in or experienced these wars, and are, with all the advantages of hindsight, passing extreme and emotional judgment based on entirely emotional, modern ideals that have already been dismissed by the majority of people as childish nonsense. They seem to be wearing some sort of rose-colored goggles in relation to some intangible, purely hypothetical modern utopia, and seem to assume that the current conditions in the western world are indicative of the situation in 1914, or 1939, or Korea in 1950, or Vietnam in 1955, etc.
And beyond all that, who are they to call anyone a monster (aside from sheer melodramatic exaggeration)? And when calling someone a monster, aren’t they kind of implying that they themselves are NOT “monsters”? At the very least in the “I’m a lesser monster because I realized/acknowledge it” way.
tl;dr “Humans are the real monsters” is emotions, melodrama, and hypocrisy.
You had me up to “intellectuals as a group.”
What the heck do you mean by that?
I really must be misreading this, because it sounds like you’re saying that “intellectuals” condemning Hitler for murdering 10,000,000 people in death camps is more “unconscionable” than Hitler murdering 10,000,000 people in death camps.
That can’t possibly be what you meant to say, can it?
It didn’t look to me like Josh ever considered the (in my opinion) correct response when Kenny was going after Ben. Namely, “Kick his ass later.”
That might defuse the situation long enough to get Ben to someplace semi-safe before telling him, “You’ve built up a track record of too many dumb-ass choices. Maybe you’d be better off finding a fresh group.”
I’ve been waiting for this episode to say the exact same thing about the insulin. Other, more general medical supplies I can understand, but what are they going to hoard with a bunch of insulin for other than treat their diabetics? Maybe it has other uses, I don’t know, but it does seem like an odd thing to ration so strictly.
Yeah, I think Shamus’ idea about trading things like insulin and similar supplies that have little use outside of a specific situation that disqualifies you from living in Crawford anyway.
See, if I was organizing a community along the lines of Crawford, and were a bit of a dick, I’d keep a small subcommunity, probably outside Crawford proper, of people who require stuff like insulin, stuff I don’t really have a need or use for myself but that these people desperately need. Heck, I’d even offer them some protection against the zeds as long as they were useful, would beat giving them guns that they could turn against me when push came to shove. This would still work in showing Crawford as a bunch of dicks (keeping a dependent and underarmed community for stuff like high-risk looting with the implication that once they’ve outlived their usefulness you’re at best going to cut them off, at worst finish them off to make sure they don’t figure out some way to get back at you or increase the general populace of zeds in your area), would give Lee’s group some natural allies against Crawford and I think would make more sense in the bigger scheme of things.
I am so glad that this game chose this art style instead of going for photorealism.If they went the photorealistic route,having heads smashed that easy with boots and heavy objects would irk me so much.
I abstained there because we were in the middle of zombies attacking us,and instead of running we are voting on who is going to be left back?Seriously guys,you pick the best times to argue.
And this idiocy from ben was the last straw for me.Not only did he get an axe that was clearly jammed in there to keep zombies out,but he also picked the perfect moment to rile everyone up.I didnt want to leave him on his own though,because terminal stupidity is still not as bad as what lilly did,but this is where I decided that I wont be helping him out of shitty situations anymore.I tried,I gave him advice,I gave him chances to show his usefulness,but he just failed at everything.
There were gunshots after the woman ran off tape, so it’s more implied she went on a shooting rampage, not just the doctor.
That doctor is a moron.He is so clearly doing a bunch of shady deals(I think his suggestion to the mother to leave was something that the community as a whole wouldnt allow),and yet he is video taping every single one of those.If he filmed the actual act he did with molly,that Id understand:He is a pervert and likes to watch his rape acts.But no,he specifically left that one out,and started filming just after sex,so that everyone would know both that he is into shady deals that go against the group,and that he is a despicable human being.
Maybe he thought the red light meant the camera was stopped, like red on a traffic light means ‘stop’?
So… “That doctor is a moron?”
In a universe where battery poles are apparently indistinguishable from each other, it only takes slight dumbness for that, not full on moronity.
I have no evidence for it, but I think he WAS taping the sex act, and that’s why the tape begins right after it – because he’s watched it at least once since and hit “stop” right after the part he wanted to see.
If that were the case,why would he:
1)Continue taping after the act
2)Zip his fly right in front of the camera,like he was about to start/stop recording while getting dressed
Actually, I thought he was deliberately showing that he HAD been using his position to get sex, but now that they were cracking down he was stopping, kind of a way out if any of the people he was using accused him and tried to get his kicked out of Crawford.
That was the only reason I could think of to tape the conversation, anyway
“I wasn’t being corrupt! See, I have proof here on this videotape that I stopped being corrupt, eventually!”
it could be a ploy for Mutually Assured Destruction – if Molly points out the doctor’s corruption, he can burn her back with a tape of her admitting to her sister’s diabetes
He keeps taping after he’s done because he doesn’t want Molly to know he was taping them. The tape is at that position because that’s when he “finished” with it the last time he watched it.
About Molly’s sister and the “took her away” thing, didn’t Molly mention when we first met her that zombies-on-a-stick were the old and disabled, or something? Maybe it’s worth looking at them more closely, see if any of them have clothing that match her sister. So maybe “Leave Crawford” is a euphemism, considering the doc did emphasise it was certain death, even though that’s only the mildest of mild hyperbole in this situation. Or maybe people who’re ill and don’t leave willingly get murdered.
My take was that the doctor was offering her to leave instead of being killed,because he is “such a nice guy”.
Why did Ben feel guilty over Duck and Katyaa but not Carley/Doug? He isn’t responsible any of them but Carley/Doug really did die for Ben. There’s should be a much stronger guilt trip for the latter.
Maybe that’s just Ben screwing up again. He can’t even get feeling guilty right.
It’s to remind the player why Kenny will flip out in just a second. Because the connection between Ben’s acts and Duck’s death wasn’t as strong back in the previous episode (which the player might have played months ago, and was overshadowed then by doug’s death and lily’s exile), it needs to be reinforced here now.
I don’t mean Duck’s death was overshadowed, just its connection to ben’s part in it.
Regarding Southern Accents, the most likely reason is that the VA is from Los Angeles (or at least has been there since 1990, according to IMDB). However, Lee was a professor of history at UGA, which suggests at some point he went away to school for at least 8 years if not 10 or 12. That’s plenty of time to lose the accent.
0:48 – Wait, climb Shell Casings? Lee, you have strange thoughts.
This episode is a good example of what this game does overall: it presents a situation in which other people make a decision about other whether someone else will die, and then asks the player to make basically the same decision. It happens on the St. John’s Dairy farm, when (I believe) the mother presents her rationalization about killing people in order to eat them, and shortly thereafter the game requires Lee to decide whether to (directly) kill the brothers. Then there’s Larry, the supplies in the station wagon, whether to leave Lilly behind, and this decision with Ben. The game invites you to understand all of these decisions, even ones which are easy to regard as evil, from the inside out and from the outside in, and in my experience that’s unique for a game to do.
I had an interesting thought in regards to Crawford…I’m assuming that the writers’ plan from square one was to have the entire community zombified when Lee’s group showed up. In that case, if the community did have kids, how would they have handled it? The “Humans are the Real Monsters” argument doesn’t really go that far when you factor in dead/zombie children. They could’ve hand-waved it and just said there were no kids, but you’ve still got the demographic problem Shamus mentions (at least you could reproduce gradually however). I’m just theorizing here, but I’m wondering if the writers worked in the ‘no kids’ part just to make the zombified town a much more black and white scenario (that, and to obviously make Crawford even more despicable). I’m just trying to find some way that the ‘no kids’ rule makes any sense, and writer intervention seems the best bet.
As in, if there are no kids we feel less guilty about Crawford being all zombied up and enjoy the revenge more?
I guess that makes some sense, but we probably just wouldn’t have thought about it, they only need to show us what they want to, so they wouldn’t show us children and we’d be too caught up in the story
And again,I am baffled why people seem to think that having wailing starved infants is a *good* idea at the peak of the zombie shuffle.
Wait a year or two, cull the zombie numbers, *then* get pregnant and all. But now, when zombies are attracted to loud noises and are behind every corner, YOU DO NOT WANT A GOD DAMNED WAILING INFANT WITH YOU.
How hard is that to understand? There IS logic behind that rule, and it is NOT just because “crawford is teh monsterz”. It’s not like everyone in crawford was in their late 40s and on the brink of nonfertility. Now, granted – the doc is an asshole, and that ‘no insulin’ rule is rubbish too. But no pregnancies, in the first year of zedpocalypse? Sorry, no, IT DOES MAKE SENSE.
The “no kids” rule went all the way up to age 14, way beyond the point of “wailing infant”.
For the forced-abortion thing: I can understand the moratorium on births, although that’s assuming it’s temporary. We don’t know for sure. They never SAY it’s temporary, and their “badass only” policy would seem to preclude children forever.
I still can’t tell if the rule was, “Get an abortion or we’ll murder you” or “get an abortion or we’ll hug you goodbye and send you on your way with your share of the gear and food.” Again, one is pure evil and the other is cold-hearted but understandable.
Since the game keeps telling us how evil and bad the Crawford people are, I think a lot of us just assume the worst.
True. I can’t argue in favour of the ‘no reasonably aged children’. But the no-pregnancies angle, well, I just see it bashed way too much in the last few episodes’ comments.
Pretty much. I think the whole problem is that the game *constantly* goes ‘Crawford’s stupid & evil, you should think they’re stupid & evil.’
EDIT:
As for babies, how I would probably handle them in a zombie-apoc settlement: allow just *one* at first, & get a significant amount of the community involved in its care (particularly the older members of it, since they could take care of the baby instead of doing more physical labour). 1) Reduces the extra workload on any one person (particularly because everyone can keep their normal sleep schedules, since when they asleep others are in charge of the baby), 2) induces solidarity in the settlement, since the baby is a shared responsibility, 3) the baby acts as a *symbol*, which everyone can see & attach to, 4) the baby grows up more with the community than with their parents, which makes *it* more attached to them. Basically, I’d want as much as possible to shift the paradigm from parent-child to community-child. One important repercussion of that paradigm shift (assuming it’s successful) is that allowing one baby doesn’t lead to tons of people also wanting to pop out a baby (which *would* put undue load on the community) – instead, the baby is ‘the community’s,’ so you’d get less of the ‘why’d you allow them to have a baby & not us?’ complaint.
(And shit, I just realized that I must have subconsciously used the same reasoning when designing one of the major communities my players met in my sort-of-post-apoc tabletop game o_O)
At 14:08, he doc does tell her ‘Maybe one day, when things are different, you can try again. But for now, today, we have to do this.’ You can interpret that as pacifying rhetoric or sincere plans, but it certainly seems that the people of Crawford would have had to consider when to allow babies.
(The doctor also frequently mentions ‘those are the rules’ in the ‘I don’t like them, but that’s what they are.’ Whether that’s just an excuse (hiding behind the rules) or an actual point (that Crawford’s rules may not be so strict forever; frex, perhaps the current ruler will be overthrown, or perhaps this *is* meant to be just the first iteration of the rules) is unclear, of course.)
“The “no kids” rule went all the way up to age 14″
on what do you base that? as long as they thought she wasn’t diabetic, they seemed fine with keeping the 14 year old sister of Molly around
The poster of rules lists ‘no one under 14 (unless given express permission).’
EDIT: Verbatim it says: “Children under _14_ NOT admitted without authorization.”
Waaait. “without authorization”. That’s a pretty important caveat, implying that there are cases when children are allowed, i.e. they get authorization. Otherwise, why bother stating it? Just have the rule be “no children under 14, full stop”.
It could be genuine or pacifying rhetoric, we don’t know for sure. All we know is that all of the characters we’ve met thus far who know of Crawford hate the place and everyone in it.
Yes, but they’ve all been personally wronged by Crawford.
The rules also state that all illnesses/medical conditions must be disclosed to the council, not that people with such will be booted out (as is so oftenly stated).
My best guess is that some group of /moderately/ reasonable people created the rules (note: it says *council*, not leader), but then this one crazy Oberson fellow took over & amped up the rules to stupid levels (although I do think that everyone we meet overstates Crawford’s supposed evilness).
(They could only have been moderately reasonable because of things like: 14 is still *way* too high (I dunno, maybe 6 or 7 would be good? With authorization for any below that? (Want something a bit past post-toddler as your baseline, basically, so that number could go as low as ~5 I guess.)). Also, including a ‘if you leave, you can never come back’ rule is pretty weird, and is usually only there to make people choose between leaving with others leaving or ever being able to return (e.g. Vernon should not have been kicked out, because HE’S A GRAVDAMN DOCTOR YOU STUPID FUCKS; rather, Vernon would have had to choose to leave (to stay with his cancer buddies) at the price of never being allowed back in).)
(& Oberson is *definitely* crazy. His response to ‘should have been containable walker threat’ is to
hang himself in the belltower, above the armory. Really, if you’ve got to go out, at least make sure you do it in a less ‘prone to causing massive pain if you fuck it up’ way <_<)
On Molly & the doctor, I think “Sexual extortion” is the wrong term.
Sexual extortion would be the doctor saying “Get horizontal with me or I’ll tell them that your sister is diabetic.”
‘Sex-for-favours’ is what we’re rally talking about here. That’s Molly saying “I’ll do you if you give me packages of insulin in return.”
Consider: who’s angry about the deal being off? MOLLY.
(Also, if the doctor was that into sexual extortion, he would have done it with the pregnant lady too (whereas instead he cuts her off before she gets far into the ‘you don’t have to tell anyone!’ line of thought).)
(One point is that the doc probably could have taken material goods instead of sex in exchange for the insulin, but it’s unclear to me WHAT would have been useful to trade – I presume that all material goods would have been going to Crawford Central anyway. (Also, perhaps a more clever setup would have been to use the insulin stores /officially/, as a ‘we’ll give you this insulin for your sis, Ms. Non-Crawford-Resident-Molly, in exchange for useful things you’ve collected for us around town.’))
Anyway, I consider the whole thing pretty dumb. Just everything. Dumb.
Even if he’d wanted something from the pregnant lady, there’s no way to hide it.
#OneGotFat
Accursed edit button, how dare you defy me!
What I meant to say was: “My first thought in response to that is: Nonsense, just say ‘one got fat.’” (Because thanks to One Got Fat, that goofy phrase is stuck in my head.)
It’s walking a thin line. Molly’s sister would drop dead, no question, without the insulin. The doctor can pretty much name his price, and if Molly doesn’t take it, her sister dies just the same as if the doctor had snitched her out. We never really learn the details of who started the deal and who did what.
He could have extorted the pregnant lady, true, but consider he cuts Molly off the second he doesn’t think he can hide it anymore (and then tapes it, but, we’ll ignore that for a second and pretend it was blackmail insurance against Molly). He can’t hide a pregnant lady for very long, so any predatory desires are quashed by his practicality.
Depends on how far along she is. Some women don’t show for months, and it still takes a bit after their first showing when unclothed to be obviously pregnant when clothed… if he were a predator, he’d probably not turn down 2-3 months extra months of ewwww and string her along for a bit.
Not disagreeing with you, but just because he’s a predator doesn’t mean he’d go after every woman he could… that and Christa isn’t showing and everyone knew she was pregnant anyway.
Also, Molly is angry the deal is off because they had sex and then the doctor says “Oh, the insulin I was going to give for that? You can’t have it. Deal’s off.”
The doctor *clearly* gets something out of the medical cabinet and gives it to Molly during the ‘we *HAD* a deal’ routine. AND says ‘this is the last that I can give you.’ Watch more closely?
Oh, you’re right. I somehow forgot that. Man, he just leaves that door wide open, too. I’m surprised Molly didn’t assault him and take the damn insulin.
Man, I wonder what it would have been like if Molly had caused the apocalypse at Crawford?
There’d be no zombies, only corpses.
Will there be a fourth entry in the “Coding style” series? I really loved those!!
Lee: “She saved your life, didn’t she?”
Kenny: “Yeah, but what has she done for me lately?”
Pretty much sums up Kenny’s entire character.
So am I the only one that’s kind of disturbed by the way that the zombies always seem to go for the arm-neck-intestines? Because it feels like they always take people down in more or less the same way, and it’s getting kind of freaky at this point.
Not if you’ve seen the Episode 5 stats. The “idealistic, merciful” people who play this game suddenly turned into selfish jerks at the last minute, apparently.
I’m surprised that many people made Clem do some pretty awful things, just for Lee’s immediate convenience. Even in ways that Lee probably knows in any playthrough would hurt her in the long-run.
Which I guess is fitting, since the people who MADE this game lost all sense of direction at about the same time.
The voice-actor for the Doctor also does Chuck and
The Stranger.
According to Wikipedia he was also the voice of Ghostface in the Scream movies, and a shed-load of other voice roles in films and video games.
I don’t see Half Life there…is this an inside joke or something, seeing as Gordon Freeman apparently doesn’t have a voice? | http://www.shamusyoung.com/twentysidedtale/?p=18569 | CC-MAIN-2014-41 | refinedweb | 17,187 | 67.99 |
Here is the documentation of the DtoKPiPiE691 class. More...
#include <DtoKPiPiE691.h>
Here is the documentation of the DtoKPiPiE691 class.
Definition at line 28 of file DtoKPiPiE691.h.
Calculate the amplitude.
Definition at line 121 of file DtoKPiPiE691.h.
References sqr(), sqrt(), and ZERO.
Make a simple clone of this object.
Implements ThePEG::InterfacedBase.
Definition at line 144 of file DtoKPiPiE691.h.
Output the setup information for the particle database.
Reimplemented from Herwig::DecayIntegrator.
Methods to calculate the amplitudes for a given channel.
Calculate the decay angle for the amplitude, the angle is the angle between the 2 and 3 for the decay
in the rest frame of the resonance which decays to 1 and 2.
Definition at line 103 of file DtoKPiPiE691.h. 150 of file DtoKPiPiE691 the different components.
Amplitude of the non-resonant component for
Definition at line 194 of file DtoKPiPiE691.h.
Complex amplitudes for use in the matrix element.
Amplitude of the non-resonant component for
Definition at line 309 of file DtoKPiPiE691.h.
Masses and widths of the various resonances.
Use local values for the masses and widths
Definition at line 369 of file DtoKPiPiE691.h.
Parameters for the phase-space integration.
Maximum weights for the various modes
Definition at line 439 of file DtoKPiPiE691.h.
The static object used to initialize the description of this class.
Indicates that this is a concrete class with persistent data.
Definition at line 177 of file DtoKPiPiE691.h. | https://herwig.hepforge.org/doxygen/classHerwig_1_1DtoKPiPiE691.html | CC-MAIN-2019-30 | refinedweb | 241 | 53.47 |
I'm trying to append tuples to my array in groups. The number of groups or the number of tuples in each group is unknown.
I'm aware there should be a very simple answer for this, but my mind is grasped on swift, which takes care of this issue for me.
This is my issue, I need to be able to do this:
array = []
array[0].append([1, 2]) # error because there isn't a '0' index
array[0].append([7, 2])
array[0].append([89, -5])
array[1].append([2, 3])
def get_data(index, array):
# loop for an un-determined number of times, calculates differently depending on the index
one_or_more = 4
for i in range(0, one_or_more):
# do some calculations depending on index, which should differ for each loop
data1 = index * 3 + i
data2 = index * 4 + i
array.append([data1, data2])
def main():
array = []
array_index = 0
some_num = "110, 121, 122, 123, 124, 125, 130, 131, 323, 324, 325, 326, 340, 341, 342, 343".strip().split(", ")
for i in some_num:
get_data(int(i), array[array_index]) # error here with 'array[array_index]', because I can't index array with '0' because it's not initialized yet
array_index += 1
if __name__ == "__main__":main()
The value at a given index is being over written. So, an array is not a suitable data structure for your task. I would use a defaultdict.
from collections import defaultdict key_lists = defaultdict(list) key_lists[0].append([1,2]) key_lists[0].append([89, -5]) key_lists[1].append([2, 3]) print(key_lists) print(key_lists[0]) one_or_more = 4 for i in range(0, one_or_more): data1 = index * 3 + i data2 = index * 4 + i key_lists[i].append([data1, data2] | https://codedump.io/share/GodfmkCLm3Pm/1/append-tuples-to-array-in-groups-python | CC-MAIN-2017-13 | refinedweb | 276 | 64.41 |
But that work also meant that I've not been paying very careful attention
to the XML-DEV mailing list or the XML developer
community. What fun I have missed! Accordingly, in this
XML-Deviant column I want to catch up with some of the more
interesting developments, most notably the RDDL2 and genx development
efforts.
RDDL is one of those interesting
projects which people often misunderstand, for at least two reasons:
first, it's an attempt to respond to the XML namespace document issue,
an essentially
contested bit of XML technology; second, the XML developer
community drives the development of RDDL, which is to say that it's
not the product of crass commercialism, such that there are marketing
flaks around to beat it into everyone's head. by implying, first, that the TAG is an odd place for
specifications to be developed (though it's not clear that the TAG
cannot develop informal specifications, since everyone seems to have
that right); and, second, that the new syntax seemed to van der Vlist
rather broken. Van der Vlist's objections to the new syntax center
mostly on what he takes to be a loss of expressivity. "... I use
[RDDL] as I have shown in my examples (a rddl:resource embedding a
whole <div/>)," van der Vlist
said,
"often with several links and even if the upgrade [to the newly
proposed 2.0 version] would be feasible through a XSLT transformation,
I consider that it would decrease the expressiveness of the links."
Further, as van der Vlist said,
"The difference with the current syntax seems pretty much limited to a
boycott of XLink which doesn't seem to be a benefit by itself to
me..." Boycotts of XLink, if that's what's going on here, may be
useful in or to some contexts, but they do seem awfully curious as an
iteration of the RDDL specification. Further, as van der Vlist also
points out, it's a strange thing to claim as a benefit of a new
version of the RDDL specification, especially when there is some doubt
as to how unused XLink really is. John Cowan, Andy Greener, and van
der Vlist named four XML applications -- XTM (Topic Maps), XBRL, SVG,
and OpenOffice's document formats -- as examples of XLink adoption.
I'll remind you, dear reader, that XLink has been a political weight
inside the W3C for some time by pointing you to three XML.com
articles: Micah Dubinko's "A
Hyperlink Offering" and two pieces of mine: "Introducing
HLink" and "TAG Rejects
HLink".
Though XLink's success and utility are matters of some dispute, Simon
St.Laurent offered
a list of reasons why it hasn't been more widely adopted. Those
reasons include XLink taking too long to arrive, being orphaned by
Microsoft (and by most browser developers, too), the belatedness and
complexity of XPointer, the overlap with both RDF and XTM, and,
perhaps most importantly, "most people still don't get/want
multi-ended links". Jeff Rafter added
two more reasons: the political dustup over HLink and XPointer's IPR
interactions with a patent of Sun's -- interactions which, in Rafter's
estimation, may have "spooked a lot of implementers". Van der Vlist
also noted that XLink bore very high expectations (which is true
historically; recall that the original W3C troika was XML, XSL, and
XLink) and the fact that extended links are too complex for many
users..
Discussions seem to be ongoing over the future direction, if any, of
RDDL 2.0. I think it's useful to point out that what happened here,
while perhaps not ideal, is encouraging. Some changes to a
conceptually useful, even if underused, specification were proposed,
and some of the core users of that specification pointed out that the
changes weren't worth their costs. All of this prompted further
discussion and, presumably, development. That's how these things
should work.
The second, interesting bit of work on XML-DEV in the past
few months is the C library, genx, for generating XML. We've all
struggled with the progression of XML's complexity, and one scene of
that struggle has been the increasing complexity of means of
generating XML programmatically. Yes, many people still write XML by
hand, not just Simon St.Laurent -- I know people who write RDF and OWL
by hand. But lots of XML these days, especially in web service
contexts, gets automatically generated by some machine process. We
probably all started out, back in the day, by generating XML with
string printing. But as the I18N and C14N burdens have increased, as
Uche Ogbuji has been demonstrating in his Python-XML columns of late,
generating XML in that way has become too error prone.
Also in XML-Deviant
The More Things Change
Agile XML
Composition
Apple Watch
Life After Ajax?
As a result of some discussion which sprang out of the Atom community,
Tim Bray stated
an interest in developing a C library for generating well-formed,
canonicalized XML efficiently. He
presented an initial design, which subsequently went through
several rounds of refinement and change, driven in large part by input
from members of the XML development community, largely
on XML-DEV. One of the interesting tensions in the use case
analysis was the issue of generating Canonical XML, very
useful in web services, versus being able to add a DOCTYPE
declaration, required to be able to generate valid
XHTML. Canonical XML and XHTML are both in the fat parts of the curve
of use cases, though they are different curves. But,
then again, they aren't. One can imagine needing a way to generate
canonicalized XML for a web service but also wanting to generate, in
the context of the same service, valid XHTML for human consumption.
Sure, you can use two different libraries or do some post-processing,
but the tensions and interactions between these core use cases is
interesting.
I won't summarize all the contributions of the individual
participants -- that's both too much work and too much low-level
technical detail, a great deal of which concerned portable C practices
anyway. I do commend the conversation threads to you for casual
reading. And, of course, the code
is available (Bray says, "the plan is to grant essentially unlimited
Open-Source rights along the lines of recent Apache copyrights") for
use and study and critical feedback.
Again, I'd like to point out that this discussion and development,
while perhaps not ideal, is another good example of useful software
getting created in a way that's responsive to community needs and
interests. I'm not entirely sure that the whole episode wasn't the
geek's version of a bar bet, but it is a handy thing to have in an
increasingly tricky area.
Share your comments on this article in our forum.
(* You must be a member of XML.com to use this feature.)
Comment on this Article
David vun Kannon
KPMG LLP
ED
The growing momentum of XBRL translates into momentum for the technology it is based on, XML Schema and XLink. In Japan, the National Tax Agency, the Bank of Japan, and the Tokyo Stock Exchange are all shifting to data collection using XBRL - XBRL taxonomies created by the regulator tell the companies what to report in XBRL instances. The data and metadata of a significant national economy, all in a single XML format.
All the applications that process XBRL documents must understand and process XLink, both simple and extended links. To me, that is "achieving traction", not the number of papers given at XML conferences.
Legislation such as Sarbanes-Oxley in the US demands (on penalty of jail time) that business executives adequately document their semantic webs of controls over financial reporting. This is a time when there is a strong business driver to the commercialization of a hyperlinking technology standard. XBRL, using XLink, already has a high level of awareness in this area.
David vun Kannon
Senior Manager
KPMG LLP
Be the first to post this article to del.icio.us | http://www.xml.com/pub/a/2004/02/25/deviant.html | crawl-001 | refinedweb | 1,347 | 56.49 |
Masonite comes with some authentication out of the box but leaves it up to the developer to implement. Everything is already configured for you by default. The default authentication model is the
app/User model but you can change this in the
config/auth.py configuration file.
There is a single
config/auth.py configuration file which you can use to set the authentication behavior of your Masonite project. If you wish to change the authentication model, to a
Company model for example, feel free to do in this configuration file.
This would look something like:
from app.Company import Company...AUTH = {'driver': env('AUTH_DRIVER', 'cookie'),'model': Company,}
The cookie driver will set a token as a cookie and then fetch the user from the database on every request. For most applications this is fine although you are making an additional query per request just to fetch the user.
This is the most basic authentication driver.
The JWT driver will store an encrypted JWT token inside a cookie with all the authenticated user information. Then when the authenticated user goes to the page, the JWT token is decrypted and fills in the data on the user model without calling the database.
You can set this driver in your
.env file:
AUTH_DRIVER=jwt
There are also 2 options you can set as well. The first option is how long until the jwt token expires. By default this is 5 minutes but you can extend it out longer:
'jwt': {'reauthentication': True,'lifetime': '5 minutes'}
The second option is whether or not the user should reauthenticate with the database after their token has expired. If set to
False, the token will simply continue to refill the user model and set a new token all without touching the database.
Again the default authentication model is the
app/User model which out of the box comes with a
__auth__ class attribute. This attribute should be set to the column that you want to authenticate with when a user logs in.
By default your
app/User model will default to the
name, you can do so here. This will lead your model to look like:
class User(Model):__fillable__ = ['name', 'email', 'password']__auth__ = 'name'
Sometimes your application will be able to either login by email OR by username. You can do this by specifying the
__auth__ attribute as a list of columns:
class User(Model):__fillable__ = ['name', 'email', 'password']__auth__ = ['name', 'email']
By default, Masonite will use the
password column to authenticate as the password. Some applications may have this changed. Your specific application may be authenticating with a
token column for example.
You can change the password column by speciyfing the
__password__ attribute to the column name:
class User(Model):__fillable__ = ['name', 'email', 'password']__auth__ = ['name']__password__ = 'token'
If you want to authenticate a model, you can use the
Auth class that ships with Masonite. This is simply a class that is used to authenticate models with a
.login() method.
In order to authenticate a model this will look like:
from masonite.auth import Authdef show(self, request: Request, auth: Auth):auth.login('[email protected]', 'password')
This will find a model with the supplied username, check if the password matches using
bcrypt and return the model. If it is not found or the password does not match, it will return
False.
Again all authenticating models need to have a
password column. The column being used to authenticate, such as a username or email field can be specified in the model using the
__auth__ class attribute.
You may change the column to be authenticated by simply changing the column value of the
__auth__ class attribute. This will look something like:
class User(Model):__fillable__ = ['name', 'email', 'password']__auth__ = 'email'
This will look inside the
You may of course feel free to roll your own authentication system if you so choose but Masonite comes with one out of the box but left out by default. In order to scaffold this authentication system you can of course use a
craft command:
$ craft auth
This will create some controllers, views and routes for you. This command should be used primarily on fresh installs of Masonite but as long as the controllers do not have the same names as the controllers being scaffolded, you will not have any issues.
The views scaffolded will be located under
resources/templates/auth.
After you have ran the
craft auth command, just run the server and navigate to and you will now have a login, registration and dashboard. Pretty cool, huh?
Masonite ships with a
LoadUserMiddleware middleware that will load the user into the request if they are authenticated. Masonite uses the
token cookie in order to retrieve the user using the
remember_tokencolumn in the table.
Using this
LoadUserMiddleware middleware you can retrieve the current user using:
def show(self, request: Request):request.user()
If you wish not to use middleware to load the user into the request you can get the request by again using the
Auth class
from masonite.auth import Authdef show(self, request: Request, auth: Auth):auth.user()
If you would like to simply check if the user is authenticated,
request.user() or
auth.user() will return
False if the user is not authenticated. This will look like:
def show(self, request: Request):if request.user():user_email = request.user().email
You can easily log users into your application using the Auth class:
from masonite.auth import Authdef show(self, request: Request, auth: Auth):auth.login(request.input('username'),request.input('password'))
Note that the username you supply needs to be in whatever format the
__auth__ attribute is on your model. If the email address is the "username", then the user will need to supply their email address.
If you need more direct control internally, you can login by the models ID:
from masonite.auth import Authdef show(self):auth.login_by_id(1)
You are now logged in as the user with the ID of 1.
If you only want to login "once", maybe for just authenticating an action or verifying the user can supply the correct credentials, you can login without saving any cookies to the browser:
from masonite.auth import Authdef show(self):auth.once().login_by_id(1)
You can do the same for the normal login method as well:
from masonite.auth import Authdef show(self, request: Request, auth: Auth):auth.once().login(request.input('username'),request.input('password'))
You can also easily register a user using the
register() method on the
Auth class:
from masonite.auth import Authdef show(self, auth: Auth):auth.register({'name': 'Joe','email': '[email protected]','password': 'secret'})
Masonite ships with an authentication middleware. You can use this middleware as a route middleware to protect certain routes from non authenticated users. This is great for redirecting users to a login page if they attempt to go to their dashboard.
You can use this middleware in your routes file like so:
Get().route('/dashboard', '[email protected]').middleware('auth')
By default this will redirect to the route named
login. If you wish to redirect the user to another route or to a different URI, you can edit the middleware in
app/http/middleware/AuthenticationMiddleware.py
If you wish to end the session for the user and log them out, you can do so by using the
Auth class. This looks like:
auth.logout()
This will delete the cookie that was set when logging in. This will not redirect the user to where they need to go. A complete logout view might look like:
def logout(self, request: Request, auth: Auth):auth.logout()return request.redirect('/login')
If you wish to require a user to verify their email address and automatically send them an email, you can extend the
User model.
from masonite.auth import MustVerifyEmailclass User(Model, MustVerifyEmail):__fillable__ = ['name', 'email', 'password']__auth__ = 'name'
When a user registers this will automatically send them an email asking them to confirm their email address.
You can use the
VerifyEmailMiddleware class to redirect an unverified user.
You can use this middleware in your routes file like so:
Get().route('/dashboard', '[email protected]').middleware('verified')
Great! You’ve mastered how Masonite uses authentication. Remember that this is just out of the box functionality and you can create a completely different authentication system but this will suffice for most applications. | https://docs.masoniteproject.com/v/v2.2/security/authentication | CC-MAIN-2020-16 | refinedweb | 1,387 | 55.64 |
Orion IPAM 1.7 Release Candidatemavturner Jul 20, 2010 5:30 PM
Thank you for your interest in taking the latest Release Candidate of Orion IPAM. The RC is ready for you to check out. There are a few things to note about the RC. This is a production-ready build and can be installed in your production environment. In fact, we want you to install it in production, then tell us about your upgrade experience here on thwack.
If you decide to install the RC, you will be one of the first recipients of 1.7. Because you'll be one of the first, Product Management (myself) and Engineering will be actively monitoring your posts and engaging with you about any feedback you have. We are providing this additional level of support because your feedback is important to us and we want to ensure your upgrade experience is smooth.
This is a fully supported build, so our Support staff will be available to you as well.
New features for 1.7 include:
- Cisco IOS DHCP Server support
- Neighbor Scanning
- Improved search capabilities
If you're an IPAM customer on maintenance and you're interested in installing the RC, send me an email at mav.turner@solarwinds.com.
Re: Orion IPAM 1.7 Release Candidatejasadelll Jul 21, 2010 8:16 AM (in response to mavturner)
The upgrade went just fine. No problems. Can't wait to dig in!
Re: Orion IPAM 1.7 Release CandidateJacobss Jul 21, 2010 9:12 AM (in response to mavturner)
Upgrade went very smoothly. Nobody but myself knew that I had updated IPAM and brought Orion down for a minute or two.
Now to jump in and try out some of the new toys.
Re: Orion IPAM 1.7 Release CandidateQuestionario Jul 21, 2010 9:16 AM (in response to Jacobss)
whats neighbor scanning?
Re: Orion IPAM 1.7 Release Candidatemavturner Jul 21, 2010 9:34 AM (in response to Questionario)
Thanks for installing and giving the quick feedback jasadelll and Jacobss!
Questionario, neighbor scanning is a new feature for IPAM 1.7. Basically, it is a way to find the status of a device that may not be responding to ICMP.
You can add a neighbor device and IPAM will scan the ARP table to see what IP addresses are active. It is disabled by default. To enable it, select a subnet, click Properties and you will see the options you need to enable it.
Re: Orion IPAM 1.7 Release Candidatejasadelll Jul 21, 2010 9:43 AM (in response to mavturner)
Are there any risks in enabling it?
Re: Orion IPAM 1.7 Release Candidatemavturner Jul 21, 2010 9:54 AM (in response to jasadelll)
There are no known risks in enabling this feature. We fully tested it with QA before reaching this RC phase.
If you are concerned at all, follow the fabric cleaner advice - Test on a small inconspicuous spot before applying to the whole garment :-)
It is not enabled by default simply because it is an advanced feature. We did not want to require you to add a neighbor device every time you added a subnet.
Re: Orion IPAM 1.7 Release Candidatejasadelll Jul 21, 2010 9:53 AM (in response to mavturner)
Hmm, the option is not there, for me at least. It's added in the web interface, right?
Re: Orion IPAM 1.7 Release Candidatejasadelll Jul 21, 2010 10:02 AM (in response to jasadelll)
Ignore my last post, please. It's there.
Re: Orion IPAM 1.7 Release Candidatejasadelll Jul 21, 2010 10:21 AM (in response to mavturner)
FYI the "What is neighbor scanning?" link appears to be a broken link.
Re: Orion IPAM 1.7 Release CandidateMarkWiggans Jul 21, 2010 2:01 PM (in response to jasadelll)
jasadell-
That is being worked on today. Thanks jasadell!
Re: Orion IPAM 1.7 Release Candidatejspanitz Jul 21, 2010 2:02 PM (in response to jasadelll)
Upgrade went very smooth. Enable the "Neighbor Scanning" on a few subnets. No noticable change in ip addresses found. I know we have one device on on of the subnets that does not respond to pings, not sure what to look for in ipam, as it was already listed as reserved.
Will test the search and cisco dhcp options shortly.
John
Re: Orion IPAM 1.7 Release Candidatepguenther Jul 22, 2010 8:40 AM (in response to jspanitz)
The upgrade went ok but now all my DHCP servers (two Windows and one Cisco) are now showing down even though a Test passes.
Re: Orion IPAM 1.7 Release Candidatemavturner Jul 22, 2010 8:51 AM (in response to pguenther)
pguenther,
Where is it showing the DHCP server as being down, in the DHCP Management tab? Were any of the subnets from those devices added?
If they don't show up or if they appear to be bouncing, please open a support ticket.
Re: Orion IPAM 1.7 Release Candidatepguenther Jul 22, 2010 10:03 AM (in response to mavturner)
They are showing down in DHCP Servers tab. My scopes that had previously been discovered (pre-upgrade) are there but show unmanageable. My new Cisco show now scopes even though the test showed it discovered one. I will open a ticket.
Re: Orion IPAM 1.7 Release Candidatemavturner Jul 21, 2010 10:02 AM (in response to mavturner)
Scroll to the bottom of the Subnet Properties pop-up. You should see an option that says "Disable Neighbor Scanning". This is checked (disabled) by default. When you un-check it, additional options will appear where you can add the IP of the neighbor device.
- option.jpg 31.1 K
Re: Orion IPAM 1.7 Release Candidatemattjenkins Jul 23, 2010 11:28 AM (in response to mavturner)
My upgrade went fine but im having problems setting up IPAM with a Cisco DHCP server (seems to only affect switch's)
When testing the credentials i get:
Test Failed
Pools data processing with error 'Invalid input detected' at command 'show ip dhcp pool'
When i log in to the switch i have the dhcp server running on, the command is not vaild (may be an IOS version issue)? as apposed to IPAM...
Anyone else manage Cisco DHCP on switch's?
Re: Orion IPAM 1.7 Release Candidatemavturner Jul 23, 2010 5:41 PM (in response to mattjenkins)
Matt,
Can you provide a little more information about your environment? Specifically, IOS verion, hardware, and scope configuration? Do you have multiple switches providing DHCP or just one? If multiple, do you get the exact same error on all of them?
Also, you can definitely open a case with support if you would like more direct assistance.
Thanks,
Mav
Re: Orion IPAM 1.7 Release Candidatemattjenkins Jul 26, 2010 3:28 AM (in response to mavturner)
Hi Mav,
They are all Catalyst 2960's and all running 12.2(25)SEE4
Config is as below subject to subnet size etc.
ip dhcp excluded-address 10.248.90.48 10.248.90.55
ip dhcp excluded-address 10.248.90.61 10.251.70.63
!
ip dhcp pool site_scope
import all
network 10.248.90.48 255.255.255.240
domain-name mydomain.com
default-router 10.248.90.49
dns-server 1.1.1.1 1.1.1.1
It doesn't seem to be a config problem as i have the same config on 2811's and they respond to IPAM correctly.
I havnt opened a case yet as i wanted to see if any one else see's this problem.
Re: Orion IPAM 1.7 Release Candidatebrian@rdu Jul 26, 2010 12:24 PM (in response to mavturner)
1.7 installed fine, but post-install, my DHCP servers are red and all the subnets are offline. I test the credentials and even reentered the password, both times the credentials pass. I even went ahead and removed the DHCP servers completely, then re-added . . . looked like progress, but they are red again.
I also ran the command net use \\dhcpserveripaddress\ipc$ /USER:DOMAIN\Account from my Orion server and got a successful response.
The credentials worked in 1.6.
Re: Orion IPAM 1.7 Release Candidatemavturner Jul 29, 2010 3:10 PM (in response to brian@rdu)
Thanks for all of the great feedback on the first round of this release candidate. We have addressed all of the issues that were raised and prepared the next RC for IPAM.
I will be sending this new RC out to everyone who recieved the original one. If anyone else would like the new RC, simply send me an email and I'll make sure you are provisioned the new RC in your customer portal (assuming your IPAM maintenance is active).
Thanks again!
Re: Orion IPAM 1.7 Release Candidatemattjenkins Aug 2, 2010 4:35 AM (in response to mavturner)
Hi Mav,
I have run the RC2 with no problems. All good!!!
Re: Orion IPAM 1.7 Release Candidatejasadelll Aug 5, 2010 1:17 PM (in response to mavturner)
Installed RC2. Then added a Cisco 2620XM and selected SSH. It "tested" ok and I was able to add it. However, when I do a Scan, it gets to 33%, then errors out with the following:
" Dhcp Server scanning failed with error:Exclusions data processing with error 'Invalid input detected' at command 'show running-config | inc exceed' "
Now I am able to issue that command on the router directly. I will tell you that I have 85 exceptions (long story). I wonder if I exceeded some maximum?
JD
Re: Orion IPAM 1.7 Release Candidatemavturner Aug 5, 2010 1:51 PM (in response to jasadelll)
Please open a ticket for this.
Do you mind elaborating on the long story My guess is it directly impacts how we are handling the Cisco DHCP scopes.
Re: Orion IPAM 1.7 Release Candidatejasadelll Aug 5, 2010 2:02 PM (in response to mavturner)
I opened a case.
Sure, I can elaborate. I use a router to lease IP addresses via DHCP to all of my "guest" subnets at each of my remote locations. We reserve the top few and bottom few addresses in each scope for static assignment, such as devices and/or servers. So this router has several scopes, each with two ranges of reservations.
JD
Re: Orion IPAM 1.7 Release Candidatedmcconnell Aug 5, 2010 2:35 PM (in response to jasadelll)
Installation was quick and easy on NPM 10 SP1. I noticed there is no longer a "SolarWinds IPAM Information Service", is that correct?
Thanks,
David
Re: Orion IPAM 1.7 Release Candidatemavturner Aug 5, 2010 4:06 PM (in response to dmcconnell)
David, I'm glad your install was quick and easy!
You are correct, IPAM is now using the SolarWinds Information Service instead of the SolarWinds IPAM Information Service. Nothing to worry about there :-)
Re: Orion IPAM 1.7 Release Candidateaaron_daniels Aug 5, 2010 4:57 PM (in response to mavturner)
Any chance the new release has any kind of account limitation as in NPM?
Thanks,
Aaron
Re: Orion IPAM 1.7 Release Candidatemavturner Aug 5, 2010 5:39 PM (in response to aaron_daniels)
Aaron,
Unfortunately not. This is something we are looking at for a future release. Can you tell me a little more about what you would like to see?
Mav
Re: Orion IPAM 1.7 Release Candidatemattjenkins Aug 6, 2010 3:11 AM (in response to mavturner)
Mav,
Like Aaron im a bit disapointed that account limitations wernt in 1.7, they have been on the wish list since IPAM was released.
For me, i should be able limit accounts on any level of group, supernet, and subnet, eg.... a user has read-only right except for subnet 192.168.2.0/24 where they have operator rights, or a user has operator right's for all groups/and below except for group 'internet' where they only have read only. etc etc....
Re: Orion IPAM 1.7 Release Candidateaaron_daniels Aug 6, 2010 4:40 AM (in response to mavturner)
In NPM we have a custom property called 'department' and in each account we restrict each account to their department.
To follow the same method it would be nice to create a custom property on each subnet, and restrict access based on that.
Thanks,
Aaron
Re: Orion IPAM 1.7 Release Candidatemandg Sep 7, 2010 10:56 AM (in response to aaron_daniels)
I agree, Aaron. I'm on the search for this very same feature - to isolate views for different users test subnets from production subnets.
Re: Orion IPAM 1.7 Release Candidatemavturner Sep 7, 2010 11:41 AM (in response to mandg)
mandg,
If you are just looking for different views, you can filter Top Subnet view resources by clicking Edit on the resource and providing a SQL filter.
For more expanded functionality, please see the "What we are working on..." thread here: If you're curious as to what we're working on for Orion IPAM...
Mav
Re: Orion IPAM 1.7 Release CandidateQuestionario Oct 22, 2010 5:44 AM (in response to mavturner)
whats this 1.7.1? there dont seem to be any notes as to what has changed in the zip file...
Re: Orion IPAM 1.7 Release Candidatemavturner Oct 22, 2010 9:21 AM (in response to Questionario)
Questionario,
I will get with you offline to discuss this. 1.7.1 will be entering customer acceptance soon and the release notes have not been published yet.
Thanks,
Mav
Re: Orion IPAM 1.7 Release CandidateQuestionario Aug 23, 2010 2:37 AM (in response to mavturner)
give us the final :D
Re: Orion IPAM 1.7 Release Candidatemattjenkins Aug 23, 2010 5:50 AM (in response to Questionario)
Ive found a 'problem' thats not documented (and i have logged a support case) whereby if i was pre-allocating a static IP address for something i would set it to reserved, once the device came on the network it would change to used though the scanning process....
This has now changed in 1.7 (RC2 at least) where reserved is actually a reserved IP address (such as subnet address and broadcast address and therefore any you want to reserve out to not be used at all....) as apposed to a pre-allocated (and in my terms reserved) IP address.
Re: Orion IPAM 1.7 Release CandidateQuestionario Aug 23, 2010 12:19 PM (in response to mattjenkins)
umpf, really?!?
I originally also thought that reserved meant reserved but we got so used to it changing into used if the scanning is turned on that we now use reserved+no scanning if we really reserve something that does not come online usually but we also reserve IPs for projects so they dont get used in several projects and when they try to go live they both got the same ip...
in that case, the reserved IP would go into used state and automatically pull all info once that server goes life and no changes are necessary.
it would really **** if that would just be changed as I wouldnt know what to do in this use-case anymore...
Re: Orion IPAM 1.7 Release Candidatemavturner Aug 24, 2010 9:10 AM (in response to Questionario)
Thanks for reporting this Matt. We are addressing it now. I'll get with you offline about the latest release.
If anyone else is interested in the latest release. Please contact me and I'll make sure you get it.
Questionario, we're almost ready for the final release :-)
Re: Orion IPAM 1.7 Release Candidatemattjenkins Aug 24, 2010 11:18 AM (in response to mavturner)
Thanks Mav
Re: Orion IPAM 1.7 Release Candidatemattjenkins Aug 27, 2010 5:24 AM (in response to mattjenkins)
RC4 has resolved the 'reserved' issue
Re: Orion IPAM 1.7 Release Candidatemavturner Aug 27, 2010 5:33 PM (in response to mattjenkins)
Questionario,
This problem has been fixed and now behaves as expected :-)
Let me know if you have any concerns.
Re: Orion IPAM 1.7 Release CandidateQuestionario Aug 30, 2010 5:55 AM (in response to mavturner)
What does "as expected" mean?
Did it change? if so, in which way?
and when will the final come out? :D
Re: Orion IPAM 1.7 Release Candidatemavturner Aug 30, 2010 10:00 AM (in response to Questionario)
If you are running 1.6 now, it will behave the same way in 1.7. There are no changes in how statuses have changed.
It will be out VERY soon :-)
Re: Orion IPAM 1.7 Release CandidateQuestionario Sep 2, 2010 10:35 AM (in response to mavturner)
it did indeed come out VERY soon =)
btw, I was wondering...
IPs that are found in the ARP table but not by ICMP, are they marked as Used?
can you somehow differ between the ones found via ICMP and the ones only found via bridge-mib?
Re: Orion IPAM 1.7 Release CandidateQuestionario Aug 24, 2010 11:30 AM (in response to mavturner)
Mav, is it really true that in the final the way Reserved works will be changed?!?
Re: Orion IPAM 1.7 Release Candidateromkon Aug 6, 2010 7:25 AM (in response to jasadelll)
JD,
test fo Cisco does not run command 'show running-config'. This command is usually configured to require higher enable level than 'show ip dhcp' command used during test.
Error message: 'Invalid input detected' at command 'show running-config | inc excluded' means that given command is unknown in current enable level.
Please try to configure related cisco credential to enable level 15. Hope that will help.
Re: Orion IPAM 1.7 Release Candidatejasadelll Aug 6, 2010 7:56 AM (in response to romkon)
Yep, that was it. Thanks romkon.
I guess I would suggest a few modifications in the next release to make this a bit more "dummy-proof":
My 2 cents.JD
- When <no enable login> is selected, blank out the 'Enable Password' field. Perhaps a blurb there that 'enable 15' is needed to scan for DHCP scopes would be handy?
- I would make the protocol under 'Advanced' visible without having to click 'Advanced' to expand the field. I bet most people use SSH to communicate with their equipment. (If they don't, they should consider it).
- In 'Advanced', when the Protocol radio button is changed from the default 'Telnet' to 'SSH', change the 'Port' field from 23 (default telnet) to 22 (default SSH) and vice-versa. Now leave it so that they can override and change the port number, just in case for whatever reason people do SSH over some port other than 22, etc.
- Make it so you can edit existing credentials in the same place where you can edit DHCP servers, rather than having to navigate to Settings/IPAM Settings to adjust.
Re: Orion IPAM 1.7 Release CandidateQuestionario Aug 10, 2010 5:34 AM (in response to jasadelll)
Sounds like IPAM 1.7 will be out soon, looking forward to it!
Re: Orion IPAM 1.7 Release Candidatejasadelll Aug 19, 2010 1:19 PM (in response to mavturner)
I have a case open for this, but I thought I would pass in on to this thread as well.
If I EDIT my Windows 2003 DHCP Server, and Test the credentials, the test finds 110 scopes. However, if I SCAN the same server, it only finds 2 scopes. I have a Cisco router DHCP server as well, and it finds all of it's scopes. How can I make the scan of the Windows DHCP server find the rest of the scopes?
Support replied back that this was a known bug in v1.6, but of course I am running v1.7 now.
Re: Orion IPAM 1.7 Release Candidatejasadelll Aug 19, 2010 3:11 PM (in response to jasadelll)
Whoops I was only at RC2. I upgraded to RC3. Afterward I had to actually delete and re-add the DHCP server. Simply re-scanning didn't do the trick. It works great now.
Re: Orion IPAM 1.7 Release Candidatebrian@rdu Aug 2, 2010 7:40 AM (in response to brian@rdu)
Roman and Mav - helped me out with 1.7. Works great. I really like the neighbor scanning.
Here's a tip for anyone looking to figure out how to have the Scope Name with the Subnet Name in the Discovered Subnets Folder:
Using Database Manager, I found the Table “IPAM_Group” that includes the FriendlyName and Comments fields. As it turns out the Discovered Subnet entry as well as the DHCP Scope Entry are right next to each other, so I can replace them one by one in the database.
Re: Orion IPAM 1.7 Release Candidatebrian@rdu Aug 2, 2010 7:45 AM (in response to brian@rdu)
Feature Request for IPAM 1.8?
Orion manages switches thus can query the MAC table and has knowledge of the interfaces (or ports on a switch) . . .
IPAM now has IP scans with the neighbor scanning can see the MAC table . . .
How about finding a way to search by an IP address and have Orion report back to you the physical switch port the IP is connected to? Does anyone know of a way to do this already?
Re: Orion IPAM 1.7 Release Candidatebriancartledge Aug 5, 2010 8:49 AM (in response to brian@rdu)
No problems so far with RC2. I've added a couple of sites with IOS DHCP.
Just some general feedback. It took me a couple of attempts to get the test credentials working, initially I didnt notice that changing the protocol radio button from telnet to ssh wasn't automatically changing the port number in the field underneath.
Re: Orion IPAM 1.7 Release Candidatemavturner Aug 5, 2010 12:31 PM (in response to briancartledge)
Thanks for the feedback Brian and Brian. Adding additional information into an address is something we are looking into but not currently working on.
You are correct, changing protocols does not automatically change the port. We can look at changing this behaviour in a future release if it causes problems for a lot of users.
Mav | http://thwack.solarwinds.com/message/121930 | CC-MAIN-2014-10 | refinedweb | 3,695 | 73.98 |
I'm trying to get an applet to work but i get this error in eclipse : JAR export finished with warnings. See details for additional information.
Exported with compile warnings: HelloWorldWeb/src/HelloWorldWeb.java.
The jar file exported but does not seem to work. When I open the html file to load the applet I get a noclassdef error. Here is the code. All files are in the same folder.
//HTML//HTMLCode:import acm.graphics.*; import acm.program.*; public class HelloWorldWeb extends GraphicsProgram{ public void run(){ add(new GLabel("hello, world"), 20, 20); } }
Code:<html> <title>Hello World</title> <applet archive = "HelloWorldWeb.jar" code = "HelloWorldWeb.class" width = 300 height = 150> </applet> </html> | http://forums.devshed.com/java-help-9/applet-hello-world-947141.html | CC-MAIN-2015-18 | refinedweb | 112 | 53.17 |
The Replace Conditional with Polymorphism Refactoring is rather simple and it is pretty much exactly what it sounds like. You have a method with a conditional like this:
def speed case @type when :european then base_speed when :african then base_speed - load_factor * @number_of_coconuts when :norwegian_blue then if nailed? then 0 else base_speed(@voltage) end end
and you replace it with polymorphism like this:
class European def speed base_speed end end class African def speed base_speed - load_factor * @number_coconuts end end class NorwegianBlue def speed if nailed? then 0 else base_speed(@voltage) end end
You can apply the Refactoring again to
NorwegianBlue#speed by creating a subclass of
NorwegianBlue:
class NorwegianBlue def speed base_speed(@voltage) end end class NailedNorwegianBlue < NorwegianBlue def speed 0 end end
Voilà, all your conditionals are gone.
You might ask yourself: does this always work? Can I always replace an
if with message dispatch? And the answer is: yes, you can! In fact, if you didn't have
if, you can implement it yourself using nothing but message dispatch. (This is, in fact, how Smalltalk does it, there are no conditionals in Smalltalk.)
class TrueClass def iff(thn:, els: ->{}) thn.() end def & yield end def | self end def ! false end end class FalseClass def iff(thn:, els: ->{}) els.() end def & self end def | yield end def ! true end end (3 > 4).iff(thn: ->{ 'three is bigger than four' }, els: ->{ 'four is bigger than three' } ) # => 'four is bigger than three' true.& { puts 'Hello' } # Hello true.| { puts 'Hello' } # => true
Also relevant: the Anti-
IF Campaign | https://codedump.io/share/4cd9niYvQ2YU/1/what-is-replace-conditional-with-polymorphism-refactoring-how-is-it-implemented-in-ruby | CC-MAIN-2017-09 | refinedweb | 254 | 73.78 |
Hi Erkki,
I'm going to start trying out a BBAPI rewrite using ECF and I have some questions about how to best use ECF concepts like namespaces & IDs.
So far it seems to me that when I have for example a phpBB provider, it should have a namespace like "ecf.phpBB".
I thought of making several object classes of bulletin boards "IIdentifiable": forums, threads, single posts, users (and some more). So for example a forum's ID within the "ecf.phpBB" namespace could have it's URL as the name i.e.
Is this the right approach, or should IDs be used mainly for user accounts?
Another problem: if a user account's ID is represented by it's URL and the URL is something like then: if the login asks for only username and password, then the URL representation (that contains the users numeric ID in phpBB) becomes known after actually connecting and successfully logging in -- that means it won't be known offline, but as I understand so far, ECF ID-s should be fully defined offline as well? Or is it ok to make a network connection while creating an ID?
Thanks. Erkki please continue to let us know how we can help.
Scott
Erkki _______________________________________________ ecf-dev mailing list ecf-dev@xxxxxxxxxxx | https://www.eclipse.org/lists/ecf-dev/msg00325.html | CC-MAIN-2019-26 | refinedweb | 217 | 67.69 |
Duck Typing and Protocols vs. Inheritance
According to irb,
>> StringIO.is_a?(IO)
>> => false
This seems illogical to me. Is this intentional? If so, why?
One answer to this:
Since StringIO doesn't use IO to base its implementation, it is not an IO.
Why does it matter? If you use standard duck typing, it shouldn't. Class hierarchy doesn't matter with duck typing. Classes are just an implementation detail with duck typing. You are best off not looking #is_a?, #respond_to?, etc. Just assume the object can do the methods you'll be using and use.
This sounds like the basic idea of duck typing: instead of requiring an object to be of a certain type, it suffices that the object responds to a set of methods.
None of this is new or specific to Ruby. By replacing the word "methods" with the OOP term "messages", the above statement reads: "[...] it suffices that the object responds to a set of messages". This does sound a lot like the idea of a (network) protocol. After all, a system that understands and responds to messages such as "PUT", "GET", "POST", etc. sent to it in a certain manner, can be said to understand the HTTP protocol.
Let's go further with this idea: a client, say a web browser, only cares that a server it communicates with understands HTTP; it does not require the server to be of a certain type or make. After all: the web would have had a harder time growing, if, say, the Mosaic browser had been hardcoded to require the server on the other end of the line to be NSCA's or Netscape's HTTP servers. By ignoring the other end of the communication, and only requiring that a "GET" is answered in a certain way, both ends of the webs development (client, server) were able to evolve independently.
The similarity of this approach to protocols was clear to users of OOP languages long ago. Smalltalk and ObjectiveC, both dynamic OOP languages, have long used the term Protocol to refer to this concept.
The Protocol concept is certainly useful, if only to give a name to a particular set of messages. This also helps with clearing up the questions raised in the above mailing list post. What the StringIO and IO share is not common ancestry but a common Protocol.
The concept is certainly not limited to dynamic languages. On the more static side, Java made a crucial step by introducing
interfaces, as a way of:
- naming a set of messages
- statically checking that a class actually implements them
Of course, as is often the case with static guarantees, interfaces only check the presence of a set of methods with certain signatures - it doesn't guarantee the behavior or even the returned values of the methods. It's not even guaranteed that the method is invokable - it's still prudent to watch out for Java's
java.lang.UnsupportedOperationExceptionwhen working with, say, Java's Collection API.
Interfaces do have their own share of problems, such as evolvability. Changes to an interface are breaking changes for all classes implementing it. Big projects, such as Eclipse, have guidelines for API evolution, which rule that an interface can't be changed once it's been published. This sometimes yields the advice to favor Abstract classes over interfaces, since Abstract classes can add new functions, but define empty implementations, so subclasses can, but don't have to implement them. This problem could, of course, be solved by making fine grained interfaces, with one method each, and building the full interface up with new interfaces that extend the previous ones, each adding a single API call.
The problem of ensuring that an object supports a Protocol could of course be solved in Ruby by delegating the interface check to a predicate function. An example:
def supports_api?(obj)While this works, it's also fraught with subtle problems -
obj.respond_to?(:length) && obj.respond_to?(:at)
end
respond_to?only works with methods defined in a class. If an object implements parts of its interface with
method_missing(e.g. a Proxy),
respond_to?would return false to these methods, although a call to these methods would work. This means that
respond_to?checking can work, but it's not a drop-in replacement for static checks (Rick de Natale refers to this coding style as "Chicken Typing", i.e. it's a kind of defensive programming).
Another, static, approach to fine grained interfaces are Scala's Structural Types:
def setElementText(element : {def setText(text : String)}, text : String) =This function requires the argument
{
element.setText(text.trim()
.replaceAll("\n","")
.replaceAll("\t",""))
}
elementto have a
setText(text:String)method, but does not care about the particular type of the object.
The focus on specific types or class hierachies of an object also limits the flexibility. An interface that requires an
intparameter can only be called with an int or - through AutoBoxing - an Integer, but nothing else. A method that just requires the object to have an to_i method (that returns an integer number, either Fixnum or BigNum) is more flexible in the long run. Classes not under the developers control might not inherit from the needed classes, although they might still support a particular Protocol.
Somewhere between the dynamic (duck typing) and static (interfaces, Scala's Structural Types) are Erlang's Behaviors. Erlang's modules (which are comparable to Ruby's Modules) group functions together. A module can use
-behaviour(gen_server).to state that it implements the Behavior
gen_server- which means that it exports a certain set of functions. This is supported by the Erlang compiler in that it complains if the module doesn't export all of the Behaviors required functions.
This also shows that the general principle of Protocols is not limited to languages that define themselves as "OOP" languages by providing concepts of Class, Object, Inheritance, etc.
How do you document the use of Protocols in Ruby, i.e. how do you talk about the set of messages that interacting objects need to agree upon?
In Groovy
by
Steven Devijver
But in Groovy you can implement methodMissing() so that methods that are called are added to the type. Next time you call this method it will directly go to that method and no longer through methodMissing(). repondsTo() would also recognize this method after the first invocation.
Grails uses this approach all over the place. See one of Graeme's talks on the Grails Exchange for more details.
Also in Groovy, when I realize a method I expect to be there isn't I just add it using ExpandoMethodClass. In this way anything can be turned into a duck.
Re: In Groovy
by
Michael Neale
Is it becuase I'm Canadian? or..
by
Deborah Hartmann
Re: In Groovy
by
Paul King
If it is for greater clarity at the source code level, in Groovy you would mix and match Java's static checking techniques with Groovy's dynamic typing capabilities. You could statically define the type of a variable (as a fine-grained interface of course) or you could implement an interface in your class definition if you wanted. These techniques provide you with a more declarative specification of your objects protocol(s) than without. That doesn't mean you abandon dynamic typing where it makes sense and you should still use fine-grained (interface-oriented programming) when thinking about interfaces anyway. It certainly puts Groovy miles ahead of many other dynamic languages for those scenarios where you want to apply a declarative style.
If it is for more robustness in your code, than you have various techniques available to you at the metaprogramming layer. In Groovy, I would possible hook into the beforeInvoke() interceptor or the methodMissing() level if needed. Groovy is a little bit more powerful (but mostly on par) with other dynamic languages in this regard.
Python and Zope interfaces
by
Kevin Teague
Zope tackled the problem by using metaprogramming to supply their own interface implementation:
griddlenoise.blogspot.com/2005/12/zope-componen...
"This problem could, of course, be solved by making fine grained interfaces, with one method each, and building the full interface up with new interfaces that extend the previous ones, each adding a single API call."
Interfaces are just a formal and semi-formal way of describing a specification. Changing the specs means breaking existing code. Interfaces in Zope are usually inherited in a fine-grained manner. Not always as fine-grained as one method or attribute per interface, but it is good design have each interface as small as makes sense, and add new functionality by layering on more specific interfaces.
The real joy though is when you can apply these same principles of interface specificity when doing data modelling and working with a persistence layer that allows complex model inheritance structures without messy ORM issues ...
from zope.interface import interface
from zope.schema import TextLine, SourceText
class IBaseContent(Interface):
"Shared attributes amongst all content objects"
title = TextLine(title=u'Title')
description = SourceText(title=u'Description')
class IDocument(IBaseContent):
"Plain document"
body = SourceText(title=u'Body')
class INewsItem(IDocument):
"News Item"
slug = SourceText(title=u'Slug for lead-in text')
You can declare that an object provides and implementation "after the fact" with the Zope Component Architecture. That is, you can use the equivalent of method_missing, or open a Class and add the required methods, and then declare that your object or class now provides a certain interface.
>> class Whatever(object):
... "some random plain old object"
...
>>> random_obj = Whatever()
>>> random_obj.>> random_obj.>> random_obj.>> interface.directlyProvides(random_obj, IDocument)
>>> IDocument.providedBy(random_obj)
True
Kind of a convoluted example, as normally you would have a concrete class that declared that it implement specific interfaces.
This can be persisted in Zope as easy as working with any normal Python object that implements a mapping interface:
>>> mydatacontainer['some-unique-name'] = random_obj
Re: In Groovy
by
Rusty Wright
public interface Graphics {
void draw();
}
public interface DeckOfCards {
void draw();
}
public final class DrawThing implements DeckOfCards, Graphics {
public void draw() {
}
}
Duck Typing.
by
Porter Woodward?
Chicken typing indeed. All the sudden you're sprinkling your code with a ton of respond_to? clauses trying to find out if a given object can respond to a particular call. On the one hand it's a workable solution - especially if you're used to programming against low-level hardware (better to ask the CPU, or GPU if it has a capability than ask what type it is and make assumptions about it's functionality). But sometimes you'd like to be able to ask - are you a chicken - or are you a duck? And get an honest answer.
And while interfaces codify this very well - you rightly point out that there is no guarantee that a given interface is even implemented correctly. There's no way to determine that in languages that don't have them anyway - just because an object .respond_to? a given method is no guarantee that the internal implementation of that method is any good.
Strongly recommend checking out Interface Oriented Programming from Pragmatic.
Re: Duck Typing.
by
Kevin Teague".
Say you have defined your interfaces as:
class IQuacker(Interface):
"It quacks!"
def quack(self):
"Make some noise"
class IDuck(IQuacker):
"Definition of a duck"
class IPlatypus(IQuacker):
"Definition of a platypus"
Then you have some basic imlementations:
class Duck(object):
implements(IDuck)
def quack(self):
print "Duck noise is the only noise!"
class Platypus(object):
implements(IPlatypus)
def quack(self):
print "Platypus noise is better than duck noise!"
Then in your client code:
>>> platypus = Platypus()
>>> IQuacker.providedBy(platypus)
True
>>> IPlatypus.providedBy(platypus)
Ture
>>> IDuck.providedBy(platypus)
False
Without interfaces, this distinction is possible but needs to deal with
implementation specific details:
>>> platypus = Platypus()
>>> hasattr(platypus,'quack')
True
>>> isinstance(platypus,Platypus)
True
>>> isinstance(platypus,Duck)
False
In the second case, where you are programming to an implementation, your
code would not work if you had a test suite that used a mock implementation:
class MockPlatypus(object):
implements(IPlatypus)
def quack(self):
pass
This mock object will still pass the method names check, but because it
has a different implementation class the check for the Class type will not
act as desired.
Sounds familiar...
by
Rickard Öberg
By focusing on interfaces, and allowing an object to easily implement as many interfaces as are necessary without having to use class inheritance or manual delegation to implement it, it becomes a lot easier to write and (re)use code.
Re: Duck Typing.
by
Porter Woodward".
I agree to an extent. However there are times when the implementation becomes important. Hence my mention of low-level interfaces: CPU and/or GPU. Sometimes you really need to know whether something is implemented - and _how_ it's implemented. For a lot of high-level applications programming - absolutely the goal should be to program to the interface. Hence my cite of Interface Oriented Design at the end of my post.
Even in higher level application programming sometimes you need to _know_; for example you might have abstracted away a lot of your persistence to a database. It can still be important to know some details about the underlying database implementation. Ideally those are encapsulated in the persistence layer - but the persistence layer will do those queries to determine the functionality of the underlying database, and specifically _how_ certain features are implemented in order to provide a common interface to users of the API regardless of the underlying implementation.
So - while it's all very well and good to say the GOF say to program to interfaces - there also needs to be the realization that sometimes to produce an elegant interface the code underneath may have some very un-OOP properties. In order to make that process a little easier it can be handy to have features that allow a high degree of introspection (is_a, responds_to, etc.). Both from the perspective of building working code - and building tools to work with the code - such features make it a little easier to reverse engineer a working code base - and can make automated refactorings a little easier.
Re: Duck Typing.
by
John DeHope
I think if architects first demanded code be driven by the code layer (as I have defined it) and only then by the application layer, we'd get better enterprise code. My point is that I find it worse to see data-access layer code that has generic library and custom business logic mixed in together, than it is to have controllers with a bit of data-access and user-interface code mixed together.
Let me say that another way... I'd rather see application code that communicates with two different app-layers, but both through interfaces rather than implementations, than I would to see code that communicates with low-level library or system implementations and higher-level interfaces.
Regarding Chicken Typing
by
Craig McClanahan
method_missing?()would give incorrect answers for the
respond_to?()test. That is true if you rely on the default inherited implementation. However, an intelligently designed class that uses this sort of dynamic implementation is also free to override
respond_to?()so that it works as expected.
An example of this technique is the way that <code>ActiveRecord::Base</code> overrides
respond_to?()to return true for all the attribute getters and setters inferred from the underlying table, even though these methods are not directly declared.
commonalities in class hierarcy
by
Arash Bizhanzadeh
StringIO and IO don't need to go back to the same superclass, because they don't share any commonalities except one: a set of methods they support.
I am a little confused here. Isn't the methods most important characteristics of classes? If they share a set of similar methods, I assume that they have something in common.
On the other hand if the concept of duck typing and protocols could be adopted, why should somebody bother with inheritance?
Re: Duck Typing.
by
Kevin Teague
Sometimes you really need to know whether something is implemented - and _how_ it's implemented.
Using interfaces does not have to mean that you should or need be detached from implementation details. In the end, it's the implementations that do all the work.
Going back to the Zope Component Architecture, it's possible, and common, for your implementations to be named, and then you can ask for a specific implementation by name. If you had an ORM Interface and two implementations:
class ISimpleORM(Interface):
def do_orm_stuff(self, data):
"worlds worst ORM interface"
class GenericPoorPerformingORM(object):
implements(ISimpleORM)
def do_orm_stuff(self, data):
# bunch of implementation details
class MySQLSpecificORM(object)
implements(ISimpleORM)
def do_orm_stuff(self, data):
# bunch of MySQL-specific implementation details
Then you might use specific implementations by registering those implementations and querying for them:
# registration (usually done in XML or with 'convention over configuration')
component.provideUtility(GenericPoorPerformingORM(), ISimpleORM, 'generic')
component.provideUtility(MySQLSpecificORM(), ISimpleORM, 'mysql-tuned')
# later on in your application code
ORM_IMPLEMENTATION = 'mysql-tuned'
orm = component.getUtility(ISimpleORM, ORM_IMPLEMENTATION)
Traits
by
Alejandro Gonzalez...
It helps to construct classes by composing them from behavioral building blocks (called traits), so a class can respond to complete set of protocols without having to use inheritance as the fundametal tool for it.
It's not a concept to replace single inheritance but to complement it. Also helps a lot in code reuse.
It was already implemented in Squeak (an open source Smalltalk dialect) and IMHO is a promising concept.
Re: Traits
by
Kevin Teague
Smalltalk's Traits is very similar to Python's zope.interface and Perl 6 is also applying the same concept and calling it Roles. They all differ somewhat in the details, but they all aim to solve the problem as eloquently stated in the Smalltalk paper, "The purpose of traits is to decompose classes into reusable building blocks by providing first-class representations for the different aspects of the behaviour of a class."
Re: Is it becuase I'm Canadian? or..
by
Keith Thomas | http://www.infoq.com/news/2007/11/protocols-for-ducktyping/ | CC-MAIN-2015-35 | refinedweb | 2,988 | 53.92 |
June 18, 2008.
Today I spent a couple of hours reworking Ambush Code Review, and its turned into something much better than the first implementation. There are two important changes:
Before, it was pretty awkward to post a response to a code snippet. I mean, I sure as hell knew how it worked, but I'm not sure if anyone else knew, and it was a pretty unhappy compromise anyway. Now, its just two button clicks to update a posted snippet with your changes. But the really interesting new feature is that it now generates the diffs between different revisions of a snippet, and displays them beneath the current version of the snippet.
You can go take a look at the snippet that screenshot is from, and I think it turns out to be a pretty compelling feature, since the whole point of ACR is to make it easier for people to suggest improvements to snippets (for example, when people post snippets into an IRC chatroom looking for help, wouldn't it be nice to actually be able to show them how to fix it?).
I'd be glad to hear any responses, now that its taken a step from being a shoddy me too service to something slightly more interesting.
Now for a quick discussion about implementing the diffs between different revisions. Things didn't quite go as expected, in the sense that it was easy in the places I thought it would be hard, and hard in the places where I thought it would be easy. Live and learn.
The easy part was actually generating the snippets themselves. The difflib module, part of the standard Python library, really makes this task trivial. The relevant code looks something like this (go here to improve upon this snippet, I'm kind of baffled about how to correctly handle the generator returned by the unified_diff function..):
from difflib import unified_diff def set_content(self, new_content): 'Handles all details of updating snippet content.' # if this is not a new Snippet if self.rendered != None: result = unified_diff(self.content.splitlines(1), new_content.splitlines(1)) try: txt = reduce(lambda a,b: u"%s%s" % (a,b), result) self.add_diff(txt) except TypeError: pass self.content = new_content lexer = get_lexer_by_name(find_lexer(self.highlighter)) self.rendered = highlight(self.content,lexer,HtmlFormatter(linenos='table'))
Which is to say, that I don't really do anything at all to generate the code diffs, other than simply calling a module function. But things did get a little bit trickier afterwards.
The problem began because the db.ListProperty property used to describe a field in BigTable requires a type argument. Sure, no problem. And it requires that it be one of a specific list. Sure, tons of choices there, no problem. And it needs all the entries in one list to be of the same type. Hey, I only want to store diffs, so they'll all be the same, no problem. And it apparently ignores you when you set the db.Text property type and complains that unicode types can't store more than 500 bytes in the database. Well, thats a problem.
Instead, I jury-rigged my own list with some old style ingenuity and some new style obliviousness to the consequences. Using... simplejson to serialize and deserialize.
from django.utils import simplejson def add_diff(self, diff): if self.diffs == None: diffs = [] else: diffs = simplejson.loads(self.diffs) diffs.insert(0, diff) self.diffs = simplejson.dumps(diffs) def get_diffs(self): 'Unserializes and returns the contents of self.diffs' return simplejson.loads(self.diffs)
I wouldn't say that this is a brilliant solution, or even a good solution, but it is a good enough solution, which seems to be what web applications boil down to eventually. Hits to the database are minimized, and CPU is almost never the restrictive factor in web development. You may wonder why I went with simplejson instead of using pickle, and its turns out the answer is quite simple. As in, simplejson is very convenient to work with, and saved me from having to use a StringIO to mimic a file for pickle to serialze and deserialize with.
Hope this breakdown of the code was slightly interesting, and let me know if there are any questions. | https://lethain.com/ambush-code-review-learns-code-diffs/ | CC-MAIN-2019-51 | refinedweb | 711 | 56.35 |
Updated: April 28, 2009
Applies To: Microsoft Search Server 2008
Updated: 2009-04-28
Unless otherwise noted, the information in this article applies to both Microsoft Search Server 2008 and Microsoft Search Server 2008 Express.
Content is any item that can be crawled, such as a Web page, a Microsoft Office Word document, business data, or an e-mail message. Content resides in a content repository, such as a Web site, file share, or SharePoint site. A content source specifies settings that define how and on what schedule content is crawled. It includes one or more addresses of a content repository from which to start crawling, also named start addresses. These settings apply to all start addresses within the whole content source.
If your organization has to crawl only the content that is contained in the SharePoint sites, you might not have to create an additional content source. Search Server 2008 defines a default content source during its initial deployment. The default content source is named Local Office SharePoint Server sites. The start addresses of all Web applications in the server farm are automatically included as part of the default content source. This content source is not crawled, by default. To index the content in the default content source, you have to either manually start or schedule crawls for it.
When you create a content source, you specify settings that define the kind of content it crawls, when the content is crawled, and crawling behavior, such as how deep to crawl within the namespace of the start address or how many server hops to allow. If you have multiple kinds of content repositories that you want to crawl, or you want crawl some content repositories on different schedules, you have to create additional content sources. Search Server has one Shared Service Provider (SSP) that supports up to 500 content sources. For more information, see the “Plan content sources” section of Plan to crawl content (Search Server 2008). For more information about how to configure crawling behavior, see Limit or increase the quantity of content that is crawled (Search Server 2008).
You can crawl only one kind of content per content source. That is, you can create a content source that contains URLs for SharePoint sites and another that contains URLs for file shares. But you cannot create a single content source that contains URLs for both SharePoint sites and file shares.
The following table lists the kinds of content that Search Server can crawl and index:
SharePoint sites
SharePoint sites from the same farm or different Microsoft Office SharePoint Server 2007, Windows SharePoint Services 3.0, or Search Server 2008 farms
SharePoint sites from Microsoft Office SharePoint Portal Server 2003 or Microsoft Windows SharePoint Services 2.0 farms
The Search Server 2008 crawler can automatically crawl all Office SharePoint Server 2007, Windows SharePoint Services 3.0, and Search Server 2008 sites and subsites. The crawler can crawl previous versions of SharePoint products and technologies. But you must specify the URL of each top-level site (site collection) and each subsite that you want to crawl.
Sites listed in the Site Directory of Microsoft Office SharePoint Portal Server 2003 farms are crawled when the portal site is crawled. For more information about the Site Directory, see About the Site Directory ().
Web sites
Web content within your organization not found on SharePoint sites
Content on Web sites on the Internet
The crawler behaves in the same manner when it uses the Web sites content type or the SharePoint sites content type. Only the crawl settings that you can configure for these content source types differ.
File shares
Content on file shares within your organization
Exchange public folders
Microsoft Exchange Server content
Lotus Notes
Content stored in Lotus Notes databases
The Lotus Notes content source option does not appear in the user interface until you have configured the index server to work with Lotus Notes. For more information, see Prepare to crawl Lotus Notes (Search Server 2008).
Each content source maintains a list of start addresses that the crawler uses to connect to the repository of content. Each content source can contain up to 500 start addresses. You cannot crawl the same address using multiple content sources. For example, if you use a particular content source to crawl a site collection and all its subsites, you cannot use a different content source to crawl one of those subsites on a different schedule.
You can use a content source to manually start a crawl or schedule when and how often the selected content source is crawled. If you want to crawl content in a part of your content source on a different schedule, you must create a separate content source for that content. For performance and manageability reasons, we recommend that you use as few content sources as possible. For more information about starting a crawl manually or scheduling a crawl, see Crawl content (Search Server 2008).. By default, Search Server uses the default content access account and uses NTLM when authenticating with servers. For more information, see Configure how the crawler authenticates (Search Server 2008). | http://technet.microsoft.com/en-us/library/bb905388(office.12).aspx | crawl-003 | refinedweb | 852 | 59.53 |
Well I have this 2nd year course for C++ where I have to write programs depending on the explanation and objectives of what the program should do. But i am having trouble to write them...
I was wondering if anyone would tell me how to start of a program that you will write and all you know is what the program must do.
say I need to write a program where there are 2 classes and a main funtion. One Employee class and one staff class..
Code:class Employee { private: char * name; // Employee's name double hourlyRate; // Hourly pay rate double hours; // Hours worked this week double taxRate (); public: Employee (); ~Employee (); void setName (char * _name); void setHourlyRate (double _hourlyRate); void setHours (double _hours); void printPayroll (); };Now I need to write the definition of each member functionNow I need to write the definition of each member functionCode:class Staff { private: int totalEmployees; Employee employees[MAX_EMPLOYEES]; public: Staff (); ~Staff (); void addEmployee (char * _name, double _hourlyRate, double _hours); int getTotalEmployees (); void printPayroll (); };
this is what I got for employee
What am i doing wrong?What am i doing wrong?Code:# include <iostream> # include "Employee.h" using namespace std; Employee::Employee() { name = new char [200]; hourlyRate = 0; hours = 0; } Employee::~Employee() { delete[] name; } double Employee::taxRate () { int anual_Income = hourlyRate * 40 * 52; if (anual_Income < 20000) { return 15;} else if (anual_Income < 30000) return 0.20; else if (anual_Income < 40000) return 0.25; else if (anual_Income < 50000) return 0.30; else if (anual_Income < 60000) return 0.35; else if (anual_Income < 70000) return 0.40; else return 0.45; } char* Employee::setName (char *_name) { name = _name; } double Employee::setHourlyRate (double _hourlyRate) { hourlyRate = _hourlyRate; } double Employee::setHours (double _hours) { hours = _hours; } void Employee::printPayroll () { double overTime = 0, hours40 = hours; if (hours > 40) { overTime == hours - 40; hours40 = 40;} double weeklyPay = hours40 * hourlyRate + overtime * hourlyRate * 1.5; double tax = taxRate() * weeklyPay; cout << *name << ": " << weeklyPay << " - " << tax << " = " << weeklyPay - tax; } | http://cboard.cprogramming.com/cplusplus-programming/108170-how-write-program.html | CC-MAIN-2015-35 | refinedweb | 316 | 61.26 |
W3C XML Schema and XInclude: impossible to use together???
Note: this entry has moved.On a project I'm working on for MS Patterns & Practices, we were excited about the XInclude spec becoming a recomendation and anxious about using it in our project, which is quite heavy on XML usage for configuration. The modularization that could be introduced transparently by XInclude was very compelling. Even if it will hardly be implemented in .NET v2, we could still take advantage of the Mvp.Xml project XInclude.NET implementation Oleg did. But apparently it's almost impossible to use XInclude and XSD validation together :(
The problem stems from the fact that XInclude (as per the spec) adds the xml:base attribute to included elements to signal their origin, and the same can potentially happen with xml:lang. Now, the W3C XML Schema spec says:
3.4.4 Complex Type Definition Validation Rules
Validation Rule: Element Locally Valid (Complex Type)
...
3 For each attribute information item in the element information item's [attributes] excepting those whose [namespace name] is identical to and whose [local name] is one of
type,
nil,
schemaLocation or
noNamespaceSchemaLocation, the appropriate case among the following must be true:
So, either you modify all your schemas to that each and every element includes those attributes (either by inheriting from a base type or using an attribute group reference), or you validation is bound to fail if someone decides to include something. Note that even if you could modify all your schemas, sometimes it means you will also have to modify the semantics of it, as a simple-typed element which you may have (with the type inheriting from xs:string for example), now has to become a complex type with simple content model only to accomodate the attributes. Ouch!!! And what's worse, if you're generating your API from the schema using tools such as xsd.exe or the much better XsdCodeGen custom tool, the new API will look very different, and you may have to make substancial changes to your application code.
This is an important issue that should be solved in .NET v2, or XInclude will be condemned to poor adoption in .NET. I don't know how other platforms will solve the W3C inconsistency, but I've logged this as a bug and I'm proposing that a property is added to the XmlReaderSettings class to specify that XML Core attributes should be ignored for validation, such as XmlReaderSettings.IgnoreXmlCoreAttributes = true. Note that there are a lot of Ignore* properties already so it would be quite natural.
Please vote the bug if you feel it's important, and better yet, think of a better solution to it!!! ;) | http://weblogs.asp.net/cazzu/XsdAndXInclude | CC-MAIN-2015-18 | refinedweb | 451 | 58.01 |
See also: IRC log
<rreck> me
<briansuda> i was second
<HarryH> scribe: Chime
<HarryH> PROPOSED: to approve GRDDL WG Weekly --4 April 2007 as a true record
<HarryH>
<john-l>
<john-l>
<HarryH> So note the real minutes are here:
<rreck> thanks
<HarryH>
<HarryH> RESOLVED to approve GRDDL WG Weekly --4 April 2007 as a true record
<HarryH> RESOLVED : approved GRDDL WG Weekly --4 April 2007 as a true record
<HarryH> Reck will be scribe next meeting.
<HarryH> Jeremy?
<HarryH> Jeremy can scribe next meeting.
<HarryH> DanC?
<HarryH> Without DanC, I suggest we move to Test Cases.
input:
outpu:
prior approval:
<HarryH> PROPOSAL: Approve as a valid test for test-case document.
<HarryH> RESOLVED: Approved as a valid test for test-case document.
jjc: prefer test approval for material, and review WD as a whole (with test text)
john-l: same preference
<HarryH> ACTION: john-l to add text to [recorded in]
<HarryH> ACTION: john-l is to add text to any tests many text where deemed appropriate. [recorded in]
Remaining tests with prior approval:
<HarryH> PROPOSED: To reapprove in bulk all tests with prior approval.
<HarryH> RESOLVED: all tests with prior approval approved.
<HarryH> PROPOSED: as a valid test for test-case document.
<HarryH> RESOLVED: as a valid test for test-case document.
HarryH: we should approve this noting that the stylesheet may be updated
FabienG: 1) difference btwn implementation 2) RDFa spec is not stable
jjc: text should reflect that the transform does not reflect a general RDFa transform
FabienG: works fine WRT the test case
FabienG: should the transform predicate be included in the output?
FabienG: at F2F - the transform is ignored
<HarryH> PROPOSAL: as a valid test for test-case document.
<HarryH> ACTION: john-l to make sure rdfa1 test case text reflects current state of rdfa [recorded in]
<HarryH> APPROVED: Given caveat about current state of rdfa, as a valid test for test-case document.
<HarryH> PROPOSAL: is a valid test for test-case document.
<HarryH> RESOLVED: is a valid test for test-case document.
<head profile="
<HarryH> PROPOSAL: is a valid test for test-case document.">
jjc: possibility that changes to the profile effected validity of output
<john-l> +1
jjc: we should copy these profiles to our test repository
<john-l> (+1 to that, rather)
jjc: would like to see the test modified in that regard
<HarryH> ACTION: jjc to do modify to keep all profiles in W3C space. [recorded in]
<jjc> ^W3C^GRDDL WG^
<HarryH> PROPOSAL: is a valid test for test-case document.
<HarryH> RESOLVED: is a valid test for test-case document.
the ns document is served as application/rdf+xml (no controversy there)
<HarryH> PROPOSED: is a valid test for test-case document.
<HarryH> RESOLVED: is a valid test for test-case document.
<HarryH> Chime: What all the controversial ones have is a "multiple output" sort of one.
the tests with maximal results are less ambiguous
jjc: for the langconneg ppl probably pass the english version but not the german version
jjc: is there a maximal result of the merge of the english and german GRDDL results?
to calculate the maximal result, dont yo uneed to know the accept headers up front?
jjc: technically possible
<DanC_lap> (I'd be happy to leave the german test in the someday pile.)
scribe: not neccessary for testing phase
<DanC_lap> (actually, the IETF rules is included in W3C process, as a SHOULD)
<DanC_lap> (is discussion of our request for CR/PR on the agenda?)
<jjc> (transparent content negotiation)
jjc: Jena reader passes the noxinclude version
[[[
* failed
ok: since raptor does do xinclude processing this is ok to fail
]]]
<HarryH> (I'm happy to discuss CR/PR is we have time. In particular, as soon as I get EARL from Jena I'll make an implementation report, but I need Jena's results and the precise number of tests to be approved)
<jjc> EARL from Jena this week ... hopefully
HarryH: as long as implementations pass noxinclude I'm happy
jjc: agrees.. but we need enough evidence
<HarryH> PROPOSAL: is a valid test for test-case document.
<HarryH> PROPOSAL: and i as a valid test for test-case document.
<DanC_lap> is the .html on purpose?
<HarryH> PROPOSAL: and as a valid test for test-case document.
<DanC_lap> 2nd
<HarryH> For previous resolutsions regards tests s/.html//
<DanC_lap> yes, s/.html#/#/g in resolutions of this meeting
<HarryH> APPROVED: and as a valid test for test-case document.
if a test passes the third, can it assume it has passed the others?
the maximal result is not isomorphic with the others
<DanC_lap> (tests don't assume anything; they're not thinking things)
<HarryH> \me asks DanC - can you take over chairing at noon? I still have these meetings at noon on Wed. till early May :(
jjc: issues with the test text
<DanC_lap> chairing... tricky... perhaps, if we start making the transition 10 minutes before you need to go.
so is "However, for the purpose of running these tests in order to determine compliance, a GRDDL-aware agent with a security policy which does not prevent it from applying transformations identified by each test will produce the GRDDL result associated with each normative test.
" authoritative
?
jjc: happy to approve number 3, and modify text of 1-2
<jjc> no delete 1-2
<jjc> annd modify text of 3
<HarryH> Note that I can't right CR transition till our test cases are fairly stable, so this test approval process is quite important.
<DanC_lap> you can start on the CR request at any time, harry. I find it's often good to work backwards from the goal
<DanC_lap> or perhaps somebody else can start on the CR request
<HarryH> ACTION: Chime and john-l to remove non-maximal tests from test-suite [recorded in]
<HarryH> ACTION: Chime and john-l to remove non-maximal tests with ones with security relevancy. [recorded in]
<DanC_lap> action -5
jjc: issues with general conneg and what the 'maximal' result is
<HarryH> ACTION: HarryH to start working on CR/PR transition report for GRDDL Spec. [recorded in]
jjc: would like to see the merge as a seperate test for conneg
<jjc> ACTION jjc to produce/check merge results involving content negotiation
<jjc> ACTION: jjc to produce/check merge results involving content negotiation [recorded in]
<HarryH> I'm happy to drop this.
<HarryH> I'm happy to e-mail IanD and ask him to drop this.
<DanC_lap> WITHDRAWN. it falls to the someday pile. bonus points to anybody who picks this up and makes progress on it.
[[[
I do notice
is not of the RDF mime type, should it really be handled
as RDF/XML?
]]]
<DanC_lap> DanC: this WG decided that the answer is yes, IIRC.
does this require the GRDDL-aware agent to attempt to parse all source documents as RDF/XML?
<HarryH> I thought there was a rule about this sort of sniffing.
<john-l> All application/xml source documents...
<HarryH> I.e. look for rdf:RDF.
the spec doesn't speak about media-type
just 'conforming RDF/XML'
<john-l> But if it's conforming RDF/XML, then it must also be XML, so anything that's not in an XML media type could not be a conforming RDF/XML document.
RDF/XML spec doesn't define conformance by anything other than the content not the media-type over the wire
<HarryH> In which case we're okay as regards RDF/XML.
<HarryH> So, one can serve RDF/XML as application/xml and still interpret it as RDF.
<HarryH> We might want to bring this up explicitly in informative text.
<HarryH> However, we should remember that we don't want to tie the spec to RDF/XML.
<DanC_lap> the relevant WG decision is under feb 7 under
<jjc>
scribe: discussion continues on what RDF/XML 'conformance' is ..
<DanC_lap> "If an information resource IR is represented by a conforming RDF/XML document[RDFX], then the RDF graph represented by that document is a GRDDL result of IR"
<HarryH> What if IR is in N3?
<HarryH> Sorry for asking the question :(
<HarryH> It's a real edge-case.
<DanC_lap> then the premise of that rule isn't satisfied and you gotta look elsewhere, Harry
<HarryH> Hmmm...
<DanC_lap> <foo/>
<HarryH> Is there a notion of RDF conformance that isn't tied to RDF/XML?
DanC_lap: is a conforming RDF/XML document
<DanC_lap> <foo xmlns="" />
<HarryH> I'll just have to re-read the spec and look for this...anyways, feel free to ignore my comments as I'm not on the phone.
<jjc> If an information resource IR is represented by a conforming RDF/XML document[RDFX], then the RDF graph represented by that document is a GRDDL result of IR.
<john-l> What about what about application/rdf+xml?
<DanC_lap> DanC nominates jjc to review this sq1 test
<DanC_lap> JJC: sq1 is not problematic; it bears the rdf:RDF root element
<DanC_lap> ... or... hmm...
<DanC_lap> (the TAG concurred with the idea that the root element namespace URI works as an alternative to a MIME type decl)
<HarryH> +` root element namespace URI working as an alternatie to MIME type.
<HarryH> +1
<DanC_lap> ACTION: JohnL [recorded in]
<DanC_lap> DanC collects advice on the xml pi appendix
<DanC_lap> ADJOURN
This is scribe.perl Revision: 1.128 of Date: 2007/02/23 21:38:13 Check for newer version at Guessing input format: RRSAgent_Text_Format (score 1.00) No ScribeNick specified. Guessing ScribeNick: chimezie Found Scribe: Chime Default Present: john-l, HarryH, Chimezie_Ogbuji, FabienG, +0127368aaaa, jjc, briansuda, rreck, DanC Present: john-l HarryH Chimezie_Ogbuji FabienG +0127368aaaa jjc briansuda rreck DanC Regrets: IanD WARNING: No meeting title found! You should specify the meeting title like this: <dbooth> Meeting: Weekly Baking Club Meeting Got date from IRC log name: 11 Apr 2007 Guessing minutes URL: People with action items: chime harryh is jjc john-l johnl WARNING: Input appears to use implicit continuation lines. You may need the "-implicitContinuations" option.[End of scribe.perl diagnostic output] | http://www.w3.org/2007/04/11-grddl-wg-minutes.html | crawl-002 | refinedweb | 1,666 | 60.65 |
This is the mail archive of the gcc-prs@gcc.gnu.org mailing list for the GCC project.
The following reply was made to PR preprocessor/9650; it has been noted by GNATS. From: Neil Booth <neil@daikokuya.co.uk> To: frey waid <waid@cisco.com> Cc: neil@gcc.gnu.org, gcc-bugs@gcc.gnu.org, gcc-prs@gcc.gnu.org, nobody@gcc.gnu.org, gcc-gnats@gcc.gnu.org Subject: Re: preprocessor/9650: string literal contactenation doesn't work with #include Date: Mon, 10 Feb 2003 23:09:48 +0000 frey waid wrote:- > i tried that but it doesn't work consistently with the newer prescan semantics. > for example, if i did this: Prescan semantics haven't changed. Apart from removal of the odd segfault ;-) > #include COMP_INC(me, mips/hello.h) > > you'd think it'd expand with the below method: > > #include "me/include/mips/hello.h" > > unfortunately, mips is a predefined macro. so it expands to "1". is there a > work around for this without having to undefine it? No, that's the way C works, because mips is lexed as a token in its own right. You need to use a different path, or #undef mips. Or, latest versions of GCC won't invade your namespace like this with -ansi. Prior versions of GCC were somewhat unpredictable. Neil. | https://gcc.gnu.org/legacy-ml/gcc-prs/2003-02/msg00472.html | CC-MAIN-2022-21 | refinedweb | 221 | 60.92 |
Archives
Migrating to the GridView and ObjectDataSource
I "adopted" a small app recently written in .NET 1.1, which I migrated to .NET 2.0 painlessly. It's only about 16 pages and user controls, so I wasn't expecting too many problems with the actual migration into VS 2005, and had none..
Convert.ChangeType doesn't handle nullables
I had an assembly, originally written against .NET 1.1 and now running on .NET 2.0, that tried to convert a boxed DateTime object to a Nullable<DateTime> (DateTime?) object, using the Convert.ChangeType method. When this code runs, I get this exception:
[InvalidCastException: Invalid cast from 'System.DateTime' to ' System.Nullable`1[[System.DateTime, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]'.]
System.Convert.DefaultToType(IConvertible value, Type targetType, IFormatProvider provider) +864
System.DateTime.System.IConvertible.ToType(Type type, IFormatProvider provider) +36
System.Convert.ChangeType(Object value, Type conversionType, IFormatProvider provider) +433
System.Convert.ChangeType(Object value, Type conversionType) +38
Since a DateTime can be assigned to a nullable DateTime, it didn't make sense to me why it couldn't be converted to one, by calling Convert.ChangeType(Object, Type) with a Nullable as the second parameter. A Google search showed that Paul Wilson, Cameron Beccario, and others ran into this too during the beta timeframe.
The CLR team at Microsoft confirmed that this is a known problem:
Yes, Convert is not very extensible and was designed around a fixed set of types to address a specific functionality requirement for VB. System.ComponentModel has a more comprehensive data type conversion model, and I believe does deal with nullable.
The docs showed a lot of System.ComponentModel classes for conversion, e.g. DecimalConverter, but unfortunately I couldn't use those in this particular case, since it doesn't support the late-bound casting that code was doing. It was disappointing that this particular case wasn't handled, but it's probably a rare case, and it's understandable given some of the changes to nullables that came so late in the game.
My workaround in the short term was to not use the Nullable type for that particular method, until I could dig into System.ComponentModel more to find an alternative, or a patch is released for Convert.ChangeType to handle nullables.
Edit: I've now implemented a wrapper that handles nullables correctly.
Web projects and code-behind in Visual Studio 2005
Some of my coworkers and I balked at what giving up web project files in VS 2005 also meant we'd give up--default namespaces, ease of referencing classes in the web site (not just App_Code stuff but code-behind files as well), and so on.
Have no fear--they're coming back.
On another note, what also came back between the beta and release is the old code-behind model. Now your code-behind (.aspx.cs) and your web form (.aspx) are no longer compiled together as partial classes--your web form inherits from the code-behind as it did in VS.NET 2003.
HttpRuntime.Cache vs. HttpContext.Current.Cache
Here's a development tip I came across on one of the ASP.NET discussion lists I'm on, at AspAdvice.com.
Original question:
Is there a difference in accessing the Cache of an application when calling HttpRuntime.Cache vs. HttpContext.Current.Cache? I "think" I remember reading about a difference in the two a few years ago, but I don't remember the specifics. This assumes that I am within a web application.
Answer from Rob Howard:
HttpRuntime.Cache is the recommended technique.
Calling the HttpContext does some additional look-ups as it has to resolve the current context relative to the running thread.
I use HttpContext.Current in a lot of the code I write too; but touching it as little as possible. Rather than calling HttpContext.Current repeatedly it's best to hang onto a reference and pass it around (when possible).
If you're in a component HttpRuntime.Cache is still the recommendation.
That said... the differences in performance are not going to be noticeable in 99% of the applications many of us write. The cases where it is going to matter is the 1% (or less) where you're trying to squeeze every last drop of performance out of you system. But this is a *minor* performance tweak, e.g. eliminating a database call, web service call or other out-of-process call in the application is definitely a better place to spend optimizing code.
For example, if you have 5 database calls in a particular code path reducing (or even optimizing) the queries is a much better use of time.
So yes, HttpRuntime.Cache is recommended but likely won't make a difference in most applications.
Another reply from James Shaw at CoverYourASP.NET:
I discovered another *great* reason to use HttpRuntime too, when writing my unit tests - HttpRuntime.Cache is always available, even in console apps like nunit!
I never use HttpContext anymore, even in class libraries. | http://weblogs.asp.net/pjohnson/archive/2006/02 | CC-MAIN-2014-52 | refinedweb | 840 | 58.38 |
NOTE:-
- In this tutorial we create a simple WCF service which is used to retrieve and save data from Pubs Database (Microsoft sample database).
- The service also demos on how to use EF 4.0 and LINQ against database coding, with no requirement of writing SQL queries.
- The continuation of this tutorial shows on how to create a client (say a WebForm in a website) to utilize this service.
- Open VS 2010
- File -> New -> Project
- Select Visual C# -> WCF (also select .net framework 4.0) -> select WCF Service Application Template.
- Give Name -> samplePubsService (also give the preferred location to save the solution).
- Click OK.
Initial Preparation of the Project in the solution:-
- Delete IService1.cs and Service1.svc, which we get by default at the time of project creation.
- Download Microsoft Sample Database – PUBS from HERE, else we can create our own database for operation.
- Extract the Database, Open the SQL file (.sql) of Pubs database -> instpubs.sql in the VS 2010, once opened -> Right click anywhere on the text zone and select -> Execute SQL (this creates our sample database).
- Now in Server Explorer (view –> server explorer) of VS 2010, Right Click -> Data Connections, Select -> Add Connection.
- In the open Dialog, Select –> ServerName (typically SQLEXPRESS), and also Select -> Database Name from the DropDownList (pubs).
- CLick OK. With this, the database part of the project is ready.
Adding a Service:-
- Right Click the project folder in Solution Explorer of VS 2010, select -> Add new Item, select -> Web, select -> WCF Service Template.
- Name it -> PubsService.svc
Adding a DataContract:-
- Right Click the project, select -> Add new Item, select -> web, select -> Class Template.
- Name it -> Author.cs
Place the below code in it:-
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Runtime.Serialization; namespace samplePubsService { [DataContract] public class Author { [DataMember] public string authorId { get; set; } [DataMember] public string authorLName { get; set; } [DataMember] public string authorFName { get; set; } [DataMember] public string authorCity { get; set; } } }
Similarly add one more DataContract, with name bookByAuthor.cs and place the following code in it.
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Runtime.Serialization; namespace samplePubsService { [DataContract] public class bookByAuthor { [DataMember] public string titleId { get; set; } [DataMember] public string title { get; set; } [DataMember] public string type { get; set; } [DataMember] public DateTime pubdate { get; set; } } }
Adding a ServiceContract:-
Open IPubsService.cs, and place the following code:-
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.ServiceModel; using System.Text; namespace samplePubsService { [ServiceContract] public interface IPubsService { [OperationContract] Author GetAuthorById(string authorId); [OperationContract] List<bookByAuthor> GetBookOfAuthor(Author authorDetails); [OperationContract] void SaveBookDetails(List<bookByAuthor> booksDetails); [OperationContract] List<Author> GetAllAuthors(); } }
Implement the IPubsService interface in the PubsService.svc.cs:-
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.ServiceModel; using System.Text; namespace samplePubsService { public class PubsService : IPubsService { public Author GetAuthorById(string authorId) { return null; } public List<bookByAuthor> GetBookOfAuthor(Author authorDetails) { return null; } public void SaveBookDetails(List<bookByAuthor> booksDetails) { } public List<Author> GetAllAuthors() { return null; } } }
To Simplify DataBase coding, we Use Entity Framework ORM module, the step by step process is described below –
- Right Click Project folder in Solution Explorer, Select -> Add new Item, Select -> Data, Select -> ADO.Net Entity Data Model, Name it -> PubsEntityModel.edmx
- Select -> Generate from Database, Select -> pubs.dbo in the DropDownList, also Check the checkbox to save entity ConnectionString to the Web.Config file.
- Check all tables; also check the two checkboxes at the bottom. (Checking the checkboxes of views and Stored Procedures is optional).
- Give name to the namespace -> pubsModel, Click Finish.
The complete model would be (Sorry!! for not getting the image quite clearly) –
But we are interested in only in the below entities (only for the sake of this tutorial) –
This completes Entity Framework Part.
Now let’s code against pubsEntities i.e., the class generated from the Entity Framework (you can find it by double clicking the PubsEntityModel.Designer.cs). So let’s go back to PubsSevice.svc.cs:-
Import the name space System.Data.Entity to use the Entity models.
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.ServiceModel; using System.Text; using System.Data.Entity; namespace samplePubsService { public class PubsService : IPubsService { public Author GetAuthorById(string authorId) { using (pubsEntities pubs = new pubsEntities()) { Author a = new Author(); var author = (from p in pubs.authors where p.au_id == authorId select p).First(); a.authorCity = author.city; a.authorFName = author.au_fname; a.authorId = author.au_id; a.authorLName = author.au_lname; return a; } } public List<bookByAuthor> GetBookOfAuthor(Author authorDetails) { List<bookByAuthor> books = new List<bookByAuthor>(); using (pubsEntities pubs = new pubsEntities()) { var titleIds = (from p in pubs.titleauthors where p.au_id == authorDetails.authorId select p); foreach(titleauthor titleId in titleIds) { bookByAuthor book = new bookByAuthor(); var bookTitle = (from p in pubs.titles where p.title_id == titleId.title_id select p).First(); book.title = bookTitle.titleOfBook; book.type = bookTitle.type; book.titleId = bookTitle.title_id; book.pubdate = bookTitle.pubdate; books.Add(book); } } return books; } public void SaveBookDetails(List<bookByAuthor> booksDetails) { using (pubsEntities pubs = new pubsEntities()) { foreach (var detail in booksDetails) { var book = (from p in pubs.titles where p.title_id == detail.titleId select p).First(); book.type = detail.type; book.titleOfBook = detail.title; book.pubdate = detail.pubdate; pubs.SaveChanges(); } } } public List<Author> GetAllAuthors() { List<Author> lstAuthors = new List<Author>(); using (pubsEntities pubs = new pubsEntities()) { var authors = from p in pubs.authors select p; foreach (author singleAuthor in authors) { Author a = new Author(); a.authorCity = singleAuthor.city; a.authorFName = singleAuthor.au_fname; a.authorLName = singleAuthor.au_lname; a.authorId = singleAuthor.au_id; lstAuthors.Add(a); } } return lstAuthors; } } }
The folder Structure:-
To Test the PubsService.svc:-
Its Simple -> Press Ctrl + F5
A WCF Test client will open, now double click on any of the method on the left pane, and enter the input manually as shown below and then press Invoke. Results should be displayed in the Bottom Pane.
This Completes the coding part of the Service.
To Follow up with the Client construction, which utilizes this Service. Please Click the below Link – PART II.
Create a Simple WCF Service Client against Pubs Database using EF, LINQ – Part II
Disclaimer:.
examples r good but lengthy, examples must be in simple
@chakravarthy
Thanks for giving me nice comments. Yes, indeed examples are lengthy, but my main motive is to give freshers a detailed explanation about introductory concepts.
Hi – Lets say this sample application is hosted and only available to those who log in to a site and gain access.
If 100 people are logged in at once and are querying and updating the database, would we use the multiple concurrency to allow a new thread be created for each user?
Wow!! Wonderful!! Its a crystal clear for novice and for all users also.
Thank you so much
Excellent, there are a lot of tutorials out there but I find that you give just enough detail. This is a simple and complete example. Thank you.
Cntl + F5 to start the WCF Test Client gives me an error says:
Failed to add a service. Service metadata may not be accessible. Make sure your service is running and exposing metadata.
Is there some special code needed in the webconfig?
Please respond.
@William – IF you follow the exact same process as I have MEntioned in the the tutorial, there should not be any problem. What I was thinking is that your web.config is not exposing MEX endpoint which is MetaData endpoint. Please check that.
Can you display what your web.config has please.
This is what I have.
It was a namespace issue. I have it working now.
Thanks.
Excellent, Great Place where i finally found what i need.
Love to see more articles from you, in this crystal clear manner
Thank You
Sudheer Rishi
+91 8801640530
+91 9246655446
Excellent! The best, straight forward, WCF EF example if seen. Thanks a lot.
Thank you! I am one week studying WCF (theoretical part) and practice this part explained to me many things, thanks again for sharing that knowledge with us!
Please keep writing great tutorials like this!
Is it necessary to always create a POCO to expose an Entity (an entity framework entity)?
Excellent, Great Place where i finally found what i need.
Kindly, Is it possible to have source code for above example
Bravo, thanks for the great article, I learn from much it about EF and WCF Data Service, straight to the point, very good.
@Jairo – not exactly always.
Hi Ravi
I need a code for a WCF service which can give me generic insert and select facility on single tables. The service shoud expose a method which accepts the tablename(string), and an array or hashtable which holds the values to be inserted in it. And, another method which accepts a tablename and a where condition based on what the select will be done. Is it possible to do it using generics+linq ? If yes please give me some lead on it.
Regards
Manoj
I was unable to get part two to work but that’s not how I want to communicate with the WCF Service anyway so I didn’t bother trying to fix it.
I have to say this was the best tutorial on the subject I could find on the NET and I had been looking for a while. The screen shots and code are exactly the way all tutorials should be laid out. Pat on the back and please continue to make great tutorials you make people happy!
Cheers
Mike.
Can you show example of crud?
This was great! Can you add crud to your example?
Can you add crud to your example?
Hi,
Nice article. I am getting the same error below
Cntl + F5 to start the WCF Test Client gives me an error says:
Failed to add a service. Service metadata may not be accessible. Make sure your service is running and exposing metadata.
Please how did William Beaty solve this problem?
Great example ……….. thats cool
Amazing, way cool, and awesome job dude! I was scouring the web looking for a comprehensive example when I stumbled on this article. I followed steps outlined by Rami, my service compiled and worked just like the example showed. Rami; you did a great job – you deserve a medal or award for your article. Thanks
Excellent, I searched for a long time before I found this. | http://www.intstrings.com/ramivemula/articles/create-a-simple-wcf-service-against-pubs-database-using-ef-linq-part-i/ | CC-MAIN-2014-10 | refinedweb | 1,729 | 51.24 |
Machine Learning in Plain English: Building a Decision Tree Model to Classify Names by Gender: Part One
Hello Friend,
Machine learning is a booming field in computer science. Its focus is to train algorithms to make predictions and decisions from datasets. These datasets can either be curated or generated in real time.
In this tutorial, I'll talk about the classification problems in machine learning. By the end of it, you’ll have built a machine learning model to classify names as either male or female. Sounds like fun, right?
Okay, let’s kick things off by first asking what I mean by a “classification problem.” Basically, classification problems sort things into one of a predefined set of categories:
Fraud detection:
- Fraud or Not fraud
Gender detection:
- Female or Male
Quant trading:
- Rise or Fall
Weather forecast:
- Sunny or Cloudy or Rainy
The typical structure of a classification problem is that you start with what you want to classify — the problem instance — and apply labels to it, with each label being a value within the predefined set of categories.
We’re going to pick the gender detection problem from the list above for our example. So, from the earlier sentence, we know that we need to have a problem instance and two labels:
Problem instance = Name
labels = (Male, Female)
In a nutshell, the flow to building this model can be visualized as:
A name => Classifier => Male/Female
Our second objective is to find rules that can classify female and male names visually (these rules don’t necessarily have to be correct).
Taking a look at the table, we can see some patterns. We can see that more female than male names end with vowels. We can also see that a male name ending with a vowel begins with a consonant, and a female name ending with a consonant begins with a vowel.
However, these constraints are not a hundred percent accurate. Rather, they’re just assumptions. We will add more constraints as we go on, but now it’s time to get into the nitty-gritty of the code.
What you'll need:
- pandas
- python 3.6.x
- sklearn
- An integrated development environment (IDE)
Or you can just download Anaconda, a Python data science platform, shipped with lots of data science tools you don't have to bother to install. If you have Anaconda installed, fire it up and launch Jupyter notebook, an open-source web application that allows you to create and share documents that contain live code, equations, visualizations, and explanatory text.
from pandas import pandas as pd from sklearn.model_selection import train_test_split from sklearn.tree import DecisionTreeClassifier from sklearn.metrics import accuracy_score
The first lines are just a bunch of imports. Pandas is a data analysis tool that allows you to tabulate data in structures that have rows and columns.
Then, from the
sklearn module, which contains a bunch of machine learning algorithms and data mining tools, we import
train_test_split. What this basically does, or what we'll need it to do, is to split our single dataset into two — one for training the model and another for testing it. I'll explain the need for splitting the dataset in a bit.
We then go on to import
DecisionTreeClassifier. This is the classification algorithm we’ll use to build our decision tree.
Finally, we import
accuracy_score. This is going to be used to check the accuracy of our model.
df = pd.read_csv('./dataset/NationalNames.csv') df = df.drop_duplicates(subset="Name") df.head()
Here we import our dataset, NationalNames.csv, using the pandas
read_csv method, which allows us to read a csv file into a pandas data frame.
This dataset contains naming trends for babies born in the United States and is sanitized, but we do have to perform one more cleaning operation, which is what you see on the second line.
There, we check for and remove duplicate names from the dataset using pandas data frame
drop_duplicates method, and pass in the column we want to check.
The last line displays the first five rows of the pandas data frame.
Next, we'll select the information that we think is most relevant for our classification. What we want is to pick a column that best represents whether a name is male or female.
Unfortunately, with the existing dataset, there’s no definite way to determine whether a name is male or female, so we should go ahead and create a new column to better classify gender.
The first column we’re going to add will check if the name ends in a vowel. At first glance, we see that female names tend to end in vowels more often than consonants. This is not a definite classification rule, and in fact may not be a rule at all. But let’s try it and see.
First, we create a function that checks if the last letter of a name is a vowel.
# Check if the name ends in vowel def checkVowelEnd(name): if name[-1] in "aeiou": return "Vowel End" return "Consonant End"
If the last letter is a vowel, we return 0 (for female), otherwise we return 1 (for male). We need this value in numeric form so it can be passed into our classifier.
df["Vowel/Consonant End"] = df["Name"].apply(checkVowelEnd) df.head()
Here, we’re creating a column Vowel/Consonant End, and we’re passing the values obtained from the vowel-ending checking function into it.
Pandas data frames have an
apply method that lets us pass in a function as an argument, and that function will be called on each row of a specified data frame column. In our program, we’re applying the
checkVowelEnd function to each name in the Name column.
We should see something like this:
Next, we check to see if this is truly a good indicator of whether a name is male or female. To pursue this, we first have to convert the Gender column by assigning numerical codes to its values. As before, we'll use 0 for female and 1 for male.
def checkGender(gender): if gender == "F": return 0 return 1 df["Gender Value"] = df["Gender"].apply(checkGender) df.head()
Again, we create a new column, Gender Value, which will contain the numerical equivalent of the genders. After this action, we should have something like this:
We’ll now create a function to compare the custom column’s value with the value of the actual gender column, Gender Value.
def compare(group): return df.groupby([group])["Gender Value"].sum()*100/df.groupby([group])["Gender Value"].count()
Breaking down this function, we have:
df.groupby(["Vowel/Consonant End"])["Gender Value"].sum()
This will return the sum of all female names that end in vowels and the sum of all female names that, in fact, end in consonants. We should get this result:
From this output, we can see that
42,424 female names actually end in vowels and that
17,506 female names also end in consonants. To validate this result, we'll need to look at the sum of all female names in our dataset, i.e. how many female names we actually have in the dataset. We'll see this after we explain what the
count method does.
df.groupby(["Vowel/Consonant End"])['Gender Value'].count()
Using the
count method again gives us the sum of all names ending in consonants and the sum of all names ending in vowels. We should see the following:
From our result, we can see that, of all the female names in the dataset,
50,254 end in vowels and
43,635 end in consonants. To validate this, we'll need to look at the sum of our entire dataset — i.e. how many names we actually have in total.
print (len(df)) # > 93889 = 43635 + 50254
We can see that the length of our dataset is the sum of
50,254 (names that end with vowels) and
43635 (names that ends in consonants).
Now, to validate that we did get the correct totals, we'll take the list of initial names that are female, and summarize the numbers ending in vowels and consonants. Hopefully, our answer will equal the actual count of female names in our dataset.
female_names = sum(df.groupby(["Vowel/Consonant End"])["Gender Value"].sum()) all_names = df.groupby(["Gender"])["Gender Value"].count() print (all_names) print ("\nBoth are equal? %s" % str(female_names == all_names["F"]))
Awesome! The values are equal, so we can continue. We typically want to get the rates at which female names end in vowels and consonants, as opposed to the absolute numbers.
print(df.groupby(["Vowel/Consonant End"])["Gender Value"].sum()*100/df.groupby([group])["Gender Value"].count())
We’re just converting our values to percentages here. We multiply the sum by
100 and we divide by the total count.
Using the
compare function we created, we can do the following:
print(compare("Vowel/Consonant End"))
Now, that’s more like it! We’re able to see that roughly 40% of names ending with consonants, and 84% of names ending with vowels, are female. This is a somewhat good classifier, so we'll keep the column.
However, if we want to get more accurate results, this column is not enough to build a decision tree. So, let’s add another. We can check whether female names frequently start with either vowels or consonants.
def vowelConsonantStart(name): if name[0] in "aeiou": return "Vowel Start" return "Consonant Start" df["Vowel/Consonant Start"] = df["Name"].apply(vowelConsonantStart) print("\n Comparison => %s", compare("Vowel/Consonant Start")) df.head()
If we look at the two rates above, we see that there’s not much difference, meaning this isn’t a very strong classification factor.
Next, let’s try using the length of names as a classifier.
def shortLongName(name): if len(name) < 7: return "Short" return "Long" df["Short/Long Name"] = df["Name"].apply(shortLongName) print(compare("Short/Long Name", df)) df.head()
I think the result we get from this comparison is quite reasonable, so we'll move on to training and testing our model.
training_data = df[["Gender Value", "Vowel/Consonant End", "Short/Long Vowel/Consonant End", "Vowel/Consonant Start"]] training_data.head()
We create a new data frame with training data and give it only the columns from the original data frame that we actually need.
From the looks of it, our columns mainly contain categorical variables, i.e. variables or attributes that can only take one of a specific set of values. Whenever we have such categorical variables, we need to convert them to numerical representations before we can feed the data into any machine learning algorithm.
So, we'll mark these columns to indicate that whenever we see particular values, they should be replaced by their numerical equivalents — usually 1 or 0.
Pandas comes through for us, as usual, and has a way to handle this.
def reprCategory(column): column = column.astype("category") return column.cat.codes training_data[["Vowel/Consonant End", "Short/Long Name", "Vowel/Consonant Start"]] = training_data[["Vowel/Consonant End", "Short/Long Name", "Vowel/Consonant Start"]].apply(reprCategory) training_data.head()
In the first line of the function
reprCategory, we convert the column into the type
category so that pandas knows that this is a categorical variable. The last line will return a column where every value has been converted to a corresponding numeric value (usually integers).
After creating the function, we use it to replace Vowel/Consonant End, Short/Long Name, Vowel/Consonant Start with columns containing the appropriate numerical codes generated by applying the function
reprCategory on the original columns.
When we print out the first few rows of
training_data, we will see that the columns have been converted.
train, test = train_test_split(training_data, test_size = 0.20)
Before continuing, it is useful to split our dataset in two — one that we can use to train our machine learning algorithm and the other to test the accuracy of our model.
The
sklearn package has a module,
model_selection, that can ease this process. As we did in the beginning, from the module, we import
train_test_split, which is the function we will use to split our dataset. It takes in two arguments — our original data and the percentage of the original data we want to convert to test data. In this case, we’re using 20% (0.20) of our original data.
clf = DecisionTreeClassifier()
Again, the
sklearn package has a module called
tree that contains tree-based models, from which we imported the
DecisionTreeClassifier above. Here, we set up an instance of it.
clf = clf.fit(train[["Vowel/Consonant End", "Short/Long Name", "Vowel/Consonant Start"]], train["Gender Value"])
DecisionTreeClassifier has a
fit method that will take in the
training_data with features and labels, apply a machine learning algorithm to it and return another
DecisionTreeClassifier object. This object will have the decision tree that has been built embedded within it.
The
fit method will take in two data frames as arguments, the first containing all the features we think are important for our classification, and the second, the corresponding labels.
clf
By printing out the classifier object, we can see a bunch of its properties. I will explain what each property does and how they can be used to increase the accuracy of our model in the next part.
clf.feature_importances_
The
feature_importances_ attribute gives us a list of scores between 0 and 1 for each of our features, with the most important feature scoring the highest. We can see that the Vowel/Consonant End feature is ranked here as being the most important.
predictions = clf.predict(test[["Vowel/Consonant End", "Short/Long Name", "Vowel/Consonant Start"]]) accuracy_score(test["Gender Value"], predictions)
Next, we attempt to gauge the accuracy of our model. We first try to use our model to predict the gender of a name using the test data. The
predict module lets us pass in our data frame, and it tries to make predictions based on the data we fed into our machine learning algorithm.
Next, using the
accuracy_score function, we pass in two parameters — the first is the list of actual values for each row in our test data, and the second is the list of values that our model has predicted. After matching each original value to the predicted value,
accuracy_score returns either 1.0 or 0.0.
Since we pass in a list of data, it matches each row's value to its corresponding prediction, aggregates it, and returns a value between 0.0 and 1.0. If
accuracy_score returns a value of exactly 0.0 or 1.0 for a list of data, then something is seriously wrong with our model. Here, we can see that my model has an accuracy score of roughly 73%. Yours may vary, but only slightly.
with open("decidenames.dot", "w") as dot_file: dot_file = export_graphviz(clf, feature_names=["Vowel/Consonant End", "Short/Long Name", "Vowel/Consonant Start"], out_file=dot_file)
It’s now time to visualize our decision tree. We open the
decidenames.dot file for writing, and we write our decision tree to it using the
export_graphviz function we imported at the start.
This takes in our classifier as the first parameter,
feature_names (a list of all our featured names) as the second, and finally,
out_file — the file we want to write to. After this, we should see the
decidenames.dot file in our filesystem. It should look like the image above.
From the graphic, we can see that it’s actually not a very complex decision tree. This is because we don’t have many features of similar importance.
What is basically going on here is that Vowel/Consonant End has been placed at the top, as the root node — the most important classification feature. If a name ends in a consonant, then it moves on to the next most important feature or attribute, which, as we can see, is the length of the name.
The same goes for vowels, but it’s important to note that in some situations, the next node or feature on a specific branch may not be the same as on another. For instance, it could be that, for a name ending in a vowel, the next most important factor is whether it starts with a vowel or consonant.
The image below labels each branches in the decision tree.
In the next part, we'll look into what each of our classifier properties does, and how they can be used to improve the accuracy of our models. We'll look into what we call “ensemble learning,” how it helps us solve a problem known as “overfitting,” and how we can use it to improve the accuracy of our model. | https://www.codementor.io/ashamao/machine-learning-in-plain-english-building-a-decision-tree-model-to-classify-names-by-gender-part-one-b47dggc7x | CC-MAIN-2017-47 | refinedweb | 2,788 | 54.52 |
I need a Programmer
Budget $10-30 USD
Your task is to develop a C program, called ascii2bin, that
reads a string of 1's and 0's as ASCII digits, and
outputs the equivalent decimal number
Your program must
exercises the read() system call to read a single byte, at a time, from stdin
validate that the read byte is appropriate for conversion, e.g., it must be either an ASCII '0' or '1'
converts each byte into an integer value via a mathematical expression
uses the resulting integer as part of the calcuation to determine the final number
identifies the end of a input string by either end of file or by a new line
End of file is detected when read() returns the value '0'
A new line is identified in the ASCII table as either: newline, nl, LF, or \n'
prints this final number on stdout
returns a value of 0 upon success and 1 otherwise
The Algorithm
offset = ?;
number = 0;
retval = read(0, &ascii_value, 1);
while (retval == 1)
digit = ascii_value - offset;
number = number << 1 + digit;
retval = read(0, &ascii_value, 1);
printf("%d\n", number);
return 0;
Validation Checks:
You should add additional validation checks to your code to catch potential errors. At a minimum, validate the following:
that each ASCII input character is one of the following characters: '0', '1', or '\n'
that the calculated number does not exceed 2^32
I am having trouble with this program I have most of the code but my output does not match the Professors completely:
#include <stdio.h>
#include <unistd.h>
int main()
{
int offset = 48; // ascii value of '0'
int number = 0;
char ascii_value;
int retval = read(0, &ascii_value, 1);
while ((retval == 1) && (ascii_value != '\n')) {
int digit = ascii_value - offset;
if ((digit == 1) || (digit == 0))
number = (number << 1) + digit;
retval = read(0, &ascii_value, 1);
}
printf("%u\n", number);
return 0;
}
These are his test file information:
$ script [login to view URL]
$ ascii2bin
0101
^d
5
$ cat [login to view URL] | ./ascii2bin ; echo $?
54356
0
$ cat [login to view URL] | ./ascii2bin ; echo $?
138
0
$ cat [login to view URL] | ./ascii2bin ; echo $?
2863311530
0
$ cat [login to view URL] | ./ascii2bin ; echo $?
4294967295
0
$ cat [login to view URL] | ./ascii2bin ; echo $?
1
Décerné à:
10 freelances font une offre moyenne de 23 $ pour ce travail
HI..i am proficient in C/C++ programming with data structures, algorithms and can help you write the console program for reading strings of 0's and 1's and convert it to decimal.
Hi; i can help you Now (immediately) send me a message so that we can discuss more. Thanks and regards.
Hi I'm a senior software engineer with 3 years experience. I think I can help you with debugging your code. Please share the test case that is failing Regards | https://www.fr.freelancer.com/projects/c-programming/need-programmer-29458100/?ngsw-bypass=&w=f | CC-MAIN-2021-17 | refinedweb | 469 | 54.66 |
In this article, we will learn to connect our Flask Application with PostgreSQL Database systems using an ORM – Object Relational Mapper, called Flask SQLAlchemy.
What is PostgreSQL?
Similar to the MySQL Database management system, PostgreSQL is another type of RDBMS used for accessing, storing, and handling the data in the form of database tables.
PostgreSQL also uses SQL- Structured Query Language to access and handle databases and also perform various Tasks in PostgreSQL
The Basic Structure of PostgreSQL
Data is stored inside Postgres DB in the form of Table. A typical Postgres Table looks like this:
The rows are called records and the columns are called fields. Therefore, in the above table we have 6 records and 4 fields.
Difference between MySQL and PostgreSQL
Though both MySQL and PostgreSQL belong to RDBMS, there are some key differences between both.
- One of the basic differences between MySQL and PostgreSQL is that PostgreSQL is an ORDBMS (Object Relational Database Management System) while MySQL is a community-driven RDBMS.
- Another advantage of PostgreSQL over MySQL is that it can support modern applications feature like JSON, XML, etc. while MySQL can only support JSON.
Why SQLAlchemy to Connect PostgreSQL to a Flask Application?
SQLAlchemy is an ORM-Objects Relational Mapper written in Python. It gives away around to interact with the Databases without using SQL statements.
It provides an extra layer on top of SQL which allows us to use Databases and Tables just like Python Class Objects. We just have to create a Class Object and SQLAlchemy will take care of the rest!
In Flask, unlike Django, which comes with a pre-built ORM in the form of Django Models, it does not have a pre-built ORM.
Hence we need to install the Flask-SQLAlchemy ORM library to use models in this web framework
Setting-up PostgreSQL in your system
In this section, we will download and set-up all the necessary packages for our Flask- SQLAlchemy-Postgres project.
1. Installing PostgreSQL shell
To install PostgreSQL, visit the link here. Once PostgreSQL is installed, open the SQL shell and set up your DB connection Username and password.
Run the below command to open shell in Terminal:
sudo su postgres pqsl
In case of Windows, directly search for SQL shell in the search menu.
I have kept my Connection details default (shown in bracket).
- Server: localhost
- Database: postgres
- Port: 5433
- Username: postgres
After you enter the password, you will be prompted into the PostgreSQL DB by default.
Now let’s create a new DB with the name Flask to store our data.
CREATE DATABASE <db_name>;
Here we are using SQL syntax only. Do check out our SQL tutorial on the JournalDev website to gain more knowledge about the query language.
To change the current Db to Flask DB use the command:
\c <db_name>;
That’s it now you are in the new Flask DB.
2. Installing psycopg2 adapter tool
We also need pyscopg2, which is the PostgreSQL database adapter for Python. Let’s run the pip command:
pip install psycopg2-binary
3. Installing ORM packages for Flask
First we need to install Flask-SQLAlchemy ORM.
To install the package, simply run the code:
pip install flask-sqlalchemy
Also we need to install Flask-Migrate.
Flask-Migrate, uses Alembic which is a light Database migration tool. It helps us to Create/Update Databases and Tables. It also allows us to update an existing Table incase you delete or create new Table Fields.
To install Flask-Migrate, run:
pip install Flask-Migrate
That is we need !! Now let’s get our hands dirty !!
Implementing a PostgreSQL database connection in Flask with SQLAlchemy
In this section, we will create a simple Flask application that stores user information in the Database.
1. Creating a Flask Model
A Model is a Python Class that represents a table in the Database. It contains information regarding the Table structure.
In Flask, it is more systematic to save all the DB information and the models in a separate file called – models.py situated right beside our main application file.
A typical models.py file looks like:
from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy() class Model_name(db.Model): __tablename__ = 'table_name' field1_name = db.Column(db.Field1Type, primary_key...) field2_name = db.Column(db.Field2Type) field3_name = db.Column(db.Field3Type) def __init__(self, Field1_name,Field1_name,Field1_name): self.field1_name = field1_name self.field2_name = field2_name self.field3_name = field3_name def __repr__(self): return f"<statement>"
This is similar to a classic Python Class. These indicate the Fields of the Table and their representation.
Therefore, let us build a small InfoModel Table to store user information:
models.py:
from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy() class InfoModel(db.Model): __tablename__ = 'info_table' id = db.Column(db.Integer, primary_key = True) name = db.Column(db.String()) age = db.Column(db.Integer()) def __init__(self, name,age): self.name = name self.age = age def __repr__(self): return f"{self.name}:{self.age}"
2. Coding our Main Flask Application
Now we will connect Postgres with our Flask Application. The syntax is :
from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate from models import db, InfoModel app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = "postgresql://<username>:<password>@<server>:5432/<db_name>" app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False db.init_app(app) migrate = Migrate(app, db) #general Flask Code @app.route('') # Your code if __name__ == '__main__': app.run(debug=True)
Here,
- We create a Flask object – app
- Then configure the PostgreSQL Connection
- I have kept SQL_TRACK_MODIFICATIONS to False just for simplicity.
- Then pass on app object to the SQLAlchemy object db
- Create a Migrate Object for migrations.
That’s it!
Also add the below Views in the app.py file.
apps.py:
from flask import Flask,render_template,request from flask_migrate import Migrate from models import db, InfoModel app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = "postgresql://postgres:[email protected]:5432/flask" app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False db.init_app(app) migrate = Migrate(app, db) @app.route('/form') def form(): return render_template('form.html') @app.route('/login', methods = ['POST', 'GET']) def login(): if request.method == 'GET': return "Login via the login Form" if request.method == 'POST': name = request.form['name'] age = request.form['age'] new_user = InfoModel(name=name, age=age) db.session.add(new_user) db.session.commit() return f"Done!!" if __name__ == '__main__': app.run(debug=True)
We can interact with the Table just like a Class Object. We use:
- db.session.add() to add new data
- db.session.comit() to save the changes
3. Implementing the Flask Code
The last thing left is to run the migrations. Hence run the commands:
python db init python db migrate python db upgrade
That’s it,
Now run the server
python app.py
And lets check the Browser. Go to “/form“
Hit Submit
That’s it now in our PostgreSQL shell, Type:
SELECT * FROM info_table
And the data will be right there!!
Perfect!
Conclusion
That’s it, guys!! This was all about setting up Flask PostgreSQL and SQLAlchemy connections. See you the next time !! Till then, Happy Coding!! | https://www.askpython.com/python-modules/flask/flask-postgresql | CC-MAIN-2021-31 | refinedweb | 1,154 | 59.9 |
Ratings skills etc on the skill page for each skill, and this will also enable users to get top rated skills and thus users can get to use the best skills rated by the community. So we implemented a rating section to SUSI SKILL CMS
Implementation
Server –
- Two APIs were implemented by the analytics team on the server which allows the user to rate skill and fetch rating for each skill.
- To rate the skill (Sample)
/cms/getSkillRating.json?model=general&group=Knowledge&language=en&skill=aboutsusi&callback=pc&_=1525446551181
- To get the ratings data for any skill (Sample)
/cms/fiveStarRateSkill.json?model=general&group=Knowledge&language=en&skill=aboutsusi&stars=3&callback=p&_=1526813916145
CMS –
- When visiting any skill make an ajax call to the server to fetch the skill data for the visited skill. The call takes in the URL from which we have to fetch data from and of course a datatype which is jsonp since server returns data in the JSON format, when the request succeeds we save the received rating to the application state and in the case or any errors we log the error for developers to debug.
// Fetch ratings for the visited skill $.ajax({ url: skillRatingUrl, jsonpCallback: 'pc', dataType: 'jsonp', jsonp: 'callback', crossDomain: true, success: function (data) { self.saveSkillRatings(data.skill_rating) }, error: function(e) { console.log(e); } });
- Save the fetched data to the application state, this data saved in the state will be used in several components and graph present on the ratings section.
saveSkillRatings = (skill_ratings) => { this.setState({ skill_ratings: data }) }
- Plug in the data received to the Bar chart component to visualize how ratings are divide.
- Import the required components on the top of the file from the recharts library which provides us with several interactive charts.
- Plug the data to the BarChart component through the data prop and render them to the page, this data is coming from the application state which we saved earlier. After that we define keys and styling for the X-Axis and Y-Axis and an interactive tooltip which shows up on hovering over any bar of that chart. We have 5 bars on the chart for each star rating all of different and unique colors and labels which appear on the right of each bar.
import {BarChart, Cell, LabelList, Bar, XAxis, YAxis, Tooltip} from 'recharts';
<div className="rating-bar-chart"> <BarChart layout='vertical' width={400} height={250} data={this.state.skill_ratings}> <XAxis type="number" padding={{right: 20}} /> <YAxis dataKey="name" type="category"/> <Tooltip wrapperStyle={{height: '60px'}} /> > </div>
- Display the average rating of the skill along with the stars
- Import the stars component from the react-ratings-declarative component.
import Ratings from 'react-ratings-declarative';
- Render the average ratings and the stars component which is available in the app state as saved before.
<div className="average"> Average Rating <div> {this.state.avg_rating ? this.state.avg_rating : 2.5} </div> <Ratings rating={this.state.avg_rating || 2.5} <Ratings.Widget /> <Ratings.Widget /> <Ratings.Widget /> <Ratings.Widget /> <Ratings.Widget /> </Ratings> </div>
- Display the total no of people who rated the skill, again, by using the ratings data saved in the state and calculating the total users who rated the skill by using a reduce function in ES6.
<div className="total-rating"> Total Ratings <div> {this.state.skill_ratings.reduce((total, num) => { return total + num.value }, 0)} </div> </div>
Outcome –
I hope this post helped you in understanding how the rating system is implemented in the CMS.
References –
- Check out which is used to render charts in the app.
- Reduce function in javascript
- API implementation in the server in this
- See sample analytics for the assistant apps | https://blog.fossasia.org/appending-a-rating-section-of-susi-skill-cms-to-the-skill-page/ | CC-MAIN-2022-21 | refinedweb | 606 | 51.68 |
Dropbox SDK for Go [UNOFFICIAL]Dropbox SDK for Go [UNOFFICIAL]
Uh OK, so why are you releasing this?Uh OK, so why are you releasing this?
InstallationInstallation
$ go get github.com/dropbox/dropbox-sdk-go-unofficial
Note that while the import path ends in
dropbox-sdk-go-unofficial, it actually exports the package
dropbox. There are additional subpackages, one for each namespace in the API:
github.com/dropbox/dropbox-sdk-go-unofficial/users
github.com/dropbox/dropbox-sdk-go-unofficial/files
github.com/dropbox/dropbox-sdk-go-unofficial/sharing
github.com/dropbox/dropbox-sdk-go-unofficial/team
UsageUsage
First, you need to register a new "app" to start making API requests. Once you have created an app, you can either use the SDK via an access token (useful for testing) or via the regular OAuth2 flow (recommended for production).
Using OAuth tokenUsing OAuth token
Once you’ve created an app, you can get an access token from the app’s console. Note that this token will only work for the Dropbox account the token is associated with.
// NOTE: this imports package `dropbox` import "github.com/dropbox/dropbox-sdk-go-unofficial" func main() { api := dropbox.Client(token, true) // second argument enables verbose logging in the SDK // start making API calls }
Using OAuth2 flowUsing OAuth2 flow
For this, you will need your
APP_KEY and
APP_SECRET from the developers console. Your app will then have to take users though the oauth flow, as part of which users will explicitly grant permissions to your app. At the end of this process, users will get a token that the app can then use for subsequent authentication. See this for an example of oauth2 flow in Go.
Once you have the token, usage is same as above.
Making API callsMaking API calls
Each Dropbox API takes in a request type and returns a response type. For instance, /users/get_account takes as input a
GetAccountArg and returns a
BasicAccount. The typical pattern for making API calls is:
Instantiate the argument via the
New*convenience functions in the SDK
Invoke the API
Process the response (or handle error, as below)
Here’s an example:
arg := users.NewGetAccountArg() if resp, err := api.GetAccount(arg); err != nil { return err } fmt.Printf("Name: %v", resp.Name)
Error HandlingError Handling
Note on using the Teams APINote on using the Teams API
All features of the Team API are supported except acting on behalf of team members. This should be available soon.
Note that to use the Team API, you will need to create a Dropbox Business App. The OAuth token from this app will only work for the Team API.
CaveatsCaveats
To re-iterate, this is an UNOFFICIAL SDK and thus has no official support from Dropbox
Only supports the v2 API. Parts of the v2 API are still in beta, and thus subject to change
This SDK itself is in beta, and so interfaces may change at any point | https://libraries.io/go/github.com%2Fdropbox%2Fdropbox-sdk-go-unofficial%2Fdropbox | CC-MAIN-2020-40 | refinedweb | 488 | 55.95 |
#include "pitches.h"
Now my questions. There is no bug_bot_music.cpp file. Matter of fact, the original sketch was copied and pasted out of a pdf file, so I don't have a .cpp with this sketch, as far as I know. Am I wrong to assume that a sketch doesn't have to have a .cpp file to compile correctly. And secondly, the pitches.h file is presently located in the library/tone directory, but evidently this new sketch is not finding it. So.....what am I doing wrong and where should I locate my files so the compiler finds them correctly. | http://forum.arduino.cc/index.php?topic=80508.0;prev_next=next | CC-MAIN-2014-49 | refinedweb | 103 | 77.53 |
To-do list in Grails
In the previous issue of JavaExpress I showed how to start working with Grails; install the environment, create the first project, domain classes with restrictions and how to use dynamic scaffolding. Now let us create a simple to-do list in Grails bottom-up. You will see how to develop a controller, use basic facilities of GORM and create custom views – crafting a CRUD application manually, without generating anything.
Creating a project and a domain class
Let us begin with creating a new project named ToDo. As we all remember from the previous article, this is all you need to do to start working with a Grails project – HSQLDB and Jetty bundled with Grails are ready to work. Let us create a domain class named
Task. The task will have a subject, a due date and a “finished” flag.
class Task { String subject Date dueDate Boolean completed static constraints = { } }
Creating a controller
The next step is creating a Task controller (like with a domain class, a controller can be created using the context menu of the project or using the command line). Let us define the following methods in it:
list,
edit,
save,
delete. They will be responsible for: displaying a list of tasks, displaying a form to add/edit a record, saving a record (a new or modified one) and deleting a record accordingly.
Retrieving records
Let us take the list action first. Passing data from a controller to a view in Grails is done by returning a map from an action. Keys of the map will represent variables available in the view. Our action can look like this:
def list = { [tasks:Task.findAll()] }
The map is created using the square brackets notation. There will be a list of tasks retrieved from the database under the key tasks. You may notice a Groovy language feature – the lack of the return keyword. By default the result of the last executed statement is returned, in the above case the created map.
To make things complete we need a GSP file which will render our tasks. Select Views and Layouts -> task from the project, New -> GSP File from the context menu and type list as the name. Grails uses the convention-over-configuration principle, so the view file is named exactly the same as the action. If needed Grails could render any other view, but now the out-of-the-box functionality is sufficient.
Let us add the following code to our view:
<g:each ${task} </g:each>
We are using here a tag bundled with Grails which lets us to iterate over a collection of elements in the view. The in attribute holds the variable over which we will iterate. The
var attribute defines the name of the element in the iterations. Without setting this attribute the element will be named
it, just like the default parameter in closures. You could add a status attribute which will be the name of a variable storing a counter of the iterations (useful when creating numbered lists etc.)
You could try and run the project to test it, but we do neither have any records nor a view to add them.
BootStrap.groovy
We will get a little help from the BootStrap.groovy file. It contains the
init section which is executed during the application start-up. We can add the following code to it:
new Task(subject:"Pranie", priority:1, dueDate:new Date(), completed:false).save()
This code will create one task and store it in the database. The example shows also how to create class instances passing values of its attributes – it is another nice feature of Groovy. Grails also gives us the ability to create an instance of a domain class with an automatic assignment of HTTP request parameters to attributes. We will use it later in saving a new task.
After such a modification of the BootStrap file our application should display the first task on the list.
Adding and editing a record
Adding and editing a record will be done using a shared view. If no identifier is passed, the application will display an empty form to add a new task. In the case when there is an identifier, before displaying the form the application will retrieve the appropriate record to edit it. Storing the records will be done in a shared method
save.
Let us prepare the
edit view (similarly to the
list view). You do not have to write anything in the controller in the edit action, because we want only to add a new record. An empty form will be sufficient. It may look like this:
<g:form Subject: <g:textField<br/> Due Date: <g:datePicker<br/> Completed: <g:checkBox<br/> <g:submitButton </g:form>
A new
g:form tag is show here. It is used to build HTML forms together with
g:textField,
g:datePicker,
g:checkbox and
g:submitButton. I encourage to read the documentation regarding the possible attributes used to configure these tags. Two new interesting Groovy features appear in this code as well: the
?. safe navigation operator which prevents a
NullPointerException to be thrown (when the left operand is
null the whole expression returns
null as well) and
?: which works similar to its counterpart in Java (if the expression on the left is
null or
false the right expression is returned, otherwise it stays the same). Thanks to handling the
null and default values the form can be used to both editing records and adding new ones.
The form sends data to the
save action which stores a new record:
def task = new Task(params) task.save() redirect(action:"list")
This action creates a new
Task object based on the passed map of HTTP request parameters (
params). Then it stores the record and performs a redirect to the
list action.
Let us add a link allowing us to edit a record and modify the
edit action to retrieve a record before displaying the form. Start with the
list view:
<g:each <g:link${task}</g:link><br/> </g:each>
The
g:link tag is introduced here which allows us to create links. As you might have noticed Grails supports passing names of controllers, actions and identifiers in forms and links. Adhering to the Grails convention simplifies work, but it is possible to control it if needed.
The modified edit action looks like this:
if (params.id) { [task:Task.get(params.id)] }
If the request parameter named id is passed, the application is retrieving a
Task record with that
id. The condition used here looks quite interesting. The params variable is a map containg the HTTP request parameters which are of type
String. How does it work then? It is another interesting feature; Groovy Truth. Not only
boolean type expressions can be used in conditions. 0 (zero), an empty string,
null, an empty array on an empty map are also treated as
false in conditions. It simplifies many expressions.
The only remaining thing is modifying the
save action. Before it only created a new record based on the request parameters, now it will have to update an existing record as well:
def task if (params.id) { task = Task.get(params.id) task.properties = params } else { task = new Task(params) } task.save() redirect(action:"list")
Deleting a record
In order to delete record let us add a new link next to each record which would trigger the
delete action. Everyone will manage to create it by himself.
And how will the controller action look like? Not to complex as expected:
def task = Task.get(params.id) task.delete() redirect(action:"list")
Similarly to the save action the application retrieves a record based on the request parameter. Next it is deleted and the list of tasks is displayed.
Summary
In this article I have shown how to create a simple Grails application with all CRUD operations. This time no scaffolding was used and everything was done manually. The application is not very complex, but it is fully functional and what is most important – it did not take too much time. The basic features of GORM (Grails Object Relationship Mapping) were introduced which allowed us to retrieve, store and delete records. We know what a domain class, a controller and views (the basic components of Grails) look like. At the same time some interesting features of the Groovy language were mentioned.
What next
It is widely known that solving problems improves learning. As an exercise I suggest performing the following tasks:
- modifying the task list to be more readable and user-friendly;
- introducing data validation (e.g. the task subject not being empty). As a hint: the constraints section of a domain class and validate method. The
g:renderErrorstag will be useful as well;
- adding a sidebar menu on the page. As a hint: modifying the page layout by adding an additional element which is the menu.
The source code is located at. Maybe some of the readers would like to contribute to this project. Best wishes and have fun.
Translation by Paweł Cegła
Odniosłem wrażenie, że artykuł napisany jest po łebkach :/ Wykonuje instrukcje krok po kroku i niestety pierwsze uruchomienie w moim przypadku kończy się błędem. I to jeszcze w NB w którym wszystko działa out of the box.
Udało mi się uruchomić przykład, ale dalej mam wrażenie, że niektóre punkty można napisać jaśniej (np. gdzie dokładnie utworzyć list.gsp).
Super, że się udało. W każdej chwili możesz skorzystać z grupy dyskusyjnej JAVA exPress. Na 100% znajdzie się ktoś, kto będzie Ci w stanie pomóc. Czasami ciężko jest trafić do każdego. Z jednej strony są ludzie tacy jak Ty, którzy potrzebują dokładnych instrukcji (co jest zrozumiałe w przypadku technologii której nie znasz), a z drugiej strony pojawiały się głosy (z tego co pamiętam to na dzone), że przykład jest zbyt uproszczony.
W przypadku dalszych problemów spróbuj napisać na naszą grupę dyskusyjną. Na 100% znajdą się osoby, co będą chciały Ci pomóc.
Spoko :) Dzięki za zainteresowanie. Jasne, że ciężko trafić do każdego, ale dobrze, że przynajmniej podejmuje się próbe. Fakt, że Grails nie znam zupełnie. No i wielkie szacun za JavaExpress! | http://www.javaexpress.pl/article/show/Todo_list_in_Grails | CC-MAIN-2020-16 | refinedweb | 1,690 | 72.87 |
Is this another overly hyped article about JavaScript. Perhaps!!! Maybe after reading this you will share my enthusiasm 😁. In 2020 JavaScript will be getting some exciting new features. Most of these features are already in the final stage of proposal and scheduled to release in 2020.
Some of these features are already available in the latest version of Chrome and Firefox browsers. So you can start playing with them in your browser right away. If not you can also head over to which is an online ide that allows you to write code in your browser.
If you would like to see all the proposals for new JavaScript features you can find them in the following github link.
⚡️
Excited!!!, let’s dive in.
Object.fromEntries()
First on our list is a
Object method. It is very common in javascript to convert objects to array and vice versa. Especially when you are working with database like firebase or some other no-sql service we are often required to do these type of transformation. In es2017
Object.entries() was introduced which returns an array from an
Object with its own key property.
Let’s take a look at an example.
const object1 = { foo: "somestring", bar: 100 }; for (let [key, value] of Object.entries(object1)) { console.log(`${key}: ${value}`); } // Outputs--> // foo: somestring // bar: 100
Object.fromEntries does the opposite of
Object.entries. Given an array it will output an object. Here’s an example
const entries = new Map([ ['foo', 'bar'], ['baz', 42] ]); const obj = Object.fromEntries(entries); console.log(obj); // expected output: Object { foo: "bar", baz: 42 }
Dynamic
import
This new feature will allow JavaScript to dynamically load modules as needed. Currently when we import modules in JavaScript they are loaded
pre-runtime. This is why we keep them at the top of our files. This works for most cases. However, to increase performance, what if we could dynamically load some of our modules at runtime. This new feature will allow that. Below is an example of dynamic module import.
const main = document.querySelector("main"); for (const link of document.querySelectorAll("nav > a")) { link.addEventListener("click", e => { e.preventDefault(); import(`./section-modules/${link.dataset.entryModule}.js`) .then(module => { module.loadPageInto(main); }) .catch(err => { main.textContent = err.message; }); }); }
Dynamic imports will allow developers to have greater control in how modules get loaded in application.
- It gives us the power to boost performance by not loading code until it is likely to be used
- It allows to catch error scenarios when application fails to load a non-critical module
- It can ensure modules that are dependent on each other don’t get caught into a race condition
You can read about dynamic imports more in the following GitHub link
⚡️
String.prototype.matchAll()
This method returns an iterator object for all matches in a string. Let’s jump right into an example
const re = /(Dr\. )\w+/g; const str = 'Dr. Smith and Dr. Anderson'; const matches = str.matchAll(re); for (const match of matches) { console.log(match); } // outputs: // => ["Dr. Smith", "Dr. ", index: 0, input: "Dr. Smith and Dr. Anderson", groups: undefined] // => ["Dr. Anderson", "Dr. ", index: 14, input: "Dr. Smith and Dr. Anderson", groups: undefined]
This method makes it really easy to work with strings, sub-strings and pattern matching with regex.
Promise.allSettled
This one is probably my favourite so far. It does exactly as the name suggests. It keeps track of settle promises. Let’s elaborate this through an example.
Let’s say we have an array of promises. We can execute them with
Promise.all. However, to know their status (which ones resolved and which ones failed) we need to iterate them all and return new value with the status.
function reflect(promise) { return promise.then( (v) => { return { status: 'fulfilled', value: v }; }, (error) => { return { status: 'rejected', reason: error }; } ); } const promises = [ fetch('index.html'), fetch('') ]; const results = await Promise.all(promises.map(reflect)); const successfulPromises = results.filter(p => p.status === 'fulfilled');
As you can see we are passing in a function called
reflect to return the status. The new proposed api will not require this
reflect function. We will be able to do the following
const promises = [ fetch('index.html'), fetch('') ]; const results = await Promise.allSettled(promises); const successfulPromises = results.filter(p => p.status === 'fulfilled');
Optional Chaining for JavaScript
If you have used Angular or Typescript chances are you are familiar with this feature. We often have to check whether an intermediate node exists in a tree like deep object.
var street = user.address && user.address.street;
The Optional Chaining Operator allows a developer to handle many of those cases without repeating themselves and/or assigning intermediate results in temporary variables:
var street = user.address?.street var fooValue = myForm.querySelector('input[name=foo]')?.value
Example taken from offcial github proposal page.
Optional chaining can be used in three positions
obj?.prop // optional static property access obj?.[expr] // optional dynamic property access func?.(...args) // optional function or method call
Indeed an exciting time for JavaScript. There are a couple of other features that are also up for release in 2020.
BigInt and
globalThis are notable. Hopefully this article was informative, for more articles like this please follow me and hit that like button 🌞 🌞 🌞
Discussion (28)
Optional Chaining is my favorite though.
Not to mention nullish coalescing. 😍
So here's an opinion: none of these are at all interesting as 'features'. They don't really extend the language - at best they're sugar over what's there already. The benefits are minor.
The downsides are not insignificant. Extending the language syntax like this means you have to 'know' a lot more magic symbols and incantations in order to 'know' JavaScript. Every extension like this makes it a harder language to learn with, to my view, very little benefit. "Scheme for the browser" has never looked so complicated.
Nice article though.
If that opinion stands on "lot more magic symbols and incantations in order to 'know' JavaScript" - what does this 'know' means?
Does mastering of JS mean knowing all the features? - I do not think so, there is documentation anyway.
Does mastering of JS mean using all the features? - same answer I guess, no one is using all what is available out there.
"magic symbols and incantations" and "The downsides are not insignificant."? - No, but nice hyperbole. There is documentation, and i cannot think about realistic scenario in which someone knows how to use String.prototype.match() and is unable to get how String.prototype.matchAll() works, or same with Object.entries() and Object.fromEntries() - I think this is just filling holes in something what i would call language 'symmetry' in this case (maybe not so needed, but better to have than to not have :-)).
Anyway are problems in understanding really coming from number of features or more from the usage itself? How long is RegExp there? I am weak in RegExp (my fault), but sometimes i am using it and it is handy, BUT i've seen few professional devs 10+ years in a job staring long minutes into some weird RegExp not knowing how exactly(!) it works...
I agree this is nothing big like ES6. And I also kind of agree than less is more, but not always.
Most of it (all?) is already ready to use in chrome or Babel, optional chaining will be usable, waiting for it coming into chrome, Object.fromEntries() is usable, same with BigInt and Promise.allSettled - i am not even using any framework so cannot comment module import and i am not professional dev anyway, I just do not think things are black or white.
I'd say to 'know' javascript implies, at the very least, being handed any snippet of JS code (that's not written specifically to be unreadable) and being able to figure out what it does on a language-level without having to consult the documentation.
This is specially relevant in cases like the
?.operator, which is hard to google when encountered in the wild.
Agree. Let's just stick to C++, or better even, assembly language. Much less to learn!
I do agree this list didn't bring much to the table, though... (except the dynamic runtime imports perhaps?) They're might be more interesting things coming up. Were private fields mentioned here?
Nope I didn't mention that. Think that is still in stage 2..might be mistaken
TypeScript 3.7 already has an Optional Chaining:
Switch to TS, guys, and you won't have to wait 2020, lol.
😆😆😆 looool
Optional chaining! 🎉
Hell yeah!!!
The biggest question is browsers support for those amazing features
If you use a transpiler (eg, Babel/Typescript), they'll all be available
Optional Chaining is definitely my pick of the bunch here. The amount of time and hassle this will save is fantastic!
Thanks for sharing the good news!
Funny how those are all things that Ruby has had for ages now (except the promise-related one, which is obviously a javascript-specific feature).
Ohh man I love ruby. Reminds me of good ol days.
Nice piece with succinct examples, great work!
Thanks for this post! Very useful information!
Love the look of the Dynamic Imports, that will make resource management so much better.
They all mean nothing to me because I'm such a noob I have no idea how to use such things and what they are good for.
feelsbadman
Everyone has to start somewhere. You will get there eventually. Not too long ago we all were noobs :)
Agreed. I'm a noob with 15 years experience
Fake it till you make it brah
Thank you Shadid!
Hello Optional Chaining!
I was hoping that Temporal would be part of ECMAScript 2020. Sadly, it appears to be only in stage 2 at the moment. github.com/tc39/proposal-temporal
Fabulous article, I’ve added new vlog too about ES6 features which include:
Array Destructing
Array Spreading
Object Destructing
Object Spreading
You can check it on youtu.be/Z5FxVKRfocw | https://practicaldev-herokuapp-com.global.ssl.fastly.net/shadid12/new-javascript-features-coming-in-2020-that-will-surely-rock-your-world-54b | CC-MAIN-2021-10 | refinedweb | 1,660 | 68.57 |
import java.util.Scanner; class CheckEvenOdd { public static void main(String args[]) { int num; System.out.println("Enter an Integer number:"); //The input provided by user is stored in num Scanner input = new Scanner(System.in); num = input.nextInt(); /* If number is divisible by 2 then it's an even number * else odd number*/ if ( num % 2 == 0 ) System.out.println("Entered number is even"); else System.out.println("Entered number is odd"); } }
Output 1:
Enter an Integer number: 78 Entered number is even
Output 2:
Enter an Integer number: 77 Entered number is odd
there are errors in the program its saying that FILE DOES NOT CONTAIN CLASS SCANNER :\
if i run any programs like usergetinputs it shows the following error
” class java.util.Scanner not found in import.”
please help me to correct this error thank you.
import package java.util.Scanner;
Then it will not show any error..!
I tried this and there were no errors whatsoever . | http://beginnersbook.com/2014/02/java-program-to-check-even-or-odd-number/ | CC-MAIN-2017-30 | refinedweb | 160 | 58.58 |
Created on 2010-08-11 23:42 by Alex.Roitman, last changed 2010-12-02 04:36 by ncoghlan. This issue is now closed.
Importing the module with the following contents results in RuntimeError:
==================
import os
pid = os.fork()
if pid == 0:
print "In the child"
else:
print "In the parent"
print "Done\n"
==================
Running the same module as main works just fine, so it seems to be a purely import issue.
I looked into the 2.6.6rc1 source. This is what I think happens in Python/import.c file:
1. After the fork() call, _PyImport_ReInitLock() is run. It sets import_lock_thread to -1 in the child, line 310.
2. In _PyImport_ReleaseLock() line 290 compares import_loc_thread to the current thread id, and if they are not the same then -1 is returned, which results in RuntimeError in PyImport_ImportModuleLevel (line 2186-2189)
So this is guaranteed to happen in the child, every time fork() is executed inside the module being imported. If I change line 290 to be:
if (import_lock_thread != me && import_lock_thread != -1)
then import proceeds fine, although I'm not sure this is a proper solution.
This happens on Linux, Darwin, and Cygwin, with python 2.6.5 and higher. I'd be happy to assist solving this, please let me know how I can help.
This may be a case of "don't do that". Starting a new thread or process during import (ie: while the import lock is held) is dangerous. Nosying Brett, since he'll know the real story.
Without looking closer at it, don't do that. =)
I guess I am missing something here. In a complex program, everything will be executed in some module or another. Consequently, the module that contains the fork() call will cause the interpreter to quit.
How can this be worked around, short of placing the fork() in the main module?
> How can this be worked around, short of placing the fork()
> in the main module?
Why wouldn't you place the fork() call in a function?
I can place it in a function. But if I execute that function from anything other than main module, the fork() will be called while import lock is held, one way or another. It will just happen in another module. So what?
1. If fork should not be called during import, it could raise an exception when invoked from import. But it does not. Is that a bug then? BTW, fork during import worked with python 2.4 just fine.
2. The whole issue7242 was devoted to work out import locks during forking. 5 months ago r78527 was committed to to just that (although it is not perfect). If this is not the proper use case then had it been done in error?
3. belopolsky: Thanks for the advice to use the mailing list. I'd appreciate it if instead you refrained from publishing my email address on this page.
Added Greg to nosy list as the one that fixed issue 7242 with the current _PyImport_ReInitLock semantics.
Also kicking over to Barry regarding implications for 2.6.6 (this is a regression from 2.6.4 due to the resolution of 7242).
7242 was about forking from a *thread*. This is about forking as a side effect of import, which, just like spawning a thread as a side effect of import, can easily cause issues.
The RuntimeError noted by the OP isn't thrown by the fork() call - it is thrown at the end of the import when control is returned to the main module. Completely reinitialising the lock without accounting for the current depth of nesting is incorrect. Instead, I believe ReInitLock should look more like:
if (import_lock != NULL)
import_lock = PyThread_allocate_lock();
if (import_lock_level > 1) {
/* Forked as a side effect of import */
long me = PyThread_get_thread_ident();
import_lock_thread = me;
import_lock_level--;
} else {
import_lock_thread = -1;
import_lock_level = 0;
}
(I haven't tested that yet, but will soon)
One slight tweak to that suggested change - the lock reinitialisation needs to acquire the new lock in the first branch.
Minimal patch attached (no niceties like NEWS or unit tests included yet)
Test script attached that demonstrates the underlying problem directly via imp.lock_held() (this could easily form the basis of a unit test)
I think it's too late to try to get this into 2.6.6. rc2's already been released, I don't expect/want an rc3, and I'm not comfortable changing this at this point. Unless you can convince me it's absolutely critical, I won't approve this for 2.6.6.
Are there any applications out there that actually rely on forking during import?
(someone discovered this bug... i'd like to know why. i think its a disgusting thing to do but never explicitly disallowed it in the past)
It turns out my proposed patch is incorrect anyway - it will do the wrong thing if a thread *other* than the one doing the fork is in the middle of a nested import at the time the fork occurs.
With issue 7242 establishing that the current thread ID may not survive the forking process on all platforms, the only way I can see to get completely correct semantics for the fork-as-a-side-effect of import case is to give the forking thread another way to detect "did I own the import lock before the fork?". One way to do that would be to move the lock nesting count into thread local storage, although that would likely suffer cross-platform incompatibility fun and games as well.
Given that, I'm inclined to go with what Brett said: don't do that. Use a __name__ == "__main__" guard so the fork only happens when run as a script, not when imported.
gregory.p.smith: This is my use case: we had the following situation with the test scripts at work. Each script is required to import TestApi module in order to run the tests. That module in turn imported the module that forks, and in the parent waits for the child to exit, then kills all child's children processes. That way tests don't leave any processes behind.
So any script that imported the cleanup module, whether directly or via another module, had this cleanup functionality "for free". One workaround for this issue would be to change all existing test scripts to call the cleanup function, instead of the cleanup module calling it at the module level.
I can see your reservations about forking/starting threads during import, but it seems like it either should work or it should be disallowed. The thing is, the actual import is working fine with the fork() call, it's releasing the lock that is messed up, because it was not initialized correctly after the fork. The patch attached by ncoghlan looks good though.
I already worked around this for my use case.
For the future, it would be nice if fork() raised an exception if called during the import, and if the documentation mentioned that forking while in import is not allowed.
Agreed on the explicit exception and documentation. :)
Will starting a thread while in import also be disallowed? If so, issue 7242 will also become moot...
On further further reflection - I'm back to thinking my patch is correct. With the way fork is now implemented, the forking thread *always* holds the import lock, so the assumption in my patch regarding the meaning of the nesting level is correct.
It could use a comment in _PyImport_ReInitLock to better explain that, though.
Unless there are any objections, I'll apply the fix to 2.7, 3.1 and 3.2.
2.6 is out of luck though (as per Barry's comment). I'll do a doc change for that, but I can't promise I'll get to it before the binary releases go out.
Fixed for 3.2 in r86928.
The fix has not been backported to 3.1, since it depends on the fix for issue 7242 (r78527) which was itself never backported to 3.1 after being forward ported to the py3k branch as part of a bulk merge (r83318)
Backporting to 2.7 would also be a manual process (although much easier, since issue 7242 is already fixed in that branch)
Given the obscurity of the error, I'm going to close this as fixed without backporting it. Anyone that wants it fixed in the 2.7 and 3.1 maintenance branches is free to develop and post the requisite patches :) | https://bugs.python.org/issue9573 | CC-MAIN-2021-25 | refinedweb | 1,419 | 73.37 |
Do you ever want to know how the SECRET_KEY works? It’s sitting in your settings.py file but do you ever wonder why you need it? If you look at the documentation, you’ll discover some very interesting things about the SECRET_KEY setting.
In the Cryptographic signing section of the Django docs, it says:.
And I’m going to add one more thing to this list: Signing cookies so that you know that your users’ cookies are not being tampered by a hacker.
How can you use the SECRET_KEY to determine if data has been tampered?
The first thing you need to do is sign your data.
from django.core.signing import Signer signer = Signer() value = signer.sign("My secret data") value
Now, your signed data is saved in the
value variable. How do you make sure that your data hasn’t been tampered with?
from django.core import signing value += 'd' try: original = signer.unsign(value) except signing.BadSignature: print ("Tampering detected!")
If the value is different, the
unsign function will throw a
BadSignature exception. The
Signer class uses the
setting.SECRET_KEY to create the hash of the signed data.
Next time you have data that you need to keep from being tampered remember the
Signer class. a Mixin
How to Use a Virtual Environment to run you Django app | https://chrisbartos.com/articles/what-is-secret-key/ | CC-MAIN-2018-13 | refinedweb | 222 | 68.87 |
Simple and tiny yield-based trampoline implementation.
Project description
This trampoline allows recursive functions to recurse virtually (or literally) infinitely. Most existing recursive functions can be converted with simple modifications.
The implementation is tiny: the gist of the module consists of a single function with around 30 lines of simple python code.
Conversion from simple recursion
Trampolined functions are generators: Instead of recursing into other functions directly, they yield the generator of the call they want to recurse into. The generator of the first call is invoked using the trampoline() function.
This is easiest to understand with an example. Consider this simple recursive function:
>>> def print_numbers(n): ... "Print numbers 0..n (recursive)." ... if n >= 0: ... print_numbers(n - 1) ... print(n) >>> >>> print_numbers(2000) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): RecursionError: maximum recursion depth exceeded in comparison
This exhausts the stack when calling it with too large n. Compare this with our trampoline version:
>>> from trampoline import trampoline >>> >>> def print_numbers(n): ... "Print numbers 0..n (trampolined)." ... if n >= 0: ... yield print_numbers(n - 1) ... print(n) >>> >>> trampoline(print_numbers(2000)) # doctest: +ELLIPSIS 0 1 2 ... 1999 2000
We added a yield statement to the recursive call, and wrapped the function call with trampoline().
trampoline takes the generator created by the print_numbers(2000) call and runs it. The generator then yields another generator of print_numbers, which then takes over, effectively recursing into it.
When a generator returns, the yielding generator takes over again.
Of course, the trampolined function doesn’t have to call itself. Any other trampolined function generator will do.
Return values
Consider this recursive factorial:
>>> def factorial(n): ... "Get factorial of n (recursive)." ... if n <= 1: ... return 1 ... return factorial(n - 1) * n >>> >>> print(factorial(2000)) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): RecursionError: maximum recursion depth exceeded in comparison
Again, this exhausts the stack at our factorial(2000) call.
We now want to convert it for our trampoline. But how do we get the result of the factorial call? This uses a rarely seen feature of yield: its return value as an expression. With this, trampoline can send the result of the callee back to the caller. Here is the trampolined solution:
>>> def factorial(n): ... "Get factorial of n (trampolined)." ... if n <= 1: ... return 1 ... return (yield factorial(n - 1)) * n >>> >>> print(trampoline(factorial(2000))) # doctest: +ELLIPSIS 3316275092450633241175393380576324038281117208105780394571935437...
The function is suspended at the yield expression, trampoline continues execution with the yielded generator, and afterwards provides us with the returned value. In the end, trampoline returns the value that was returned by our first generator.
Python requires that we add braces around a yield expression after a return, making it look a little more ugly. We can circumvent this by adding a variable:
>>> def factorial(n): ... "Get factorial of n (trampolined)." ... if n <= 1: ... return 1 ... value = yield factorial(n - 1) ... return value * n >>> >>> print(trampoline(factorial(10))) 3628800
In this case, no extra braces are required.
Exceptions
Exceptions are handled just as one might expect:
>>> def factorial(n): ... "Get factorial of n (trampolined). Unless we don't like the number." ... if n <= 1: ... return 1 ... if n == 500: ... raise Exception("I don't like this number") ... return (yield factorial(n - 1)) * n >>> >>> print(trampoline(factorial(1000))) Traceback (most recent call last): File "/usr/lib/python3.7/doctest.py", line 1329, in __run compileflags, 1), test.globs) File "<doctest README.rst[10]>", line 1, in <module> print(trampoline(factorial(1000))) File "trampoline.py", line 39, in trampoline raise exception 25, in trampoline res = next(stack[-1]) File "<doctest README.rst[9]>", line 6, in factorial raise Exception("I don't like this number") Exception: I don't like this number
As seen in this example, event tracebacks are preserved, hiding no information in error cases. There is just one additional stack frame of the trampoline function for each generator-yield.
This also means that yields work just fine inside with blocks.
Tail Calls
A trampolined function can raise TailCall (which is an exception) passing it the generator of the next function call:
>>> from trampoline import TailCall >>> >>> def factorial(n, x=1): ... "Get factorial of n (trampolined)." ... if n <= 1: ... return x ... raise TailCall(factorial(n - 1, x * n)) ... yield # just to make this a generator >>> >>> # This could take some seconds (the numbers are extremely large) >>> print(trampoline(factorial(100000))) # doctest: +ELLIPSIS 282422940796034787429342157802453551847749492609122485057891808654...
This implementation uses constant memory, and theoretically works with any n (until the result gets too large).
Beware that we still need to have a generator function, so there has to be a yield in the function, reachable or not. The
raise TailCall(...) yield
idiom is recommended if the function doesn’t yield any other calls.
Suggestions
Expose a wrapper
If you want to hide the trampolined-ness of a function and simplify its usage, expose a wrapper function that calls the trampolined function with trampoline:
>>> def exposed_factorial(n): ... "Get factorial of n." ... return trampoline(factorial(n)) >>> >>> print(exposed_factorial(42)) 1405006117752879898543142606244511569936384000000000
Just make sure to always use the trampolined version from other trampolined functions. Otherwise it will recurse as usual, taking no advantage of the trampoline.
Use it in classes
trampoline works just fine with methods.
>>> class Node(object): ... ... def __init__(self, name, children=()): ... self.name = name ... self.children = children ... ... def do_print(self, prefix=""): ... print(prefix + self.name) ... for child in self.children: ... yield child.do_print(prefix=" " + prefix) >>> >>> root = Node("root", [Node("first", [Node("one")]), Node("second", [Node("two"), Node("last")])]) >>> trampoline(root.do_print()) root first one second two last
Subclasses can extend or override these trampolined methods to provide their own implementation. Just make sure to always yield super calls when extending a trampolined method.
Caveats
Lastly, there are some downsides to consider.
Yield
As we use yield for recursion, we cannot use it to yield actual values.
Simple cases could be rewritten with a callback function or by appending or returning a list.
Memory consumption
Recursing hundreds of thousands of times allocates a lot of objects for local variables and for the generators themselves, which all need to exist at the same time. When overdoing it, this can easily lead to multiple gigabytes on the stack.
Of course, if we mess up our exit condition and recurse infinitely, we will exhaust our memory.
Use tail calls if they are an option. Otherwise an iterative approach may be preferable.
Performance
As said above, when recursing extremely deeply, the stack may get rather large. These objects not only have to be allocated, but need to be freed as well when done, which slows down the return path.
Function call and exception handling overhead may come into play for functions that don’t recurse deeply or use a lot of tail calls. This should only matter for functions that don’t do a lot of work. A simple tail-calling count-down from one million takes about one second on a mediocre laptop.
Tracebacks
When an exception occurs at ridiculous recursion depth, displaying the traceback may take a while, depending on the exception handler and formatter. Reducing sys.tracebacklimit may help. Of course, the traceback will then be cut off. Python’s default traceback limit applies here too, printing the last 1000 frames.
Tail calls don’t have this problem, as they don’t appear in tracebacks.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages. | https://pypi.org/project/trampoline/ | CC-MAIN-2020-24 | refinedweb | 1,236 | 50.94 |
phylter is a mini-dsl filter language. You can use it to allow users to write there own filters without letting them access your database directly (and thus, need to understand your database layout).
The language implements the following operators:
== (equals),
> (greater than),
< (less than),
>= (greater than or equals),
<= (less than or equals) and the two operators
and and
or.
The precende of the
and and
or operator follows the python operator precedence.
from phylter import parser parser = parser.Parser() query = parser.parse("foo == 'bar'") query.apply(data)
The query is passed as string to a
Parser instance which builds a
Query object. The
apply method applies the query to the passed iterable using the most appropiate backend (see below).
The
Query's
apply method decides the best backend to use based on the type of the passed iterable. As a fallback, the
ObjectsBackend will be used.
The most universal backend is the
ObjectsBackend. This backend applies the query to standard python objects.
The
DjangoBackend will be used if the
iterable argument of the
apply method is a Django
QuerySet or
Manager instance. The
DjangoBackend translates the
Query object into a Django database query:
class Person(models.Model): first_name = models.CharField(...) last_name = models.CharField(...) age = models.PositiveIntegerField(...) query = Parser().parse("first_name == 'Alice') query.apply(Person.objects)
will result in a Django query roughly equivalent to
Person.objects.filter(first_name='Alice')
and a query like
first_name == 'Bob' or age > 20 in
Person.objects.filter(Q(first_name='Bob') | Q(age__gt=20))
See LICENSE.txt | https://code.not-your-server.de/phylter.git | CC-MAIN-2017-39 | refinedweb | 252 | 60.11 |
Signals¶
Introduction¶
Signals are Godot’s version of the observer pattern. They allow a node to send out a message that other nodes can listen for and respond to. For example, rather than continuously checking a button to see if it’s being pressed, the button can emit a signal when it’s pressed.
Note
You can read more about the observer pattern here:
Signals are a way to decouple your game objects, which leads to better organized and more manageable code. Instead of forcing game objects to expect other objects to always be present, they can instead emit signals that all interested objects can subscribe to and respond to.
Below you can see some examples of how you can use signals in your own projects.
Timer example¶
To see how signals work, let’s try using a Timer node. Create a new scene with a Node and two children: a Timer and a Sprite. In the Scene dock, rename Node to TimerExample.
For the Sprite’s texture, you can use the Godot icon, or any other image you
like. Do so by selecting
Load in the Sprite’s Texture attribute drop-down menu.
Attach a script to the root node, but don’t add any code to it yet.
Your scene tree should look like this:
In the Timer node’s properties, check the “On” box next to Autostart. This will cause the timer to start automatically when you run the scene. You can leave the Wait Time at 1 second.
Next to the “Inspector” tab is a tab labeled “Node”. Click on this tab and you’ll
see all of the signals that the selected node can emit. In the case of the Timer
node, the one we’re concerned with is “timeout”. This signal is emitted whenever
the Timer reaches
0.
Click on the “timeout()” signal and click “Connect…”. You’ll see the following window, where you can define how you want to connect the signal:
On the left side, you’ll see the nodes in your scene and can select the node that you want to “listen” for the signal. Note that the Timer node is red - this is not an error, but is a visual indication that it’s the node that is emitting the signal. Select the root node.
Warning
The target node must have a script attached or you’ll receive an error message.
On the bottom of the window is a field labeled “Method In Node”. This is the name
of the function in the target node’s script that you want to use. By default,
Godot will create this function using the naming convention
_on_<node_name>_<signal_name>
but you can change it if you wish.
Click “Connect” and you’ll see that the function has been created in the script:
extends Node func _on_Timer_timeout(): pass # replace with function body
public class TimerExample : Node { private void _on_Timer_timeout() { // Replace with function body. } }
Now we can replace the placeholder code with whatever code we want to run when the signal is received. Let’s make the Sprite blink:
extends Node func _on_Timer_timeout(): # Note: the `$` operator is a shorthand for `get_node()`, # so `$Sprite` is equivalent to `get_node("Sprite")`. $Sprite.visible = !$Sprite.visible
public class TimerExample : Node { public void _on_Timer_timeout() { var sprite = GetNode<Sprite>("Sprite"); sprite.Visible = !sprite.Visible; } }
Run the scene and you’ll see the Sprite blinking on and off every second. You can change the Timer’s Wait Time property to alter this.
Connecting signals in code¶
You can also make the signal connection in code rather than with the editor. This is usually necessary when you’re instancing nodes via code and so you can’t use the editor to make the connection.
First, disconnect the signal by selecting the connection in the Timer’s “Node” tab and clicking disconnect.
To make the connection in code, we can use the
connect function. We’ll put it
in
_ready() so that the connection will be made on run. The syntax of the
function is
<source_node>.connect(<signal_name>, <target_node>, <target_function_name>).
Here is the code for our Timer connection:
extends Node func _ready(): $Timer.connect("timeout", self, "_on_Timer_timeout") func _on_Timer_timeout(): $Sprite.visible = !$Sprite.visible
public class TimerExample : Node { public override void _Ready() { GetNode("Timer").Connect("timeout", this, nameof(_on_Timer_timeout)); } public void _on_Timer_timeout() { var sprite = GetNode<Sprite>("Sprite"); sprite.Visible = !sprite.Visible; } }
Custom signals¶
You can also declare your own custom signals in Godot:
extends Node signal my_signal
public class Main : Node { [Signal] public delegate void MySignal(); }
Once declared, your custom signals will appear in the Inspector and can be connected in the same way as a node’s built-in signals.
To emit a signal via code, use the
emit_signal function:
extends Node signal my_signal func _ready(): emit_signal("my_signal")
public class Main : Node { [Signal] public delegate void MySignal(); public override void _Ready() { EmitSignal(nameof(MySignal)); } }
Conclusion¶
Many of Godot’s built-in node types provide signals you can use to detect
events. For example, an Area2D representing a coin emits
a
body_entered signal whenever the player’s physics body enters its collision
shape, allowing you to know when the player collected it.
In the next section, Your first game, you’ll build a complete game including several uses of signals to connect different game components. | https://docs.godotengine.org/en/3.1/getting_started/step_by_step/signals.html | CC-MAIN-2019-39 | refinedweb | 881 | 62.48 |
If you download the installer:
It will look in your system registry to see which versions of Java you have installed and will choose a correct/valid one or open a web page to direct you to install a correct/valiid one. No doubt you don't have a Java 1.8 (64 bit) or higher Java version installed on your system.
Or you can look at the Wiki details:
import tkinter as tk root = tk.Tk() def main_account_screen(): main_screen = tk() main_screen.geometry("1920x1080") #set the configuration of GUI window main_screen.title("Account Login") #set the title of GUI window #create a FORM label tk.Label(text="Choose login Or Register", bg="blue", width="300", height="2", font=("Calibri", 13)).pack() tk.Label(text="").pack() #create a Login button tk.Button(text="Login", height="2", width="30").pack() tk.Label(text="").pack() #create a register button tk.Button(text="Register", height="2", width="30").pack() main_screen.mainloop() # start the GUI main_account_screen() # call the main_account_screen() function | https://www.eclipse.org/forums/feed.php?mode=m&l=1&basic=1&frm=89&n=10 | CC-MAIN-2019-39 | refinedweb | 165 | 52.97 |
How to access methods of MainWindow from Dialog Form (Subclassing I guess!)
Hello, please I need help.
I have my MainWindow and my Dialog, both created with QDesigner.
My MainWindow possesses a QTextEdit entitled 'textEdit' and my Dialog has a QPushButton named 'clickOk'
My concern is : I want when I click on that QPushButton of my Dialog that he clears everything I wrote in the textEdit using 'clear()' method of QTextEdit.
Of course I use signal and slot but it's not working, I mean when I click on QPushButton nothing occurs in the textEdit of my MainWindow.
by the way, I use modeless to show my Dialog using 'show()' method and it's works perfectly:
this is the code
QDialog *dlg = new QDialog(this); dlg->show();
I don't want to use modal with '.exec()' function as I want the user to still use both at the same time.
Below's my implementation for everything (the two Forms) :
IMPLEMENTATION
MainWindow.h
public slots: void clearText();
MainWindow.cpp
void MainWindow::clearText() { ui->textEdit->clear(); //QMessageBox::information (this, "TITLE", "WORKING = OK"); }
Dialog.h
Private or Pulic slots: // even if I put it in public or private, it still doesn't work void clearClick();
Dialog.cpp
//in the constructor connect(ui->clickOk, SIGNAL(clicked()), this, SLOT(clearClick()));
void QDialog::clearClick() { // I tried both methods below but nothing seems to happen // First Method QMainWindow dlg; dlg.clearText(); // Second Method QMainWindow *dlg = new QMainWindow(); dlg->cleanText(); }
PS : I tried to test if my ' void MainWindow::clearText() ' of the MainWindow works by inserting a QMessageBox in it,
when I click on QPushButton of the QDialog, and of course it really goes through that function, because the QMessageBox appears when I execute the project... but 'ui->textEdit->clear();' doesn't work.
Thanks for your help in advance
- mrjj Qt Champions 2016
Hi
The code is a bit confusing.
You do
QMainWindow dlg;
dlg.clearText();
which is a new copy of mainwindow so it wont contain the text you except.
I made a small example of how you can do it
In words its the following:
In Dialog we make new public signal ClearClicked
We connect (in dialog) the button's "clicked" signal to our new signal ClearClicked
(since we can't connect directly to button from mainwindow)
Then in mainwindow we connect this new signal ClearClicked to a function
in mainwindow (ClearText ) that clears the text.
.
My second way to do that was this below : "I forgot to paste the code in my first post"
// Second Method QMainWindow *dlg = new QMainWindow(); dlg->cleanText();
Thanks for your prompt reply.
I'm taking a look at the project your gave me, and I'll get back to you for more question.
- ValentinMichelet
As a rule of thumb, I recommend you to make connections from the parent widget, who is aware of it's children since children are often created from parent widget. This is what mrjj coded:
- the main window creates the dialog;
- the dialog can emit a signal when its button is pushed;
- the main window connects this signal to a custom slot;
- the slot does the clear.
You were trying the reverse way.
Moreover, creating connections from the parent widget enables you to make two children communicate between them, without having to know each other.
Sorry for the delay, I was writing my CCNP Exam.
@"mrjj"
you said “(since we can't connect directly to button from mainwindow)”
So if i understand very well, you mean, in all my Qt applications that I will develop that possess more than one Form, objects of the UI like Label, Button, TextBox... in the Main Window ARE NOT DIRECTLY accessible from an another dialog,
so I must ALWAYS create a signal to do so.
I've also read something like that in two Qt books I have but I needed a very clear clarification like that.
You know what, I really like your explanation on the post as well as in the source code your sent me,
it’s very very clear to newbie.
I hope you’ll be (you're) a very good teacher.
and I like the way you give source-code as an example instead of saying a lot of theories like some people else in other Qt Forum.
So if i understand the signal according to your project,
a signal is a empty function??
because I did not see any implementation of the signal “ClearClicked” in mydialog.cpp, you just defined/declared it in mydialog.h.
so basically, a signal is like a empty method?
Thanks very much for you help.
Thanks as well to ValentinMichelet for your explanation.
PS : Please I know that the matter is solved but you can keep posting comments and explanations if you have, I'll read and reply as well.
Have a wonderful week-end!
- mrjj Qt Champions 2016
@freesix
Hi welcome back
When you design a form or dialog. The objects you insert in the editor
are put it a special UI object.
For mainwindow its
#include "ui_mainwindow.h"
This is auto created by the editor and is basically just a normal c++ object containing
all the widgets you put in the UI form.
class Ui_MainWindow {
public:
QPushButton *btRec;
QPushButton *btSend;
QMenuBar *menuBar;
...
In the mainwindow class is then a variable of that Ui_MainWindow type
private:
Ui::MainWindow *ui;
This allows us to say ui->btSend (or any other widget) in all methods of mainwindow.
However, since ui is private, no other class can access the widgets directly.
(like btSend).
This is the reason I say we cannot direct access another forms or dialogs ui's widgets.
It is possible to allow access by make access functions in the owning class
like
QPushButton * MainWindow::GiveMeSendButton() { return ui->btSend; }
But we don't like to do it as it makes rest of program aware of we have such button.
(and if we then make it a spinbutton, we need to change other forms too as they knew exact type)
so we use the signal trick so rest of program don't know the exact widget. (called encapsulation)
a signal is a empty function??
Yes. it is just a normal function but we never define a body for it.
Only the name and parameters are important. (the signature of the signal)
You will not always use the signal approach. You can also make concrete access function for others to use.
Say you have a dialog where user inputs a Delay. (it stays open)
Then if say mainwindow wants to read it at some point.
You define a GetDelay () function in the dialog that mainwin just uses.
this is instead of allowing mainwin to do like
Dialog->ui->Edit->getText() , getting the value directly off the widget.
Instead we define methods to let others get the data without knowing how we really do it (inside)
Hope it makes sense :)
Super nice weekend to you too
Thanks, I do appreciate your explanation.
Hello,
in the source code, there is a public signal (according to you)
but I don't see anything that put that 'signal' public or private.
Can you explain it for me please???
- mrjj Qt Champions 2016
Hi
well it lists it as a slot
signals:
void ClearClicked();
its listed in the public section.
class MyDialog : public QDialog{
public:
signals:
void ClearClicked();
Meaning it can be seens from outside class.
Public also in the sense that it is used to re-signal
a signal from inside the dialog as mainwindow
dont have directly access to the UI widgets to set it directly.
connect(Dia, SIGNAL(ClearClicked()), this , SLOT(clearText()));
Okay thanks | https://forum.qt.io/topic/61728/how-to-access-methods-of-mainwindow-from-dialog-form-subclassing-i-guess | CC-MAIN-2018-05 | refinedweb | 1,271 | 61.06 |
Hello..
I have downloaded Monogame for Mac, then open Visual Studio 2017 (Mac) and then added the Monogame:
extension -> gallery -> game development -> MonoGame Extension
Once it was finished installing, I have restarted Visual Studio, then added a new MonoGame project (Mac), but got an error about a Throw exception.
Tried to do another project but this time for windows and no throw exception was showed but editor does not recognizes Xna namespace from Microsoft. Do I need to install anything else?
Thanks.
After deleting and re-installing Visual Studio, it worked for the Mac project ! (Monogame Mac application)
But the XNA namespace is still missing when I choose to create a Monogame Windows application, maybe I need a Mac to develop for Mac and a Windows machine to develop for Windows builds? | http://community.monogame.net/t/monogame-on-mac-question/10671/2 | CC-MAIN-2019-22 | refinedweb | 132 | 61.8 |
socket − Linux socket interface
#include <sys/socket.h>
sockfd = socket(int socket_family, int socket_type, int protocol);
This manual page describes the Linux networking socket layer user interface. The BSD compatible sockets are the uniform interface between the user process and the network protocol stacks in the kernel. The protocol modules are grouped into protocol families like AF_INET, AF_IPX, AF-only. −1 −1).
SO_BINDTODEVICE was introduced in Linux 2.0.30. SO_PASSCRED is new in Linux 2.2. The /proc interfaces was introduced in Linux 2.2. SO_RCVTIMEO and SO_SNDTIMEO are supported since Linux 2.3.41. Earlier, timeouts were fixed to a protocol-specific setting, and could not be read or written.
Linux assumes that half of the send/receive buffer is used for internal kernel structures; thus the values in the corresponding /proc files are twice what can be observed on the wire.
Linux will only allow port reuse.
The CONFIG_FILTER socket options SO_ATTACH_FILTER and SO_DETACH_FILTER are not documented. The suggested interface to use them is via the libpcap library.
getsockopt(2),/. | http://man.linuxtool.net/centos7/u3/man/7_socket.html | CC-MAIN-2019-35 | refinedweb | 173 | 50.53 |
Hey!!
I having an sim900 GPRS shield and having some issue with it. I communicate with it by SoftwareSerial. When I use my phone to call the sim900, it serial print “RING”, I want to use that to something. For example to turn on an LED when the sim900 is ringing. I have read the topics about serial.readString but can’t get it to work. Here is my code that I have used:
#include <SoftwareSerial.h> SoftwareSerial sim900(2, 3); String simRead; int led = 14; void setup() { // put your setup code here, to run once: sim900.begin(19200); Serial.begin(19200); pinMode(led,OUTPUT); } void loop() { if (sim900.available() > 0){ simRead = sim900.readString(); if (simRead == "RING"){ digitalWrite(led,HIGH); delay(500); } } }
Please help!
Thanks!
-HansDia | https://forum.arduino.cc/t/help-with-softwareserial-read-string/474315 | CC-MAIN-2022-27 | refinedweb | 126 | 69.68 |
an interactive course on Educative.io!
"Redux Fundamentals" workshop in New York City on April 19-20. Tickets still available!
Practical Redux, Part 3: Project Planning and Setup
This is a post in the Practical Redux series.
Initial steps for our sample application
Table of Contents
- Planning the Sample Application
- UI Mockups
- Project Setup and Configuration
- Final Thoughts
- Further Information
Planning The Sample Application
As I mentioned in the series introduction, I've got a number of specific techniques and concepts that I'd like to talk about. I've had several requests to show some actual working examples of these techniques, so I've decided to try to build a small example application to demonstrate these ideas in a meaningful context.
I'm a big fan of the Battletech game universe, a game about big stompy robots with weapons that are used to fight wars a thousand years in the future. The game universe includes miniatures tabletop games, computer games, roleplaying games, fiction, and more.
There's a number of fan-built projects based in the Battletech universe. One of the most popular is Megamek, a cross-platform computer implementation of the Classic Battletech tabletop game. In addition, the Megamek authors have built a tool called MekHQ, a tool for managing an ongoing campaign for a fictional combat organization, such as a mercenary unit.
For this blog series, I'm planning to build a miniature version of the MekHQ application. I definitely do not intend to seriously rebuild all of MekHQ's functionality, but it should serve as a useful inspiration and justification for most of the techniques I want to show off.
On a related note: I'm absolutely making this up as I go along :) I've got some definite ideas for what I want to show off, but I'll be developing this sample app as I work on each post. That means I'll probably make some mistakes, need to change things, and iterate on the code. This will be a learning experience for everyone involved :)
Every project needs a good name. I haven't come up with a good name yet, so we'll call this "Project Mini-Mek" for now. (If anyone comes up with a better name, I'm listening!)
Project Features
MekHQ is a very complex and in-depth application. The "About" page describes it this way:
For Project Mini-Mek, we're only going to deal with a couple of these, and at a very simple level. Here's a tentative list of features:
- Load JSON data describing the pilots and Battlemechs in a combat force
- For both pilots and Battlemechs:
- Show a list of all items
- Allow selection of an item in the list, and show details of the selected item
- Edit the details for a pilot
- Organize the pilots and their mechs into "lances" of four mechs, and the "lances" into a "company" of three lances.
- Add and remove pilots and mechs from the force
- Save the force back out to JSON
So, basically Yet Another CRUD APP, with some specific themes :) For now, I'm not planning to deal with a backend or any AJAX handling. I figure I'll start with static JSON being directly imported, and then maybe add file import/export later on.
UI Mockups
MekHQ: Pilot Listing
Let's start by looking at some screenshots of the original MekHQ UI. First, here's the screen that shows the list of pilots, and the details for the currently selected pilot:
MekHQ: Unit Table of Organization Tree
Next, the "Unit Table of Organization" section, showing the various sub-units in a tree structure, and again with a details section on the right:
This gives us a general idea of the UI layout we want: a tab bar across the top, with most of the tab panes containing a list of some kind on the left, and a details box for the currently selected item on the right.
Here's some rough mockups of what our UI might look like:
Project Mini-Mek: Unit Info
Project Mini-Mek: Pilot Listing
Project Mini-Mek: Mech Listing
Project Mini-Mek: Unit Table of Organization Tree
Project Setup and Configuration
We're going to set up the project using the excellent Create-React-App tool. I'm also going to be using the new Yarn package manager, partly because it's supposed to be faster, and partly because this gives me a chance to try it out. Also, as an FYI, I'm writing all this on Windows, but I don't expect any meaningful OS/platform issues to pop up as we go. Finally, I don't necessarily intend to show every last command I've typed or bit of code I've written as we go on - the real focus is intended to be on using Redux itself, not using Git or an editor.
The project is available on Github, at. I plan on updating it as I publish each post, and hope to show both some of the nitty-gritty "WIP" commits as well as cleaner "final result" commits. Also, when I show code snippets or refer to source files in the repo, I'll usually try to link to that file on Github at the specific version where the changes were made.
All right, let's do this!
Creating the Project
Follow the instructions for installing the
create-react-app and
yarn tools on your system. Once that's done, we can create our project:
create-react-app project-minimek
This is a good time to initialize a Git repo for the initial sample files and project config files. After the project is created, we want to set up a Yarn lockfile to nail down the specific dependency versions we're using.
create-react-app already installed everything it needs (using NPM, although Yarn support is planned), but we need to run
yarn to make sure we're ready for adding more dependencies:
cd project-minimek yarn
There's a bunch more file work done as Yarn figures out what dependencies you have, and prepares its lockfile,
yarn.lock. That should be committed to Git as well.
Dependencies
Time to pull in our initial list of dependencies. Here's what we're going to add:
- Redux: because without it, this would be a really short blog series
- React-Redux: ditto
- Redux-Thunk: the most common and simple addon for side effects and complex dispatching logic
- Reselect: needed for memoized "selector" functions when retrieving data from our state
- Redux-ORM: a handy abstraction layer for managing relational data in our state
- Lodash: every useful function you can think of, and a bunch more you didn't even know existed
- cuid: We'll probably be generating IDs at some point, so this will fill that need
We can add them all in at once:
yarn add redux react-redux redux-thunk reselect redux-orm lodash cuid
And then commit our
package.json and
yarn.lock again.
Initial Redux Configuration
We need to set up the initial Redux store and reducers, make the store available to our component tree, and make sure that it's being used. Here's what my initial Redux configuration looks like:
store/configureStore.js
import {createStore, applyMiddleware, compose} from "redux";(...storeEnhancers); const store = createStore( rootReducer, preloadedState, composedEnhancer ); return store; }
I like to keep my store setup logic in a
configureStore function that can be further improved as time goes on. I also try to keep the setup for each piece of the configuration process separate, so it's easy to follow what's going on.
reducers/testReducer.js
const initialState = { data : 42 }; export default function testReducer(state = initialState, action) { return state; }
reducers/rootReducer.js
import {combineReducers} from "redux"; import testReducer from "./testReducer"; const rootReducer = combineReducers({ test : testReducer, }); export default rootReducer;
Our initial reducers just pass along some test data so we can verify things are working.
We then create a store instance and use it in the rendering process:
index.js
import React from 'react'; import ReactDOM from 'react-dom'; import {Provider} from "react-redux"; import App from './App'; import './index.css'; import configureStore from "./store/configureStore"; const store = configureStore(); ReactDOM.render( <Provider store={store}> <App /> </Provider>, document.getElementById('root') );
Finally, we add a simple test component, connect it to Redux, and render it in our App component to verify that everything's hooked up properly:
SampleComponent.jsx
import React, {Component} from "react"; import {connect} from "react-redux"; const mapState = state => ({ data : state.test.data }); class SampleComponent extends Component { render() { const {data} = this.props; return ( <div> Data from Redux: {data} </div> ); } } export default connect(mapState)(SampleComponent);
App.js
import React, { Component } from 'react'; import logo from './logo.svg'; import './App.css'; import SampleComponent from "./SampleComponent"; class App extends Component { render() { return ( <div className="App"> <div className="App-header"> <img src={logo} <h2>Project Mini-Mek</h2> </div> <SampleComponent /> </div> ); } } export default App;
We should now see the text "Data from Redux: 42" in our page, right below the header bar.
Adding the Redux DevTools Extension
One of the original reasons for Redux's creation was the goal of "time-travel debugging": the ability to see the list of dispatched actions, view the contents of an action, see what parts of the state were changed after the action was dispatched, view the overall application state after that dispatch, and step back and forth between dispatched actions. Dan Abramov wrote the original Redux DevTools toolset, which showed that information with the UI as a component within the page.
Since then, Mihail Diordiev has built the Redux DevTools Extension, a browser extension that bundles together the core Redux DevTools logic and several community-built data visualizers as a browser extension, and adds a bunch of useful functionality on top of that. Connecting the DevTools Extension to your store requires a few extra checks, so there's now a package available that encapsulates the process needed to hook up the DevTools Extension to your store.
We'll add the helper package with
yarn add redux-devtools-extension, then make a couple small changes to the store setup logic:
store/configureStore.js
- import {createStore, applyMiddleware, compose} from "redux"; + import {createStore, applyMiddleware} from "redux"; + import { composeWithDevTools } from 'redux-devtools-extension/developmentOnly'; - const composedEnhancer = compose(...storeEnhancers); + const composedEnhancer = composeWithDevTools(...storeEnhancers);
This should add the DevTools enhancer to our store, but only when we're in development mode. With that installed, the Redux DevTools browser extension can now view the contents of our store and the history of the dispatched actions.
Component Hot Reloading
Out of the box,
create-react-app will watch your files on disk, and whenever you save changes, it will recompile the application and reload the entire page. That's nice, but we can actually set up some improvements on that. In particular, the Webpack build tool used by
create-react-app supports a feature known as Hot Module Replacement, or HMR, which can hot-swap the newly compiled versions of files into your already-open application. That lets us see our changes faster. This works great with a React app, and even better in combination with Redux, since we can reload our component tree but still keep the same application state as before.
We'll also want to add the
redbox-react package, which we can use to render an error message and a stack trace if something goes wrong. Once that's installed, we need to update
index.js to rework the top-level rendering logic:
index.js
import React from 'react'; import ReactDOM from 'react-dom'; import {Provider} from "react-redux"; import './index.css'; import configureStore from "./store/configureStore"; const store = configureStore(); // Save a reference to the root element for reuse const rootEl = document.getElementById("root"); // Create a reusable render method that we can call more than once let render = () => { // Dynamically import our main App component, and render it const App = require("./App").default; ReactDOM.render( <Provider store={store}> <App /> </Provider>, rootEl ); };); } }; // Whenever the App component file or one of its dependencies // is changed, re-import the updated component and re-render it module.hot.accept("./App", () => { setTimeout(render); }); } render();
With this in place, editing one of our components (such as changing the text in
SampleComponent.jsx) should now just reload the component tree, rather than reloading the entire page. If there's an error, we should see it displayed on the screen and logged in the console. (To try it out, you can add
throw new Error("Oops!") to
SampleComponent.render() and see what happens.)
Reducer Hot Reloading
Finally, we can also configure our project to hot-reload our reducers as well. Right now, if we edit the initial state in our
testReducer.js from
data : 42 to
data : 123, we'll see the whole page reload, just like it did for component edits before we added the hot reloading. We need to listen for updates to the root reducer file, re-import it, and then replace the old reducer in the store with the new one. The updated
configureStore.js looks like this:
store/configureStore.js
import {createStore, applyMiddleware} from "redux"; import { composeWithDevTools } from 'redux-devtools-extension/developmentOnly';WithDevTools(...storeEnhancers); const store = createStore( rootReducer, preloadedState, composedEnhancer ); if(process.env.NODE_ENV !== "production") { if(module.hot) { module.hot.accept("../reducers/rootReducer", () =>{ const newRootReducer = require("../reducers/rootReducer").default; store.replaceReducer(newRootReducer) }); } } return store; }
Final Thoughts
At this point, we know what kind of app we want to build, and have a decent idea what it should do and what it should look like (or at least enough of an idea to get us started). We also have an initial project set up with our basic dependencies, and some nice tweaks to the development workflow.
Next time, we'll at setting up some initial UI layout, and possibly tackle some of the initial data modeling as well.
If you've got questions, comments, or suggestions, please let me know! Leave me a comment here, file an issue in the repo, or ping me on Twitter or Reactiflux.
Further Information
- Project Mini-Mek repo
- Create-React-App home
- Time travel debugging:
- Webpack Hot Module Replacement info | http://blog.isquaredsoftware.com/2016/11/practical-redux-part-3-project-planning-and-setup/ | CC-MAIN-2018-17 | refinedweb | 2,359 | 50.16 |
{
Steve posted a coding challenge a few days ago - a change dispenser. I thought it would be a nice exercise for my fledgling Python skills and implemented it with just a small variation on pluralizing coin denominations.
def make_change(amt):
output = "Change is "
coins = (['quarte|r|rs', 25], ['dim|e|es', 10], ['nicke|l|ls', 5], ['penn|y|ies',1])
for i in coins:
r = amt // i[1]
if(r > 0):
coinout = re.split('\|', i[0])
output += "%d %s%s " % (r, coinout[0], coinout[1:][r > 1])
amt = amt - (r * i[1])
print output
make_change(48)
A few things I learned along the way:
* I was reminded that dictionary objects do not guarantee order.
* I was using Python regular expressions to do a match on the string "this |and|or that" and discovered if you use match with simply \|(\w+) it returns nothing since the match must start from the beginning of the string!
* I was going to use a lambda expression for the pluralization but that's such a large hammer for what in the end would become a split
Python's behavior with booleans is another point of interest - when I test the following: coinout[1:][r > 1] I'm taking advantage of anything true being a 1. I wonder if this is "bad" but it's a seductive thing to take advantage of... | http://metadeveloper.blogspot.com/2008_06_01_archive.html | CC-MAIN-2018-22 | refinedweb | 226 | 59.57 |
This page discusses - Introduction to Dojo and Tips
AdsTutorials. It is an Open Source JavaScript toolkit that provides a simple the Application Programming Interface for building the serious applications in less time. The functionality of Dojo to make HTTP requests and receives dynamic interfaces.The amount of functionality available in dojo, a few architectural differences compared to most other frameworks; it uses a late of function. That dojo Script always includes the package names in an object reference. IT is very nice for-each loop function, for instance, I have to refer this as {dojo.lang.forEach(listOfThings, myFunc);} instead of just {forEach(listOfThings, myFunc);}. Dojo increases readability when the debugging or the refastening things later. If you want to refer to a DOM element "dojo way", you write "dojo.byNa;" Another big change in the philosophy between the dojo and the prototype is that prototype long and glorious history of changing initial javascript objects, like that adding useful new functions to the string object. The Dojo provide resulted in the collisions on other the erratic behavior if using other JavaScript libraries for programming, If you want change or assume at functionality of the very same the function names. To using the namespaces, the dojo ensures that no the collisions occur between itself and any other JavaScript libraries on the same page. I'm going to use the dojo Application Programming Interface.
Posted on: April 18, 2011 If you enjoyed this post then why not add us on Google+? Add us to your Circles
Advertisements
Ads
Ads
Discuss: Introduction to Dojo and Tips
Post your Comment | http://roseindia.net/dojo/dojoHelloWorld/js/dojo/dojo-tips.shtml | CC-MAIN-2018-09 | refinedweb | 266 | 54.02 |
hi
i'm trying to set this up dead simply in a lab.
i just want to see my tiny 8GB newly created VMGuest failover from one host to the other.
vcenter 6.7 uj, latest version.
3 virtual nodes. running esxi.
2 as nodes (1x50gb cache vmdk, 1x200gb capacity vmdk) identical. 2 NICs. 1x1GbE (management). 1x10GbE (configured for vsan).
1 as witness node.
i've enabled vSphere HA. i've enabled DRS.
all enabled OK as a vsandatastore. which i can browse through vCEnter.
i can copy files manually to the vsandatastore.
i've uploaded a virtual guest (windows server 2012 r2, evaluation mode, brand new. put a few folders on the desktop for fun). from vmworkstation. just dragged it across to the vcenter's datacenter and into the cluster, selecting the vsandatastore as the destination disk.
(what worried me is the 10GbE network wasn't going crazy when i copied this to one node. i've looked at s2d from Microsoft before now and it instantly starts synchronising to the 2nd node.)
i've run the vguest on Node1. happy days. i'm pinging the guest from a 4th machine.
disconnect the network cables on node1. to simulate a power cut on one node (or a motherboard failure - bang!)
uh oh!! no pinging. wait. wait. wait.
i'm clicking around. looking for an alert. i can still get the vcenter interface up and i look in there of course.
"lost communication with node 1"
"insufficient vsphere ha failover resources "
they're identical nodes. i can't click on the VMguest and click migrate. i can't click play. the vsandatastore is empty.
i just want this to be easy and work as expected in the theory books.... to see this working in practice and then i can decide if its to be good enough for production.
any advice, or links to youtube. for a practical implementation to see all the features working. would be appreciated. otherwise i've lost 10 hours of my life.
thanks very much
🙂
ive been into policies -> vm storage policies -> vsan default storage policy
looking in the storage compatibility, and mine doesnt appear there. not sure if it should or not??
if i tick force provisioning, on the previous advanced policy rules step, then it does show up.
does it need more 200GB hard disks adding? does it like to have 4 or 5
ive just forced the provision through. the 10GbE card went crazy for a bit. which looks promising.
ive again disconnected the node2 from the network. (both NICs) to simulate a mainboard failure. bang!
but same again.
i cant even drag the VMGuest to the Node1 (through vCenter). it pops up with Move To: this action is not available....
vSanDataStore is now has a folder named Windows Server 2012. but thats empty.
not good!
Hello Matt,
Welcome to Communities and vSAN.
"uh oh!! no pinging. wait. wait. wait."
So, firstly even if HA and vSAN are properly configured this is expected behaviour - HA is not capable of magically migrating a VM off a dead/isolated node and thus what it does is determine that this has happened and restart the VM on a remaining node (providing the data is sufficiently available), note that this is not instantaneous, for zero-downtime failover you would configure FT VMs or some form of in-VM clustering/redundancy/load-balancing.
"i can't click play. the vsandatastore is empty."
What this means is that the data (including the namespace Objects AKA VM folders) are inaccessible - this could be either due to them being provisioned as FTT=0 Objects which have no redundancy (and you just lost either the whole or part of the only copy) or there is some other issue with the cluster (e.g. remaining node was no longer clustered with the Witness).
"ive been into policies -> vm storage policies -> vsan default storage policy
looking in the storage compatibility, and mine doesnt appear there. not sure if it should or not??"
This means that the cluster in the current state is not capable of provisioning data with the Storage Policy (SP) rules chosen - e.g. if you only have 2-nodes available (e.g. 1 data-node + Witness) then you can't use an SP that requires a minimum of 3 nodes for component placement (e.g. the Default SP rules).
"if i tick force provisioning, on the previous advanced policy rules step, then it does show up."
Yes, but that's because Force Provisioning means it will make FTT=0 data if FTT=1 data creation is not possible - this means you don't have 3 nodes with available storage/clustered properly here.
"i cant even drag the VMGuest to the Node1 (through vCenter). it pops up with Move To: this action is not available...."
As I said above...how exactly would you expect vCenter to move/migrate a VM from a ESXi host it is not currently connected to? Secondly (if you had this configured correctly, which it looks like you don't) even if it was connected back to vC (but not vSAN) the VM would be dead/crashed as its Objects (e.g. vmdks) would be inaccessible from this host as they would have lost quorum.
What Storage Policy (SP) did you apply to your test VM? If none then assign an SP with the storage rules you want applied to your data (e.g. right-click VM, Edit Storage Policy, select an SP and apply).
So, step 1 here should be to put your cluster back together and validate that you can make FTT=1 FTM=RAID1 Objects - if you cannot then this is the problem from the start, this can easily be validated via:
Cluster > Monitor vSAN > Proactive tests > Proactive VM creation Test > Run
However, note that the above test uses the SP assigned as default to the vsanDatastore so if you have been messing with that (e.g. adding Force Provisioning = true) then undo these changes or make a new standard FTT=1,FTM=RAID1 SP.
If the above test fails it should tell you why e.g. need 3 Fault Domains (e.g. nodes) but found only 2 (e.g. if you didn't configure disks for the Witness or a node is isolated or has disks offline/unusable).
More information relating to the state of the cluster can be checked at:
Cluster > Monitor > vSAN > Health > retest
Bob | https://communities.vmware.com/t5/VMware-vSAN-Discussions/vSAN-vSphereHA/m-p/2301434 | CC-MAIN-2022-40 | refinedweb | 1,073 | 75.1 |
I need to be able to encrypt data in PHP using a public key generate by .NET(RSACryptoServiceProvider).ÃÂ I will then decrypt the data later in C# using the private key.
ÃÂ
View Complete Post
i am using belowcode in web.config
<loggingConfiguration name="" tracingEnabled="true" defaultCategory="General"> <listeners> <add name==".\Logs\jeejix_error.log" footer="------------Error End----------------------------" formatter="Text Formatter" header="---------Error Start-------------------------------" rollFileExistsBehavior="Increment" rollInterval="Day" rollSizeKB="50" /> </listeners> <formatters> <add type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken i export a MS Excel file generated By SSRS 2008 i'm not able to change the sheet name (Sheet 1,Sheet 2,Sheet 3) dyanamically.Sp Please try to give me a solution. ?
Hello:
Last Friday, I installed Windows Sharepoint Services 3.0 (WSS) on Windows Server 2008. This morning (Monday), I noticed that the C drive has only 502 KB of free space. I went through the C drive and found a 15 GB log file in the following directory:
C:\Program Files\Common Files\microsoft shared\Web Server Extensions\12\LOGS
This, apparently, got created at 7:44PM last Friday night somehow. I, just now, deleted it as it was too big to open in Notepad. The server now has 14.2 GB of free space on the C drive.
Since the C drive is only a 30GB drive, we can't afford for log files of this size to get created again.
I checked Event Viewer and there were no events leading to a cause for this.
Does anyone know why this would have happened? Is there a way of preventing this from happening, again? Is there a way of automatically purging these log files?
In light of this, the client would like for the Temp, tmp, and all log file locations moved off of the C drive and onto the D drive. Is there a way to do so without uninstalling and reinstalling WSS onto the D drive?
Are there really any issues (aside from log file creation!) with installing Windows Sharepoint Service onto the C drive?
childofthe1980s
I
Hi Everyone,
Is there a way to encrypt a file at the client level before it is uploaded to a server? (and decrypt it when it comes back from the server).
I realize there are server apps for this as well but my host doesn't offer it in it's shared hosting plans.
Thanks,.
So one of my views refuses to display, instead throwing up an error about an unreferenced assembly in a generated code file.
Here's the controller action:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using CindySanabria.Domain;
using System.Diagnostics;
namespace CindySanabria.Controllers
{
public class ProfileController : Controller
{
private IMembersRepository _membersRepo;
public ProfileController(IMembersRepository repo)
{
Debug.WriteLine("Constructing ProfileController");
this._membersRepo = repo;
}
//
// GET: /Profile/Create
[Authorize]
public ActionResult Create()
{
Debug.WriteLine("Running Create action");
return View();
}
}
}
And here's the view:
<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<CindySanabria.Domain.Member>" %>
<asp:Content
Create Profile
</asp:Content>
<asp:Content ID="Content2" ContentPla
How to sign a dynamically generated PDF file?
Using Itextsharp .
Without external certificate, can we sign a document?
Request your speedy response
Hall of Fame Twitter Terms of Service Privacy Policy Contact Us Archives Tell A Friend | http://www.dotnetspark.com/links/64872-how-can-i-use-key-file-generated-by-rsacryptoserviceprovider.aspx | CC-MAIN-2017-13 | refinedweb | 568 | 51.24 |
User talk:Cronolio
Wiki maintenance
For the job well done maintaining multiple articles you receive this cool red trophy and a high five from Larry the cow! Thanks for all your hard work in translating to Russian as well! --Maffblaster (talk) 22:43, 9 November 2016 (UTC)
Bypassing a redirect
What was your thinking in this edit? Was it was related to translation? Because I don't think there is any good reason to replace a simple link to a redirect page by a more complicated link to a section within an article. - dcljr (talk) 03:46, 24 February 2017 (UTC)
- Yes. Redirect is work only for english articles and always when it possible i write link to translated version of article. Like {{c|[[Gentoolkit#euse|euse]]}} >> {{c|[[Gentoolkit/ru#euse|euse]]}}. If you know how to have previous selected language on next page, let me known. --Cronolio (talk) 10:40, 24 February 2017 (UTC)
Would it not be preferable to create "translated" redirects in such cases, e.g., euse/ru containing
#REDIRECT [[Gentoolkit/ru#euse]]? That way the translations could benefit from redirects the same way the English versions do. Is there a technical reason this would not work? BTW, in this edit you still have a link to the English euse. - dcljr (talk) 06:43, 25 February 2017 (UTC)
Two main reasons:
- Convenience, since it's much easier to link to euse (or euse/ru, etc.) when it is first mentioned in an article rather than having to remember (or search and find out) that it's covered in the Gentoolkit (Gentoolkit/ru, etc.) article.
- At some point in the future, we may want to have a standalone article for euse, in which case none of the extisting [[euse]] links would have to be changed.
There may be other reasons I haven't thought of. - dcljr (talk) 03:01, 26 February 2017 (UTC)
- For 1st reason: in rendered version the name is
euse(as it see reader) because i am wrote [[Gentoolkit#euse|euse]].
- Another no good reason: no good idea to write in
*article*/ru (any language code)because it is reserved for translation. So what happening if in the future we will have euse article (for translation too) and someone forget about this euse/ru redirect?
- Ok i just done what you asking me for. But by me this no liked (imho). Sorry if... --Cronolio (talk) 09:22, 26 February 2017 (UTC)
What I meant in #1 was: as a wiki editor, it is much easier to add links to [[euse]] where they are needed rather than having to remember to use [[Gentoolkit#euse|euse]]. Obviously to readers the links look the same. (But that's my point: It's easier for editors and makes no difference to readers.) As for #2, if euse ever gets created as an article needing translation, we would simply delete any existing euse/xx redirects and use the translation extension in the normal way. Are you saying that the existence of redirects called euse and euse/ru will cause problems (now) for translators? How? (I am not a translator, so I don't know much about it.) Isn't the change you made here exactly how you would translate that part of the "Fontconfig" article if euse was a regular article and not a redirect? Why should it be different because it's a redirect? I still don't understand why you don't like using a redirect in this way… - dcljr (talk) 10:29, 26 February 2017 (UTC)
- I done this edit and create this page with redirect because you ask me for this. With reason as some search entry point (as i understand).
- I think the redirect is a tool for the lazy editors 😀 My total reasons here:
- Infrastructure side: i think i save some number of HTTP request/answer for gentoo servers and for reader www-client also. For redirect is work required extra HTTP request/answer.
- "Cat in box" and end point of url: if i good reader and i see
eusein url i like to see
Eusearticle. If not, it seems to me that I was deceived 😞 "Cat in box" mean the reader never knows what awaits him at the end of. Search for "Schrödinger's cat" on wikipedia also 😉
- Translation side and probably main for me: if translator like I am care about national relinking of articles, which under translation. Like link from
foo/xxto
moo/xx. This translators does the translation for
moolike
moo/xx. With redirect from
mooto
booarticle by your "redirect way" it is looks like each translator should create a ton
moo/xxpages with redirect to
boo/xx(sorry for my english. try to understand it)
So if i will edit
fooarticle and fix link
moowith
boo(that will work without redirect) i do all the work of other translators, and for myself too. It's much easier way. --Cronolio (talk) 12:38, 26 February 2017 (UTC)
- Looks like mediawiki do it via Special:MyLanguage. Example
[[Special:MyLanguage/Help:Extension:Translate/Off-line translation|<translate><!--T:49--> Off-line translation</translate>]]. There is also seen a completely different approach to marking for translation. --Cronolio (talk) 18:55, 26 February 2017 (UTC)
OK, let's consider each of these points:
- This, I believe, is a complete non-issue. The additional server load of redirects is surely negligible.
- Whether your link is to [[euse]] or [[Gentoolkit#euse|euse]], the reader still sees euse and ends up at euse. There is absolutely no difference to readers.
- Each translator would create a single [[moo/xx]] redirect for the language they are translating into. (So you just "do the work of" yourself.) This would have to be understood by translators, of course. So I guess my question now is: in the current situation, if a translator comes across a link to [[moo]] in the original article, how do they know whether to link to [[moo/xx]] or just keep it [[moo]] (in the case where moo has not been translated to language xx yet)? Does the translate extension tell them?
As for the Special:MyLanguage feature, I know about that, but I don't think I've seen it used in articles (in the main namespace) around here very much. I'd have to think about that.... - dcljr (talk) 19:58, 26 February 2017 (UTC)
- Sometime it slowly work on my desktop. What happening on mobile device i don't know.
- I mean if reader move the cursor at url and see what in url.
- All in manual mode my friend. I check each link in article.
- You can ask maffblaster for translation privileges. --Cronolio (talk) 20:51, 26 February 2017 (UTC)
Would you mind if I asked other users about this and directed them to this talk page? I'd like to get some other opinions on this... - dcljr (talk) 23:41, 26 February 2017 (UTC)
I've done it. - dcljr (talk) 10:02, 1 March 2017 (UTC) | https://wiki.gentoo.org/wiki/User_talk:Cronolio | CC-MAIN-2017-13 | refinedweb | 1,164 | 72.26 |
Announcements
November GameDev Challenge: Pong! 11/01/17
JbsMembers
Content count201
Joined
Last visited
Community Reputation274 Neutral
About Jbs
- RankMember
rotating texture coordinates for rectangular quad
Jbs replied to Funcdoobiest's topic in Graphics and GPU ProgrammingIs rotating the actual quads not allowed? It seems like you could just do that instead of rotating the uvs. If that isn't going to work, you could use a 2D rotation texture matrix that is setup for the angle of rotation. Something like: 2x4 [ cosAng, -sinAng, 0.0f, 0.0f ] [ sinAng, cosAng, 0.0f, 0.0f ]
OpenGL "throwing away" specific mip map levels?
Jbs replied to coderchris's topic in Graphics and GPU ProgrammingOne thing you might want to investigate is adding a mipmap bias to that texture to sort of modify the mipping calculations. In essence, when the texel-to-pixel ratio is calculated to determine the mip level, you can apply a certain adjustment to the value which will affect the final level which is used. You might be able to set the bias such that it always picks your nth level. OpenGL Reference DirectX References
shufpd
Jbs replied to xinsan's topic in General and Gameplay Programming[google] First Result
adding arrays
Jbs replied to eppo's topic in General and Gameplay ProgrammingQuote:Original post by TheGilb Or if you were to change your dynamic arrays into C-style arrays of fixed size: *** Source Snippet Removed *** Even C++ template magic won't be faster than a decent memcpy implementation. Still, remember that the fastest code is the code that isn't written. I believe he wants to place the sum in the destination array, not the copy.
Irrilecht Font Question
Jbs replied to murdock's topic in For BeginnersIt would be much better to ask this in the Irrlicht forums: Linky
dynamic_cast of this
Jbs replied to matt3d's topic in General and Gameplay ProgrammingI do not think anyone has explicitly explained yet why you were receiving a stack overflow, so I'd like to clear that up in case you were still unsure. I'm willing to be that Init() was marked as virtual in some part of the class hierarchy. So, executing void Engine::Init() { Component *Parent = dynamic_cast<Component *>(&this); Parent->Init(); ... } really results in the cpu looking at virtual table of Parent and finding Engine::Init(). So Parent->Init() executes Engine::Init() instead of Component::Init(), which in turn causes an nonterminating loop and thus the stack overflow.
- 1) I'm not sure if this is the problem, but in my experience a black render is either an improperly bound texture or improperly bound texture coordinates. Have you tried boiling the shader down any? For example, first just return the sampled decal map and assure that works. Then, slowly build the shader up to find the breaking point? 2) My mistake, I thought you meant to cache the current and next keyframe on the gpu for interpolation, not the entire animation sequence. I'm not sure that such a large amount of data could be cached (or if you would have any guarantees that it would stay cached during the rendering of other materials.) Also, by doing it in immediate mode you could only cache at most the number of texturing units the hardware supported. If you get this to work and find some big performance wins, I'd love to hear about it.
How to reduce the code size?
Jbs replied to flyfish_bit's topic in General and Gameplay ProgrammingCheck for static memory buffers and constants that must be packed into the executable. Also, if you are using C++, be aware that templated code must be instanced for each type that uses it. In other words, vector<int>, vector<myclassA>, vector<myclassB> all have unique code generated for them in the executable.
- 1) I'm assuming that by "it wont work" you mean the Cg program will not compile. What kind of error string are you getting with the failed compilation? In case you aren't sure how to get the error, (or for the reference of whoever else is reading this thread), you can register an error callback method with Cg that I have found quite helpful in these situations. For example, this is how I do it: bool ShaderFactory::Initialize() { ... // create the context sCgContext = cgCreateContext(); if( !sCgContext ) { Log::LogError( "Failed to create Cg context!" ); return false; } // get a suitable vertex profile sCgVertexProfile = cgGLGetLatestProfile( CG_GL_VERTEX ); if( sCgVertexProfile == CG_PROFILE_UNKNOWN ) { Log::LogError( "Failed to query valid vertex profile!" ); return false; } // get a suitable fragment profile sCgFragmentProfile = cgGLGetLatestProfile(CG_GL_FRAGMENT); if( sCgFragmentProfile == CG_PROFILE_UNKNOWN ) { Log::LogError( "Failed to query valid fragment profile!" ); return false; } // set callback cgSetErrorCallback( CGErrorHandler ); ... return true; } and CGErrorHandler is my callback defined as: #define BREAK_ON_SHADER_ERROR { do { __asm int 3 } while( GetFalseValue()) static void CGErrorHandler() { CGerror err = cgGetError(); const char * errStr = cgGetErrorString(err); const char * errListing = cgGetLastListing( sCgContext ); Log::LogError( "Cg Error!" ); Log::LogError( errStr ); Log::LogError( errListing ); BREAK_ON_SHADER_ERROR; } cgGetErrorString() will give you a fairly vague but sometimes useful error message. cgGetLastListing() will give you the exact compile error reported from cgc. The is usually the most helpful message. BREAK_ON_SHADER_ERROR is just a utility for forcing VisualStudio to insert a breakpoint if the method is called. 2) I don't believe that you can explicitly get access to more than one vertex position attribute within a Cg program. So, it would seem that in order to interpolate between two keyframe positions you are going to have to pack the additional vertex position in somewhere...possibly a texture coordinate unit. Of course this does not have to be done in immediate mode, but sometimes using the gpu to offload cpu workload requires some trickery.
Factory and objects without default constructors
Jbs replied to wild_pointer's topic in General and Gameplay ProgrammingOne quick idea would be to have the Factory class only parse the very top of the xml tree. So, let's say you had the xml: <Entity Name="Player"> <WorldTransform Translation="10, 0, 3"/> <Renderable Effect="Foo.fx" Mesh="Bar.x"/> <Body LinearVelocity="100, 0, 0"/> </Entity> <Entity Name="Trigger"> <WorldTransform Translation="10, 0, 3"/> <AABB Min="0 0 0" Max="10 10 10"> </Entity> The factory would be responsible for parsing only the name of the entity. The factory could then delegate the further parsing of the tree to sub factories which knowledge of the structure of the subtrees. So the factory would have a sub factory for the parsing of "Player"s and "Trigger"s. These sub factories would then be responsible for the instancing of the required sub classes.
Is this a correct way to use boost::shared_ptr?
Jbs replied to sheep19's topic in For Beginnersconst Weapon* const WeaponPack::returnWeapon( const std::string& name ) { for(std::vector< boost::shared_ptr<Weapon>>::iterator iter = m_pWeaponPack.begin(); iter < m_pWeaponPack.end(); ++iter) if((*iter)->GetName() == name) return (*iter).get(); //if the name wasn't found, return a pointer to nothing return NULL; } I would also point out that it is a little awkward to return a raw pointer from this method if the intended usage of the shared_ptr was for reference counting. If a user calls returnWeapon() and caches the returned pointer for longer than the lifetime of the WeaponPack instance, the cached ptr will reference invalid memory. If the intended usage was just ensured destruction inside an stl container, this isn't as big a deal. Just to be clear, here is how the method would look: boost::shared_ptr<Weapon const> WeaponPack::returnWeapon( const std::string& name ) { for(std::vector< boost::shared_ptr<Weapon>>::iterator iter = m_pWeaponPack.begin(); iter < m_pWeaponPack.end(); ++iter) if((*iter)->GetName() == name) return (*iter); //if the name wasn't found, return a pointer to nothing return boost::shared_ptr<Weapon const>(); }
Matrices, normals, lighting and cg
Jbs replied to Damocles's topic in Graphics and GPU ProgrammingQuote:Original post by Damocles Right, where to start... I have a system setup where I can draw one mesh, translate/rotate to a given offset and draw another mesh, translate/offset, draw a third mesh, and so on and so on. Each tertiary mesh inheriting it's parent's rotation/translation. So, I'm not completely sure I understand, but I think what you mean is you are doing a hierarchical transform. In other words, you transform are stacked onto top of each other, as in skeletal systems? I'm going to assume that is the case in my answer. Quote: I also have a cg script which handles vertex blending and vertex lighting. Now, when I send in the first mesh in a series of meshes, the lighting is perfect because the rotation matrix is the same as the world matrix. The problem is when the tertiary meshes go into the script, their normals get screwed up because they are still working as if they were in the world matrix. This messes up the lighting part of the script. My first thought was to multiply the normals by the matrix passed into the script (the same matrix used to multiply the vertexes) and then re-normalize, to get the new normal. This results in no lighting at all on the models - they are pitch black on every poly. So now I'm trying to figure out where the problem lies - I need to figure out how to get the vertex normal into the same matrix space as the vertex. Any ideas? And for reference, the cg script... (yes, it is mostly just the Nvidia examples botched into one script) *** Source Snippet Removed *** Another thing I'm not quite clear about is why you are lerping the normal like this: 'float3 N = lerp(normal, posN, keyFrameBlend);' I'm not very familiar with Cg, but does that say you are blending the normal and the position together? I'm not sure that is what you want to be doing. Instead, you want to transform the normals of your mesh by the current stacked transform. What I think you should do is take your ModelViewProj, which takes your model positions from model to projection space, and multiply your model normals by the inverse transform of this. Note that each time you move up the transform hierarchy you should change your ModelViewProj matrix that is passed into the Cg shader. For information on why normals are transformed in this odd way I googled this: I hope that helps!
US mid-term election
Jbs replied to Samsonite's topic in GDNet LoungeQuote:Original post by DrjonesDW3d ... *Applauds* You are absolutely correct. Show me a person who cares about the issues and stills needs to be reminded to vote and I'll show you a liar.
Train robots to take over the world!
Jbs replied to CyberSlag5k's topic in GDNet LoungeHaha, what a good feeling. I saw your post and thought to myself, "hey, that looks interesting." I get into the post and see that you're talking about the game I made! hooray! I've been working on NERO for 2 years now, and have been the lead engineer for a little over a year. We're glad that it interests you! The build you can get from nerogame.org is a little over a year old, but it is currently the sole topic of a research class at the University of Texas so we expect a new release this December that will include better gameplay elements as well as a plug-in system for different learning methods. Anyway, thanks for the post, you made my day. :P Oh, also, these robots won't be taking over the world. P.S. Which course and university had you write a report about NERO? We're always interested when people show interest in us.
Why is this a function instead of a constant?
Jbs replied to polaris2013's topic in For Beginners[Edit: I take back my answer...seems I was wrong.] I tried compiling the line in question, and didn't seem to have any problems. | https://www.gamedev.net/profile/37503-jbs/ | CC-MAIN-2017-47 | refinedweb | 1,996 | 61.36 |
Created on 2005-04-29 17:36 by boisgerault, last changed 2005-04-29 17:52 by tim.peters. This issue is now closed.
The doctest ELLPSIS marker (default: "...") may be
confused by the doctest parser with the multiline
statement marker ("...").
Example: in the following code, the intent was to accept
any result after "print 42". This is NOT a multiline
statement,
but however the test fails (Expected: nothing, Got: 42).
----------------------------------------
#!/usr/bin/env python
import doctest
def test():
"""
>>> print 42 #doctest: +ELLIPSIS
...
"""
def run():
"Run the test."
doctest.testmod()
if __name__ == '__main__':
run()
----------------------------------------
Logged In: YES
user_id=31435
That's true. doctest has few syntax requirements, but the
inability to start an expected output block with "..." has
always been one of them, and is independent of the
ELLIPSIS gimmick. I doubt this will change, in part because
the complications needed to "do something about it" are
probably pig ugly, in part because it's so rare a desire, and in
part because there are easy ways to work around it (like
arranging for the expected output to start with something
other than '...'). | https://bugs.python.org/issue1192554 | CC-MAIN-2017-43 | refinedweb | 183 | 73.98 |
Download and install IronRuby
Go to and click on the Downloads tab. Grab the .zip file that is appropriate for your platform. There is also a Windows Installer, but I don’t know what it does, so I stick with the zip file. Extract it to a folder on your computer – I recommend c:ironruby. Add c:ironrubybin to your path (if you already have a version of ruby installed, I recommend putting IronRuby in the path AFTER your existing ruby).
Download and install Rake
This is easy, as rubygems comes along with IronRuby. Open a command prompt and type:
igem install rake
In your c:ironrubybin folder, there are two new files: rake.bat and rake. I made copies of those files and named them irake.bat and irake, respectively. This is completely unnecessary, but helpful if you already have an existing ruby installed. irake will run a script with IronRuby, and rake will run a script with your existing ruby.
To test it, create a new file named rakefile.rb in a temporary folder. Add the following contents:
task :default do puts 'hello world' end
Open a command prompt to the folder containing that file, and type irake. After an unfortunate pause, you should see the "”hello world” message. You now have a working IronRuby installation that can run rake scripts. If you have another version of ruby installed (and in your path), you can execute the same script by typing rake. You should see that it also (though much more quickly) puts the greeting message on screen.
Now for something interesting
If you ran the last demo under both versions of ruby, you witnessed the downside of using rake under IronRuby– the slow startup time. However, IronRuby does have one nice big advantage for .NET developers: the ability to easily call your .NET code from the script.
For example, I recently built a simple website using a Web Application Project, which compiles to a DLL. I wanted to be able to build out the database schema using my Fluent NHibernate configuration. I created a static BuildSchema method that does just that:
1: public class Database
2: {
3: public static void BuildSchema()
4: {
5: new SchemaExport(GetConfiguration()).Create(false, true);
6: }
7:
8: public static Configuration GetConfiguration()
9: {
10: return Fluently.Configure()
11: .Database(MsSqlConfiguration.MsSql2008.ConnectionString(x =>
12: {
13: x.Database("mydatabse");
14: x.Server(".");
15: x.TrustedConnection();
16: }))
17: .Mappings(map => map.AutoMappings.Add(
18: AutoMap
19: .AssemblyOf<Database>(t => typeof(Entity).IsAssignableFrom(t))
20: ))
21:
22: .BuildConfiguration();
23: }
24: }
I cannot easily execute the DLL from the command-line (to rebuild the database as part of a build script). Normally I would have to create a separate Console application project, which calls BuildSchema from its Main method. However, with IronRuby, I can invoke this method with the following code:
1: desc "Generate the database (requires IronRuby)"
2: task :db do
3: $:.unshift('.srcMyAppbin')
4: require 'MyApp'
5: MyApp::Database.BuildSchema
6: puts 'Database rebuilt'
7: end
Most of this is standard rake code. The interesting bits are in:
- Line 3 – Extend $: (the array of paths that ruby searches for files to load) to include the location of my binary. Otherwise, IronRuby will not be able to find any of the assemblies my assembly depends on.
- Line 4 – Load the libary built from the web application project (MyApp.dll)
- Line 5 – Invoke the static Database.BuildSchema method
With IronRuby and Rake, it is trivial to create build script tasks that make use of your existing .NET code. No need to create special task libraries, as you would with NAnt or MSBuild. | https://lostechies.com/joshuaflanagan/2010/06/14/using-rake-under-ironruby/ | CC-MAIN-2016-30 | refinedweb | 605 | 66.44 |
.NET Back to Basics: The int Class
The humble 'int'. We take it for granted every day we write software in .NET without even stopping to think what's behind the scenes. To many developers, it's just a simple type, but below the covers 'int' is actually a type, set in the 'System' namespace.
Granted, it's not as large as 'Math' or 'Collections' or even 'String', but it has a few unique tricks up its sleeve that can prove interesting.
For a start, int comes in several flavours:
- Int16
- Int32
- Int64
- UInt16
- UInt32
- UInt64
In most cases, you'll simply just use 'int' when writing software, but in cases where you need to make sure that your value sticks to a specific number of bits, and is definitely signed or unsigned, you need to use the actual class name.
The 16, 32, & 64 specify the 'Bit Size' of the number. The 'U' prefix means that the 'Unsigned' variety is to be used.
Let's try an example. Create yourself a simple .NET console mode program in Visual Studio and make sure program.cs has the following code in it:
using System; namespace IntClassExplorer { class Program { static void Main() { UInt16 umax16 = UInt16.MaxValue; UInt16 umin16 = UInt16.MinValue; Int16 max16 = Int16.MaxValue; Int16 min16 = Int16.MinValue; UInt32 umax32 = UInt32.MaxValue; UInt32 umin32 = UInt32.MinValue; Int32 max32 = Int32.MaxValue; Int32 min32 = Int32.MinValue; UInt64 umax64 = UInt64.MaxValue; UInt64 umin64 = UInt64.MinValue; Int64 max64 = Int64.MaxValue; Int64 min64 = Int64.MinValue; Console.WriteLine("Maximum Value for Unsigned Int16: {0}", umax16); Console.WriteLine("Minimum Value for Unsigned Int16: {0}", umin16); Console.WriteLine("Maximum Value for Signed Int16: {0}", max16); Console.WriteLine("Minimum Value for Signed Int16: {0}", min16); Console.WriteLine("Maximum Value for Unsigned Int32: {0}", umax32); Console.WriteLine("Minimum Value for Unsigned Int32: {0}", umin32); Console.WriteLine("Maximum Value for Signed Int32: {0}", max32); Console.WriteLine("Minimum Value for Signed Int32: {0}", min32); Console.WriteLine("Maximum Value for Unsigned Int64: {0}", umax64); Console.WriteLine("Minimum Value for Unsigned Int64: {0}", umin64); Console.WriteLine("Maximum Value for Signed Int64: {0}", max64); Console.WriteLine("Minimum Value for Signed Int64: {0}", min64); } } }
If you run this, you should see the following output:
Figure 1: Output from our first code listing
You can see straight away that the unsigned versions all have a minimum value of 0, which means they can't be used to represent negative values. The signed versions, however, can, but at the cost of their upper positive limit being halved.
The maximum value is the number of bits to the power of 2, so for a 16 bit number this is
2^16 = 65536
This number comes from the binary columns across the number, which are all powers of 2. For example, a 4 bit number with four columns would be
8 4 2 1 (Work from the right to the left.)
Adding each of these up give us
8+4+2+1 = 15
Which means 15 is the maximum number a 4 bit integer can take. A 16, 32, and 64 bit integer are no different, except instead of four columns going from right to left, you go for as many columns as there are bits in the number.
So, What Makes Signed Numbers Different?
I'm glad you asked :-)
With a signed number, the left most bit is not used as part of the number; it's used as a flag to indicate if our integer is positive, or negative, and it's because of this that our number range is effectively halved.
Because each 'bit' column is a single power of 2, reducing the columns in your 16 bit number, for example, reduces it to a 15 bit number, effectively dividing the number by 2.
If you want to learn more about how this works, the 2's compliment article of Wikipedia is a great place to start.
The important point to take away from the previous example is the Sign type and constants that each of the integer classes have, which let you easily find the minimum and maximum values each can hold.
The integer classes also have a number of useful methods that allow you to convert string to integers, integers to strings, and perform testing on them.
The first two of these are
- CompareTo
- Equals
CompareTo returns an integer value indicating if the passed-in operand is greater than, less than, or equal to the value being converted. Change your program.cs file to contain the following code and run it.
using System; namespace IntClassExplorer { class Program { static void Main() { Int32 myInt = 5; Int32 lessInt = 1; Int32 greaterInt = 8; Int32 sameInt = 5; Console.WriteLine("{1} compared to {0} gives a value of {2}", lessInt, myInt, myInt.CompareTo(lessInt)); Console.WriteLine("{1} compared to {0} gives a value of {2}", greaterInt, myInt, myInt.CompareTo(greaterInt)); Console.WriteLine("{1} compared to {0} gives a value of {2}", sameInt, myInt, myInt.CompareTo(sameInt)); } } }
The results should look something like the output in Figure 2:
Figure 2: Output from code Listing 2
As you can see from Figure 2, if the operand is less than the integer being compared to, a value of 1 is returned. However, if the operand is greater, a -1 is returned, with 0 being returned if and only if the operand and the source integer are equal.
If you now change the three 'Console.WriteLine' statements in code snippet 2 as follows:
Console.WriteLine("{1} equal to {0} gives a value of {2}", lessInt, myInt, myInt.Equals(lessInt)); Console.WriteLine("{1} equal to {0} gives a value of {2}", greaterInt, myInt, myInt.Equals(greaterInt)); Console.WriteLine("{1} equal to {0} gives a value of {2}", sameInt, myInt, myInt.Equals(sameInt));
Then re-run the program, you'll see the difference between 'Equals' and 'CompareTo':
Figure 3: The output from code snippet 2, with the write line statements changed
As you can see, 'Equals' simply returns a Boolean value indicating if the value is equal or not, whereas 'CompareTo' returns a value that also tells you the direction of the inequality.
Moving on from comparisons, next up are the "Parsing" methods.
Parsing is the act of taking a string containing a possible integer value, and attempting to turn it into an integer. For example:
"123" becomes 123
But
"ABC" would throw an error
All of the parse methods are static members of each of the Intxx classes, which means you don't need to instantiate an object using new to use them.
There are two main versions of the Parsing methods:
- Parse
- TryParse
Parse has four overrides, as follows:
- Parse(string)
- Parse(string, IFormatProvider)
- Parse(string, NumberStyles)
- Parse(string, NumberStyles, IFormatProvider)
The first simply takes the string you wish to parse, and attempts to convert it to an integer representation. If the string is un-parseable, parse will throw a 'FormatException' which can be caught by using the normal try/catch mechanism.
The remaining three take Format providers (a .NET class that represents culture-specific formatting information to help parse non-current culture formats) and/or a member of the 'System.Globalization.NumberStyles' enumeration that allows you to let parse know about things like the presence of hyphens, hexadecimal number formatting, and other similar options.
In most cases, the first version is generally all you'll want to use. If, however, you're dealing with values provided by a user who's not native with the currently selected culture, you'll often want to be very specific about the culture and formats you set up.
Change your program.cs file to look as follows:
using System; namespace IntClassExplorer { class Program { static void Main() { try { Int32 test1 = Int32.Parse("12345678"); Console.WriteLine("Test 1 converted successfully to {0}", test1); } catch(Exception ex) { Console.WriteLine("Test 1 failed with exception {0}", ex); } Console.WriteLine(); try { Int32 test2 = Int32.Parse("ABCDEF"); Console.WriteLine("Test 2 converted successfully to {0}", test2); } catch (Exception ex) { Console.WriteLine("Test 2 failed with exception {0}", ex); } Console.WriteLine(); try { Int16 test3 = Int16.Parse(Int32.MaxValue.ToString()); Console.WriteLine("Test 3 converted successfully to {0}", test3); } catch (Exception ex) { Console.WriteLine("Test 3 failed with exception {0}", ex); } Console.WriteLine(); } } }
When you run this program, you should get something similar to Figure 4:
Figure 4: Output from testing the int Parse method
In the last bit of code, test 1 works fine because that's a parsable integer. Test 2, however, does not due to the fact that it's not possible to derive a number from it.
Test 3 fails because, although the value is a genuine integer, the value produced is far too large for the destination variable and so causes an overflow exception to be thrown.
'TryParse', like parse, has overrides, but you'll notice that, unlike parse, it returns its integer result in an 'out' parameter, rather than as a result of the method call. The main reason for this is because 'TryParse' returns a Boolean stating if the conversion was successful and does NOT throw any of the exceptions that 'Parse' does.
'TryParse' is designed for use inside code where you intend to detect and act on invalid format and overflow errors yourself, or where throwing an exception might prove to be more trouble than it's worth; for example, in an embedded Linq statement.
Change the code in program.cs as follows:
using System; namespace IntClassExplore { class Program { static void Main() { Int32 test1; bool test1result = Int32.TryParse("12345678", out test1); Console.WriteLine("Test 1 converted to {0} with result {1}", test1, test1result); Int32 test2; bool test2result = Int32.TryParse("ABCDEF", out test2); Console.WriteLine("Test 2 converted to {0} with result {1}", test2, test2result); Int16 test3; bool test3result = Int16.TryParse(Int32.MaxValue.ToString(), out test3); Console.WriteLine("Test 3 converted to {0} with result {1}", test3, test3result); } } }
Then run it. The result should look a bit like the following:
Figure 5: Output from testing tryparse
If the number cannot be converted, the output result remains at 0 (the default value) and the output from the method call is false, allowing you to make the decision on how to handle the error yourself. The drawback is that you don't know the actual error that occurred, only that the conversion failed. This means that, if you want to handle the error differently depending on the issue, you'll still have to use 'Parse'.
The final method to cover is "ToString()" which, put simply, converts the integer value represented by the current Intxx object into its string representation.
The overrides to the method allow for an IFormatProvider to be given, allowing the integer to be formatted in a culture-specific way, or to provide a regular string that provides formatting instructions to build the string up in a certain way, such as padding out spaces.
Intxx can also use the normal +, -, /, and * operators to perform direct mathematic operations on its values, and can also take part in operations that perform AND, OR, or XOR on the variables in question.
Next month, we'll revisit the 'string' class in the same way as we've done here, and take a closer look at the various methods provided under the lid there.
Until then, don't get your integers in a knot and make sure you parse them correctly.
Shawty
RE: R&D ManagerPosted by Peter Shaw on 01/30/2016 03:20am
Indeed Jim, and yes a small oversight on my part there.Reply
r&d managerPosted by jim lohr on 01/26/2016 01:01pm
a mistake that could cause confusion amongst newbies... you state: "The maximum value is the number of bits to the power of 2, so for a 16 bit number this is 2^16 = 65536" this is incorrect. the formula for the maximum value of a 16 bit number is (2^16)-1=65535 the value 65536 is the number of unique values of a 16 bit number which are 0 through 65535 inclusive.Reply
R&D ManagerPosted by Jim Lohr on 01/25/2016 09:09am
Minor error, but could cause confusion to newbies... you state: "The maximum value is the number of bits to the power of 2, so for a 16 bit number this is 2^16 = 65536" The formula you gave is for the number of unique values which are zero though 65535 inclusive. The formula for the max value is actually (2^16)-1 = 65535.Reply | http://www.codeguru.com/columns/dotnet/.net-back-to-basics-the-int-class.html | CC-MAIN-2017-22 | refinedweb | 2,073 | 62.38 |
Now that you’re a little more familiar with the elements that make up the interface, it’s time to look at some of the more advanced layout elements you have at your fingertips with XUL. In most of these examples, I’ve omitted the default opening and closing window elements to reduce repetition. You should by now have several saved files that contain the XML declaration and XUL namespace etc, so unless it is subject to the discussion, I’ve focused purely on the element being described. You may find it beneficial to set yourself up a basic XUL file containing just the opening window element with the necessary namespace that you can open, modify and save under a different name to reduce the amount of typing you need to do.
Vbox and Hbox
The two most basic layout elements within XUL are the vbox and hbox, which divide the application window into vertical or horizontal boxes respectively. Interface elements are then added as children to these elements. There is no limit to the number of children that can be placed inside a box, and boxes will quite happily nest as necessary to give the look you are trying to achieve. One important fact to note is that boxes will not wrap, so placing more elements in a vertical box will increase the height of your application window, and placing more elements in a horizontal box will increase the width of your window. The hbox and vbox elements are shorthand equivalents of using the box element with an orient attribute. So <hbox> is equal to <box orient=”horizontal”> and <vbox> is equal to <box orient=”vertical”>. If the box element is used without specifying the orient, the default attribute is horizontal. Similarly, the <bbox> element is shorthand for a box element that has an align=”baseline” attribute. Incase you’re wondering, the baseline value of the alignment attribute causes children of the box element to be aligned so that their labels line up.
<?xml version=”1.0″?>
<window id=”boxes” title=”The Box Model” width=”500″ height=”300″ screenX=”50″ screenY=”100″
xmlns=”
there.is.only.xul”>
<button label=”Button1″/>
<button label=”Button2″/>
<button label=”button3″/>
</window>
This is extrememly similar to one of the windows created in the first article in this series, but do it again to remind yourself how the buttons are laid out in the window. Now, in the same file, add an opening and closing set of <hbox> tags so that they encapsulate the three buttons and run the file again. See the difference? Now put an opening and closing set of <vbox> elements within the hbox, and the buttons go back to a vertical stack. Placing another vbox enclosed set of buttons inside the outer hbox gives you two columns:<hbox>
<vbox>
<button label=”Button1″/>
<button label=”Button2″/>
<button label=”button3″/>
</vbox>
<vbox>
<button label=”Button4″/>
<button label=”Button5″/>
<button label=”button6″/>
</vbox>
</hbox>
This very flexible layout method is aptly named by the creators of XUL as the box model.
{mospagebreak title=Flex and Grids}
Flex
A common attribute of elements placed in boxes is Flex, which makes the room the element uses an attribute of flexible. In the example above, all of the buttons are the same size and there is a lot of left over space to the side of them. Try adding a flex=”1″ attribute to the second opening vbox element. Now the second set of buttons will take up all of the remaining available space in the window. This is commonly used with spacers to make other elements appear in appropriate places within windows. You may at this point be thinking that the value of flex is of a Boolean type, with 1 for true and 0 for false. This is not the case; the flex attribute is of the integer type. If you have multiple elements with the flex attribute, the attribute with the highest flex value will take up the most space.
Grids
Another positional element is the grid element, which allows you to specify both vertical and horizontal positions of elements. The grid is commonly used with elements and their corresponding labels to ensure that everything lines up correctly within your interface. The grid syntax is very easy to master; everything in the grid should be contained within an opening and closing grid element set, individual rows are defined within a rows opening and closing element set and individual columns are defined within a columns opening and closing element set. Care should be taken when designing grids as it is easy to misplace elements. Add the following code to a new XUL file and execute it in the normal way:<grid>
<rows>
<row>
<button label=”button1″/>
<button label=”button2″/>
<button label=”button3″/>
</row>
</rows>
<columns>
<column>
<button label=”button4″/>
<button label=”button5″/>
<button label=”button6″/>
</column>
</columns>
</grid>
Now, the dilemma that you face here is that button 4 has overlaid and obscured button 1. Generally, you would only add content to rows or columns rather than both to avoid this kind of conflict. Try changing it to this to get the desired (in this example) effect:
<grid>
<rows>
<row>
<button label=”button1″/>
<button label=”button2″/>
<button label=”button3″/>
</row>
<row>
<button label=”button4″/>
</row>
<row>
<button label=”button5″/>
</row>
<row>
<button label=”button6″/>
</row>
</rows>
</grid>
Much better! Again, the flex attribute is more than welcome if you need to make elements stretch to fit the available space within the window. In the example above however, the flex attribute may have unexpected results without the addition of columns. Try adding the flex attribute to the first and last opening row elements to see how the buttons are affected.
{mospagebreak title=Groupbox, Stack and Deck}
Groupbox
Another positional model that can be used is that of the <groupbox> which stacks child elements in a column and draws a bow around them. The syntax for this is equally simple, and although one has been provided, an example is not strictly necessary:<groupbox>
<caption label=”Groupbox”/>
<description value=”Item1″/>
<description value=”Item2″/>
<description value=”Item3″/>
</groupbox>
Without a stylesheet to make it look nice, this example is pretty bland, but it demonstrates the use of the groupbox element.
Stack & Deck
Other layout methods include the stack and deck elements, both similar but with a subtle difference; both elements place interface elements in a physical stack, placing them on top of each other, but while the stack elements offers transparency, so elements at the bottom of the stack can still be visible, the deck does not, and elements will be seen to cover entirely or overlap depending on their placement.<stack>
<description value=”Bottom Stack!”/>
<description value=”Top Stack!”/>
</stack>
<spacer height=”10″/>
<deck>
<description value=”Bottom Deck!”/>
<description value=”Top Deck!”/>
</deck>
The code above will draw a window with the stack at the top and the deck below. The stack elements are all displayed at once, hence the incomprehensible garble. Notice how we have specified two decks, but only one deck is displayed, and this is the bottom one. When the selectedIndex attribute is not defined, the default value is zero. Indices, as we all know, tend to be zero based, so the above deck has a max index of 1. In order to display the top deck, simply add a selectedIndex=”1″ attribute to the opening deck tag. Now the top deck will be displayed. Clearly, the use of a script to modify the selectedIndex value could produce effects similar to basic animation.
{mospagebreak title=Content Elements}
All I’ve talked about so far are elements; interface elements and layout elements. What I haven’t mentioned yet are content elements. We’ve seen buttons, labels, controls etc, but nothing in which to actually store content. What that content actually is depends on what the application does, for a browser, such as Mozilla, the main content is HTML pages. As XUL came around in order for Mozilla to actually be constructed, HTML pages are easily displayed using an iframe element. To test this out fully, you’ll need a web page to display. You could create one of your own, or to save yourself some time you could work with something that’s already out there.
What I did was to go to the Google homepage (because it has a relatively simple homepage but features many links and has some functionality) in a browser, and save the page as google.htm to my XUL directory. Do whatever you want, but get an HTML file that at least has links to other pages on it. Now, create a basic window (I mean add the opening and closing window element to a blank text file with the necessary namespace) with nothing in it except the following line of code:
<iframe src=”google.htm” flex=”1″/>
Note that the attribute must be included, or the page will not open within the iframe. Now, save it as iframe.xul or similar and then execute it with the command line. Your window should appear with the Google homepage loaded in it. The links should work and you can even do actual searches with it. You’ve just created a browser, with just a couple of lines of code! If your window is smaller than the size of the page you’ve selected for this example, Mozilla will even include working scrollbars for you, with no additional code. You’re not restricted to displaying just web pages either, change the src attribute of the iframe to one of the XUL files you’ve already created and watch in awe as that is loaded just as easily. It will even render simple text files, which you can prove by changing the src to a file ending in .txt. The files that you’re opening should be located in the same directory as the iframe.xul file, or should include the full path to them if they’re not.
I feel it appropriate to mention at this point that true to its XML roots, XUL is also able to work with and process HTML tags and render them within its windows accordingly. In order to use the tags that it supports you need to make sure that the XHTML namespace is imported. This requires the addition of the namespace to the opening window tag, and an HTML prefix preceding each HTML element you wish to use. Create the following file for confirmation of this:<?xml version=”1.0″?>
<window
id=”html”
title=”Render HTML”
width=”500″
height=”300″
screenX=”50″
screenY=”100″
xmlns=”
there.is.only.xul”
xmlns:html=””>
<html:div>
This is HTML!
</html:div>
<html:ol>
<html:li>This is an html list item!</html:li>
<html:li>So is this!</html:li>
</html:ol>
</window>
So you see, there are several very basic ways to include content within your XUL files. The next article introduces RDF, and explains how more complex elements can be access via a chrome URL from within Mozilla to give added functionality and power to your XUL applications. | http://www.devshed.com/c/a/XML/An-Introduction-to-XUL-Part-3/ | CC-MAIN-2017-22 | refinedweb | 1,852 | 58.72 |
03 February 2011 16:48 [Source: ICIS news]
TORONTO (ICIS)--Switzerland’s 2010 chemical and pharmaceuticals exports rose to Swfr75.9bn ($79.9bn), up 5.7% from 2009, but the bulk of Swiss non-pharma chemical exports have not yet caught up to pre-crisis 2008 levels, a chemical industry trade group said on Thursday.
The group, SGCI Chemie Pharma Schweiz, credited pharmaceuticals for the overall increase in exports. Exports of pharmaceuticals were Swfr60.6bn, up 4.2% from 2009, and up 9.7% from a record 2008 year, the group said.
However, SGCI said while non-pharma exports for pigments, dyes and colourants rose 11.2% from 2009, to Swfr800m, they were still down 15.9% from their 2008 level.
Swiss organic chemical exports rose also by 11.2% from 2009, to Swfr3.6bn, but were still down 11.1% from 2008.
Crop chemical product exports rose 11.6% from 2009, to Swfr2bn, but were down 8.4% from 2008.
The only non-pharma sector recording increases from both 2009 and 2008 were flavours and fragrances, which rose 19.6% from 2009, to Swfr1.9bn, and were up 1.8% from 2008.
Regionally, the largest export market for Swiss chemicals and pharmaceuticals was the EU, where customers bought Swfr43.7bn worth of product, up 2.3% from 2009. However, exports to the EU were still 10.6% below their 2008 level, the group said.
The chemicals and pharmaceuticals industry is ?xml:namespace>
As for pharma imports,
Major Swiss chemical and pharmaceuticals producers include Novartis, Roche, Clariant, EMS Chemie, Lonza and Syngenta, among others.
($1 = Swfr0.95; €1 = Swfr1.29)For more on Clariant, EMS and other producer | http://www.icis.com/Articles/2011/02/03/9432202/swiss-2010-non-pharma-chem-exports-still-below-2008-levels.html | CC-MAIN-2014-42 | refinedweb | 278 | 71.82 |
Tutorial: Support ink in your Windows app
Surface Pen (available for purchase at the Microsoft Store).
This tutorial steps through how to create a basic Windows app that supports writing and drawing with Windows Ink. We use snippets from a sample app, which you can download from GitHub (see Sample code), to demonstrate the various features and associated Windows Ink APIs (see Components of the Windows Ink platform) discussed in each step.
We focus on the following:
- Adding basic ink support
- Adding an ink toolbar
- Supporting handwriting recognition
- Supporting basic shape recognition
- Saving and loading ink
For more detail about implementing these features, see Pen interactions and Windows Ink in Windows apps.
Introduction
With Windows Ink, you can provide your customers with the digital equivalent of almost any pen-and-paper experience imaginable, from quick, handwritten notes and annotations to whiteboard demos, and from architectural and engineering drawings to personal masterpieces.
Prerequisites
- A computer (or a virtual machine) running the current version of Windows 10
- Visual Studio 2019 and the RS2 SDK
- Windows 10 SDK (10.0.15063.0)
- Depending on your configuration, you might have to install the Microsoft.NETCore.UniversalWindowsPlatform NuGet package and enable Developer mode in your system settings (Settings -> Update & Security -> For developers -> Use developer features).
- If you're new to Windows app development with Visual Studio, have a look through these topics before you start this tutorial:
- [OPTIONAL] A digital pen and a computer with a display that supports input from that digital pen.
Note
While Windows Ink can support drawing with a mouse and touch (we show how to do this in Step 3 of this tutorial) for an optimal Windows Ink experience, we recommend that you have a digital pen and a computer with a display that supports input from that digital pen.
Sample code
Throughout this tutorial, we use a sample ink app to demonstrate the concepts and functionality discussed.
Download this Visual Studio sample and source code from GitHub at windows-appsample-get-started-ink sample:
- Select the green Clone or download button
- If you have a GitHub account, you can clone the repo to your local machine by choosing Open in Visual Studio
- If you don't have a GitHub account, or you just want a local copy of the project, choose Download ZIP (you'll have to check back regularly to download the latest updates)
Important
Most of the code in the sample is commented out. As we go through each step, you'll be asked to uncomment various sections of the code. In Visual Studio, just highlight the lines of code, and press CTRL-K and then CTRL-U.
Components of the Windows Ink platform
These objects provide the bulk of the inking experience for Windows apps.
Step 1: Run the sample
After you've downloaded the RadialController sample app, verify that it runs:
Open the sample project in Visual Studio.
Set the Solution Platforms dropdown to a non-ARM selection.
Press F5 to compile, deploy, and run.
Note
Alternatively, you can select Debug > Start debugging menu item, or select the Local Machine Run button shown here.
The app window opens, and after a splash screen appears for a few seconds, you’ll see this initial screen.
Okay, we now have the basic Windows app that we’ll use throughout the rest of this tutorial. In the following steps, we add our ink functionality.
Step 2: Use InkCanvas to support basic inking
Perhaps you've probably already noticed that the app, in it's initial form, doesn't let you draw anything with the pen (although you can use the pen as a standard pointer device to interact with the app).
Let's fix that little shortcoming in this step.
To add basic inking functionality, just place an InkCanvas control on the appropriate page in your app.
Note
An InkCanvas has default Height and Width properties of zero, unless it is the child of an element that automatically sizes its child elements.
In the sample:
- Open the MainPage.xaml.cs file.
- Find the code marked with the title of this step ("// Step 2: Use InkCanvas to support basic inking").
- Uncomment the following lines. (These references are required for the functionality used in the subsequent steps).
using Windows.UI.Input.Inking; using Windows.UI.Input.Inking.Analysis; using Windows.UI.Xaml.Shapes; using Windows.Storage.Streams;
- Open the MainPage.xaml file.
- Find the code marked with the title of this step ("<!-- Step 2: Basic inking with InkCanvas -->").
- Uncomment the following line.
<InkCanvas x:
That's it!
Now run the app again. Go ahead and scribble, write your name, or (if you're holding a mirror or have a very good memory) draw your self-portrait.
Step 3: Support inking with touch and mouse
You'll notice that, by default, ink is supported for pen input only. If you try to write or draw with your finger, your mouse, or your touchpad, you'll be disappointed.
To turn that frown upside down , you need to add a second line of code. This time it’s in the code-behind for the XAML file in which you declared your InkCanvas.
In this step, we introduce the InkPresenter object, which provides finer-grained management of the input, processing, and rendering of ink input (standard and modified) on your InkCanvas.
Note
Standard ink input (pen tip or eraser tip/button) is not modified with a secondary hardware affordance, such as a pen barrel button, right mouse button, or similar mechanism.
To enable mouse and touch inking, set the InputDeviceTypes property of the InkPresenter to the combination of CoreInputDeviceTypes values that you want.
In the sample:
- Open the MainPage.xaml.cs file.
- Find the code marked with the title of this step ("// Step 3: Support inking with touch and mouse").
- Uncomment the following lines.
inkCanvas.InkPresenter.InputDeviceTypes = Windows.UI.Core.CoreInputDeviceTypes.Mouse | Windows.UI.Core.CoreInputDeviceTypes.Touch | Windows.UI.Core.CoreInputDeviceTypes.Pen;
Run the app again and you'll find that all your finger-painting-on-a-computer-screen dreams have come true!
Note
When specifying input device types, you must indicate support for each specific input type (including pen), because setting this property overrides the default InkCanvas setting.
Step 4: Add an ink toolbar
The InkToolbar is a UWP platform control that provides a customizable and extensible collection of buttons for activating ink-related features.
By default, the InkToolbar includes a basic set of buttons that let users quickly select between a pen, a pencil, a highlighter, or an eraser, any of which can be used together with a stencil (ruler or protractor). The pen, pencil, and highlighter buttons each also provide a flyout for selecting ink color and stroke size.
To add a default InkToolbar to an inking app, just place it on the same page as your InkCanvas and associate the two controls.
In the sample
- Open the MainPage.xaml file.
- Find the code marked with the title of this step ("<!-- Step 4: Add an ink toolbar -->").
- Uncomment the following lines.
<InkToolbar x: </InkToolbar>
Note
To keep the UI and code as uncluttered and simple as possible, we use a basic Grid layout and declare the InkToolbar after the InkCanvas in a grid row. If you declare it before the InkCanvas, the InkToolbar is rendered first, below the canvas and inaccessible to the user.
Now run the app again to see the InkToolbar and try out some of the tools.
Challenge: Add a custom button
Step 5: Support handwriting recognition
Now that you can write and draw in your app, let's try to do something useful with those scribbles.
In this step, we use the handwriting recognition features of Windows Ink to try to decipher what you've written.
Note
Handwriting recognition can be improved through the Pen & Windows Ink settings:
- Open the Start menu and select Settings.
- From the Settings screen select Devices > Pen & Windows Ink.
- Select Get to know my handwriting to open the Handwriting Personalization dialog.
In the sample:
- Open the MainPage.xaml file.
- Find the code marked with the title of this step ("<!-- Step 5: Support handwriting recognition -->").
- Uncomment the following lines.
<Button x: <TextBlock x:
- Open the MainPage.xaml.cs file.
- Find the code marked with the title of this step (" Step 5: Support handwriting recognition").
- Uncomment the following lines.
- These are the global variables required for this step.
InkAnalyzer analyzerText = new InkAnalyzer(); IReadOnlyList<InkStroke> strokesText = null; InkAnalysisResult resultText = null; IReadOnlyList<IInkAnalysisNode> words = null;
- This is the handler for the Recognize text button, where we do the recognition processing.
private async void recognizeText_ClickAsync(object sender, RoutedEventArgs e) { strokesText = inkCanvas.InkPresenter.StrokeContainer.GetStrokes(); // Ensure an ink stroke is present. if (strokesText.Count > 0) { analyzerText.AddDataForStrokes(strokesText); resultText = await analyzerText.AnalyzeAsync(); if (resultText.Status == InkAnalysisStatus.Updated) { words = analyzerText.AnalysisRoot.FindNodes(InkAnalysisNodeKind.InkWord); foreach (var word in words) { InkAnalysisInkWord concreteWord = (InkAnalysisInkWord)word; foreach (string s in concreteWord.TextAlternates) { recognitionResult.Text += s; } } } analyzerText.ClearDataForAllStrokes(); } }
- Run the app again, write something, and then click the Recognize text button
- The results of the recognition are displayed beside the button
Challenge 1: International recognition
Challenge 2: Dynamic recognition
Step 6: Recognize shapes
Ok, so now you can convert your handwritten notes into something a little more legible. But what about those shaky, caffeinated doodles from your morning Flowcharters Anonymous meeting?
Using ink analysis, your app can also recognize a set of core shapes, including:
- Circle
- Diamond
- Drawing
- Ellipse
- EquilateralTriangle
- Hexagon
- IsoscelesTriangle
- Parallelogram
- Pentagon
- Quadrilateral
- Rectangle
- RightTriangle
- Square
- Trapezoid
- Triangle
In this step, we use the shape-recognition features of Windows Ink to try to clean up your doodles.
For this example, we don't attempt to redraw ink strokes (although that's possible). Instead, we add a standard canvas under the InkCanvas where we draw equivalent Ellipse or Polygon objects derived from the original ink. We then delete the corresponding ink strokes.
In the sample:
- Open the MainPage.xaml file
- Find the code marked with the title of this step ("<!-- Step 6: Recognize shapes -->")
- Uncomment this line.
<Canvas x: And these lines. <Button Grid.
- Open the MainPage.xaml.cs file
- Find the code marked with the title of this step ("// Step 6: Recognize shapes")
- Uncomment these lines:
private async void recognizeShape_ClickAsync(object sender, RoutedEventArgs e) { ... } private void DrawEllipse(InkAnalysisInkDrawing shape) { ... } private void DrawPolygon(InkAnalysisInkDrawing shape) { ... }
- Run the app, draw some shapes, and click the Recognize shape button
Here's an example of a rudimentary flowchart from a digital napkin.
Here's the same flowchart after shape recognition.
Step 7: Save and load ink
So, you're done doodling and you like what you see, but think you might like to tweak a couple of things later? You can save your ink strokes to an Ink Serialized Format (ISF) file and load them for editing whenever the inspiration strikes.
The ISF file is a basic GIF image that includes additional metadata describing ink-stroke properties and behaviors. Apps that are not ink enabled can ignore the extra metadata and still load the basic GIF image (including alpha-channel background transparency).
In this step, we hook up the Save and Load buttons located beside the ink toolbar.
In the sample:
- Open the MainPage.xaml file.
- Find the code marked with the title of this step ("<!-- Step 7: Saving and loading ink -->").
- Uncomment the following lines.
<Button x: <Button x:
- Open the MainPage.xaml.cs file.
- Find the code marked with the title of this step ("// Step 7: Save and load ink").
- Uncomment the following lines.
private async void buttonSave_ClickAsync(object sender, RoutedEventArgs e) { ... } private async void buttonLoad_ClickAsync(object sender, RoutedEventArgs e) { ... }
- Run the app and draw something.
- Select the Save button and save your drawing.
- Erase the ink or restart the app.
- Select the Load button and open the ink file you just saved.
Challenge: Use the clipboard to copy and paste ink strokes
Summary
Congratulations, you've completed the Input: Support ink in your Windows app tutorial ! We showed you the basic code required for supporting ink in your Windows apps, and how to provide some of the richer user experiences supported by the Windows Ink platform.
Related articles
Samples
- Ink analysis sample (basic) (C#)
- Ink handwriting recognition sample (C#)
- Save and load ink strokes from an Ink Serialized Format (ISF) file
- Save and load ink strokes from the clipboard
- Ink toolbar location and orientation sample (basic)
- Ink toolbar location and orientation sample (dynamic)
- Simple ink sample (C#/C++)
- Complex ink sample (C++)
- Ink sample (JavaScript)
- Coloring book sample
- Family notes sample | https://docs.microsoft.com/en-us/windows/uwp/design/input/ink-walkthrough | CC-MAIN-2020-45 | refinedweb | 2,079 | 55.13 |
Yes
Yes
Last edited by GTO_India; 2013-07-19 at 09:17.
My mif file i.e "MyView_0x2004aa1e.mif " is not getting created at data\z\resource\apps after running or building the App Why is it so?
Where as mifconv tool Iam able to create it at Epoc32\tools and hence I have changed in the .pkg file as
"$(EPOCROOT)Epoc32\tools\MyView_0x2004aa1e.mif" -"!:\resource\apps\MyView_0x2004aa1e.mif"
Post your _reg.rss file here.
Post the LOCALISABLE_APP_INFO block here from the main .rss file.
The .mif file is created in tools because you are running mifconv manually, there. It is probably not a problem, your .mif file is deployed correctly.
Hi wizard
my _reg.rss
#include "MyView.rls"
#include <appinfo.rh>
#include <MyView_0x2004aa1e.rsg>
UID2 KUidAppRegistrationResourceFile
UID3 0x2004aa1e
RESOURCE APP_REGISTRATION_INFO
{
app_file="MyView_0x2004aa1e";
localisable_resource_file = STRING_myview_loc_resource_file_1;
localisable_resource_id = R_LOCALISABLE_APP_INFO;
embeddability=KAppNotEmbeddable;
newfile=KAppDoesNotSupportNewFile;
}
in main.rss
RESOURCE LOCALISABLE_APP_INFO r_localisable_app_info
{
short_caption = qtn_app_short_caption_string;
caption_and_icon =
CAPTION_AND_ICON_INFO
{
caption = qtn_app_caption_string;
number_of_icons = 1;
icon_file = "\\resource\\apps\\MyView_0x2004aa1e.mif";
};
}
block here from the main .rss file ?
Last edited by GTO_India; 2013-07-24 at 09:10.
why .mif is not created at ""$(EPOCROOT)epoc32\data\z\resource\apps\" then ?
Hi wizard_ hu Iam waiting for the reply from you
In theory it looks fine. A thing you may want to check is copying the .mif and the original .svg file somewhere on the mass storage drive, and try opening them with the built-in file browser.
If you check the icon_aif.mk and similar files of the example applications, you will see that it is explicitly written there that the icon file should go to $(EPOCROOT)epoc32\data\z\resource\apps\, these things do not happen automatically.
buit-in file browser? Any way i will see
Last edited by GTO_India; 2013-07-26 at 13:13.
Hi Neil and Wizard Now after changing my workspace three thinga are getting created when I run or Build the application.
Those are
MyView_0x2004aa1d.mif of my App Icon
MYView_newImage.mif of my App screenshot
MYView_newImage.mbm of my App screenshot
Even though all are crated at C:\Nokia\devices\Nokia_Symbian3_SDK_v1.0\epoc32\data\z\resource\apps
My App Icon is not showing I doubt whether t is due to my sbs problem
I have also asked the query related to sbs (The Symbian Build System (sbs) cannot be found on the PATH. Carbide needs a valid SBS installation on the PATH to use the SBSv2 builder i.e Raptor/SBSv2 minimum version supported in carbide c++ is 2.15.0 .Your sbs version is 0.0.0.Please update your sbs installation and ReScan from the Build Configuration Filtering Prference page..)
at
You would get many people to help you if you dont call out to specific persons helpYou would get many people to help you if you dont call out to specific persons helpHi Neil and Wizard
Last edited by Symbian_Neil; 2013-08-19 at 10:51. Reason: typo
what do you mean by
changing back the paths in the pkg file ?
Ok can someone kindly answer the query related to sbs also
My .pkg files look like this
; Seven files to install
;
"$(EPOCROOT)\Epoc32\release\$(PLATFORM)\$(TARGET)\MyView_0x2004aa1d.exe" -"!:\sys\bin\MyView_0x2004aa1d.exe"
"$(EPOCROOT)\epoc32\data\Z\resource\apps\MyView_0x2004aa1d.rsc" -"!:\resource\apps\MyView_0x2004aa1d.rsc"
"$(EPOCROOT)\epoc32\data\z\resource\apps\MyView_0x2004aa1d.mif" -"!:\resource\apps\MyView_0x2004aa1d.mif"
"$(EPOCROOT)\epoc32\data\Z\private\10003a3f\apps\MyView_reg.rsc" -"!:\private\10003a3f\import\apps\MyView_reg.rsc"
"$(EPOCROOT)epoc32\data\z\resource\apps\MyView_mbm.mbm" -"!:\resource\apps\MyView_mbm.mbm"
"$(EPOCROOT)Epoc32\data\z\resource\apps\MYView_newImage.mif" -"!:\resource\apps\MYView_newImage.mif"
"$(EPOCROOT)Epoc32\data\z\resource\apps\MYView_newImage.mbm" -"!:\resource\apps\MYView_newImage.mbm"
Last edited by GTO_India; 2013-08-19 at 13:41.
Did you restart your device?
Well actually there are a number of suggestions already in this same thread itself (and a few of your other older threads on the same issue), instead of repeating, can you try all the suggestions in the previous posts of the thread where in post #31 you say that it worked.
Yes I have restarted the device twice. | http://developer.nokia.com/community/discussion/showthread.php/241650-Image-and-name-as-expected-not-showing-when-a-Symbian-app-is-rebuilt-Updated-again?p=922353&viewfull=1 | CC-MAIN-2014-35 | refinedweb | 681 | 59.6 |
Objective
Serial Communication - MPLAB® Xpress Example
In this project, a serial communications link is established with the PIC16F18855 MCU populating the MPLAB Xpress Development Board and a host PC. This communication is enabled by a PIC18LF25K50 MCU which is also populated on the Xpress board and is configured for two different USB classes to perform the following tasks:
- Configured using the USB Mass Storage Device (MSD) Class, receives .hex files from the host PC and then programs the PIC16F18855 using Microchip Technology’s In-Circuit Serial Programming (ICSP™) technology
- Translates EUSART data transmissions from the PIC16F18855 and transmits over the USB connection to the host PC using the USB Communications Device Class (USB CDC)
Using the latter CDC configuration enables the PIC16F18855 to send and receive information through the PIC18LF25K50 to an available USB port on a host computer. Terminal emulation software running on the host computer connects to the associated COM Port and can then be used to display information from the PIC16F18855 or allow the user to send commands back to the Microcontroller.
Materials
Hardware Tools (Optional)
Software Tools
Exercise Files
Project Video
This video shows the step-by-step creation of this project. The detailed written description is further below on this page under the Procedure heading.
Procedure
The PIC16F18855 EUSART peripheral connects on pins RC1 (TX) and RC0 (RX) to a PIC18LF25K50 configured to operate as a CDC USB device to translate the EUSART message for transmission over the USB protocol to a host computer COM Port.
The project uses:
- MPLAB Xpress Cloud-Based Integrated Development Environment with MPLAB Code Configurator Plug-in: mplabxpress.microchip.com
- PIC16F18855 Microcontroller:
- PIC18LF25K50 Microcontroller:
- MPLAB Xpress Development Board
- FREE Terminal Emulation Software
Windows users need to install the appropriate signed drivers in order to use the CDC configuration on the PIC18LF25K50 as detailed below. Linux and MAC OS users may skip over these two steps.
- The Windows signed drivers can be downloaded directly here.
- Once the inf – Composite Devices.zip has been downloaded, extract the files to the C:\DRIVERS\WIN directory.
To follow along with these steps, MPLAB Xpress should be open and the user should be logged in so that the MPLAB Code Configurator plug-in can be used. The setup is described in the Setup and Installation section of this training module. You should see a screen similar to the one shown here.:
1
Task 1.
2
Task 2
Create a new project in MPLAB Xpress for a PIC16F1855 using the MPLAB Xpress Development Board. Instructions are below if this is your first project.
3
Task 3
Open the MPLAB step two to open the MPLAB, set up the oscillator system and other configuration settings, and input and output selections for your device. When all this is completed you can generate project code including a main.c file. All these generated files will be included in your MPLAB Xpress project.
4
Task 4
In the open MCC window, the default parameters for the System resource can be used but you will need to add the EUSART peripheral to this project and setup the pin connections for the communication.
In the Device Resources area scroll down to locate the EUSART peripheral and expand. Double-click on the EUSART to add the peripheral to the Project Resources.
The Enable EUSART box should be checked. Enable Transmit should also be checked. The Baud Rate dropdown should be set to 19200. Finally, the Redirect STDIO to USART should be checked since this project will be using PRINTF statements to send data from the EUSART peripheral.
The setup in MCC should look like this:
System
- System Module
- Interrupt Module
- Pin Module
Peripherals
- EUSART
6
Task 6
Click the Generate button in MCC to create the appropriate header and source files for this configuration. A main.c file will also be generated for the project.
Upon successful code generation the “Generation Completed” notification should appear. Select OK to close the window.
New MCC Generated header and source files should now be present in the Project window of the MPLAB Xpress IDE including a new main.c source file.
7
Task 7
Click on the main.c source file in the Project pane to open the file and scroll through the code to locate the // Add your application code comment inside of the while(1) loop inside of the main().
At this point add a simple printf statement that will be used to execute a transmission over the EUSART and eventually display on the host computer. A simple statement enclosed in double quotes is all that is needed.
printf("Hello from MPLAB Xpress! \n \r");
You may wish to add a newline (\n) and a carriage return (\r) commands as shown.
9
Task 9.
10
Task 10
Open a terminal emulator program on the host computer and select the COM port associated with the MPLAB Xpress board. In this example a free program called TeraTerm is used. Note that the COM port number will probably be different from that shown below.
Configure the terminal emulation software to communicate at the 19200 baud rate that was configured earlier in the project when configuring the EUSART in MCC.
Results
Once communication is established, the terminal window should display the text enclosed in the printf statement added earlier in the project.
Analysis
The example shows how to perform one-way communication. The Xpress board sends the data as ASCII characters that are then displayed in the terminal window as text.
Conclusions
This project can be the basis for building a two-way communication project where data entered in the terminal window is sent back to the Xpress board and the data can be used in another algorithm. | https://microchipdeveloper.com/xpress:xpressexample | CC-MAIN-2020-05 | refinedweb | 950 | 61.06 |
view raw
I got error message TypeError: 'type' object does not support item
assignment for "dict[n] = n". Any help or suggestion? Thank you so
much!
Here is the purpose of this code.
Design and implement a TwoSum class. It should support the following
operations: add and find.
add - Add the number to an internal data structure. find - Find if
there exists any pair of numbers which sum is equal to the value.
For example,
add(1);
add(3);
add(5);
find(4) -> true
find(7) -> false
class TwoSum(object):
dict = {}
def add(self,n):
dict[n] = n #TypeError: 'type' object does not support item assignment
def find(self,n):
for i in range(0,len(dict)+1):
if dict[i] == None:
continue
val = n - dict[i]
if dict[val] != None and val != i+1:
return True
return False
test = TwoSum()
test.add(1)
test.add(3)
test.add(5)
print(test.find(4))
print(test.find(7))
Lot of issues here, I'll try to go through them one by one
dict = {}
Not only is this
overwriting python's dict, (see mgilson's comment) but this is the wrong data structure for the project. You should use a list instead (or a set if you have unique unordered values)
The data structure is an instance variable, it needs to be defined with
self and inside the
__init__ function. You should be using something like this:
class TwoSum(object): def __init__(self): self.numbers = []
def add(self,n): dict[n] = n
Assigning items to a dictionairy is not the way to do it. You should instead append to your list. Additionally you need to append to the list for that instance using
self.variableName = value
That range is wrong, and you would need a nested range, or itertools.combinations since you have to check for any two numbers that sum to a certain value, pythons
sum() is handy here.
To loop through the numbers you can use two ranges or itertools.combinations
import itertools class TwoSum(object): def __init__(self): self.numbers = [] def add(self, num): self.numbers.append(num) def find(self, desiredSum): for nums in itertools.combinations(self.numbers, 2): if sum(nums) == desiredSum: return True return False test = TwoSum() test.add(1) test.add(3) test.add(5) print(test.find(4)) print(test.find(7)) #True #False
def find(self, desiredSum): for num1 in self.numbers: for num2 in self.numbers: if num1 + num2 == desiredSum and num1 != num2: return True return False | https://codedump.io/share/8Qo6lYL0JCoL/1/python-typeerror-39type39-object-does-not-support-item-assignment | CC-MAIN-2017-22 | refinedweb | 416 | 67.45 |
Defining Jobs using Firetasks¶
This tutorial shows you how to:
- Run multiple tasks within a single Firework
- Run tasks that are defined within a Python function, rather than a shell script
This tutorial can be completed from the command line, but some knowledge of Python is helpful. In this tutorial, we will run examples on the central server for simplicity. One could just as easily run them on a FireWorker if you’ve set one up.
Introduction to Firetasks¶
In the Introductory tutorial, we ran a simple script that performed
echo "howdy, your job launched successfully!" >> howdy.txt". Looking inside
fw_test.yaml, recall that the command was defined within a task labeled
ScriptTask:
spec: _tasks: - _fw_name: ScriptTask script: echo "howdy, your job launched successfully!" >> howdy.txt
The
ScriptTask is one type of Firetask, which is a predefined job template written in Python. The
ScriptTask in particular refers Python code inside FireWorks that runs an arbitrary shell script that you give it. You can use the
ScriptTask to run almost any job (without worrying that it’s all done within a Python layer). However, you might want to set up jobs that are more powerful than shell scripts using Python programming. Later in this section, we’ll demonstrate how to accomplish this with custom Firetasks. However, first we’ll demonstrate the simplest version to linearly run multiple tasks.
Running multiple Firetasks¶
You can run multiple tasks within the same Firework (it might be helpful to review the Workflow Model diagram). For example, the first step of your Firework might write an input file that the second step reads and processes. Finally, a third step might move the entire output directory somewhere else on your filesystem (or a remote server).
Let’s create a Firework that:
- Writes an input file based on a template with some substitutions applied. We’ll do this using a built-in
TemplateWriterTaskthat can help create such files.
- Executes a script using
ScriptTaskthat reads the input file and produces some output. In our test case, it will just count the number of words in that file. However, this code could be any program, for example a chemistry code.
- Copies all your outputs to your home directory using
FileTransferTask.
The three-step Firework thus looks like this:
Navigate to the tasks tutorial directory in your installation directory:
cd <INSTALL_DIR>/fw_tutorials/firetask
Look inside the file
fw_multi.yaml:
spec: _tasks: - _fw_name: TemplateWriterTask context: opt1: 5.0 opt2: fast method output_file: inputs.txt template_file: simple_template.txt - _fw_name: ScriptTask script: wc -w < inputs.txt > words.txt use_shell: true - _fw_name: FileTransferTask files: - dest: ~/words.txt src: words.txt mode: copy
There are now three tasks inside our spec: the
TemplateWriterTask,
ScriptTask, and
FileTransferTask. The
TemplateWriterTaskwill load an example template called
simple_template.txtfrom inside the FireWorks code, replace certain portions of the template using the
context, and write the result to
input.txt. Next, the
ScriptTaskruns a word count on
input.txtusing the
wccommand and print the result to
words.txt. Finally,
FileTransferTaskwill copy the resulting output file to your home directory.
Note
If you would like to know more about how templated input writing works and define your own templated files, you should consult the TemplateWriterTask tutorial. A copy of
simple_template.txtis given in the directory as
simple_template_copy.txt(however, modifying the copy won’t modify the actual template).
Note
The
FileTransferTaskcan do much more than copy a single file. For example, it can transfer your entire output directory to a remote server using SSH. For details, see the FileTransferTask docs.
Run this multi-step Firework on your FireServer:
lpad reset lpad add fw_multi.yaml rlaunch singleshot
You should see two files written out to the system,
inputs.txt and
words.txt, confirming that you successfully ran the first two steps of your job! You can also navigate to your home directory and look for
words.txt to make sure the third step also got completed correctly.
This combination of writing a file, executing a command, and perhaps moving the results could be used in many situations. For example, you could use
TemplateWriterTask to write a templated queue script, and then use the
ScriptTask to submit it (e.g., via the qsub command). (note, however, that FireWorks provides more powerful methods to submit jobs through queues). Or, you could use the
TemplateWriterTask to write an input file, the
ScriptTask to execute a code that can read that input file, and finally the
FileTransferTask to move the results somewhere.
Note
The only way to communicate information between Firetasks within the same Firework is by writing and reading files, such as in our example. If you want to perform more complicated information transfer, you might consider defining a workflow that connects FireWorks instead. You can pass information easily between different FireWorks in a Workflow through the FWAction object, but not between Firetasks within the same Firework (Workflow Model).
Python Example (optional)¶
Here is a complete Python example that runs multiple Firetasks within a single Firework:
from fireworks import Firework, FWorker, LaunchPad, ScriptTask, TemplateWriterTask, FileTransferTask from fireworks.core.rocket_launcher import launch_rocket # set up the LaunchPad and reset it launchpad = LaunchPad() launchpad.reset('', require_password=False) #') firetask3 = FileTransferTask({'files': [{'src': 'words.txt', 'dest': '~/words.txt'}], 'mode': 'copy'}) fw = Firework([firetask1, firetask2, firetask3]) # store workflow and launch it locally, single shot launchpad.add_wf(fw) launch_rocket(launchpad, FWorker())
Creating a custom Firetask¶
The
TemplateWriterTask,
ScriptTask,
FileTransferTask are built-into FireWorks and can be used to perform useful operations. In fact, they might be all you need! In particular, because the
ScriptTask can run arbitrary shell scripts, it can in theory run any type of computation and is an ‘all-encompassing’ Firetask. ScriptTask also has many additional features that are covered in the ScriptTask tutorial.
However, if you are comfortable with some basic Python, you can define your own custom Firetasks for the codes you run. A custom Firetask gives you more control over your jobs, clarifies the usage of your code, and guards against unintended behavior by restricting the commands that can be executed.
Even if you plan to only use the built-in tasks, we suggest that you still read through the next portion before continuing with the tutorial. We’ll be creating a custom Firetask that adds one or more numbers using Python’s
sum() function, and later building workflows using this (and similar) Firetasks.
How FireWorks bootstraps a job¶
Before diving into an example of custom Firetask, it is worth understanding how FireWorks is bootstrapping jobs based on your specification. The basic process looks like this:
- The first step of the image just shows how the spec section of the Firework is structured. There is a section that contains your Firetasks (one or many), as we saw in the previous examples. The spec also allows you to define arbitrary JSON data (labeled input in the diagram) to pass into your Firetasks as input. So far, we haven’t seen an example of this; the only information we gave in the spec in the previous examples was within the _tasks section.
- In the second step, FireWorks dynamically loads Python objects based on your specified _tasks. It does this by searching a list of Python packages for Python objects that have a value of _fw_name that match your setting. When we set a _fw_name of
ScriptTaskin the previous examples, FireWorks was loading a Python object with a _fw_name class variable set to
ScriptTask(and passing the
scriptparameter to its constructor). The
ScriptTaskis just one type of Firetask that’s built into FireWorks to help you run scripts easily. You can write code for custom Firetasks anywhere in the user_packages directory of FireWorks, and it will automatically be discovered. If you want to place your Firetasks in a package outside of FireWorks, please read the FireWorks configuration tutorial. You will just need to define what Python packages to search for your custom Firetasks, or use a special format that allows for direct loading of classes.
- In the third step, we execute the code of the Firetask we loaded. Specifically, we execute the
run_taskmethod which must be implemented for every Firetask. FireWorks passes in the entire spec to the
run_taskmethod; the
run_taskmethod can therefore modify its behavior based on any input data present in the spec, or by detecting previous or future tasks in the spec.
- When the Firetask is done executing, it returns a FWAction object that can modify the workflow (or continue as usual) and pass information to downstream FireWorks.
Custom Firetask example: Addition Task¶
Let’s explore custom Firetasks with an example: a custom Python script for adding two numbers specified in the spec.
Staying in the firetasks tutorial directory, remove any output from the previous step:
rm howdy.txt FW.json words.txt
Let’s first look at what a custom Firetask looks like in Python. Look inside the file
addition_task.pywhich defines the
Addition Task:
class AdditionTask(FiretaskBase): _fw_name = "Addition Task" def run_task(self, fw_spec): input_array = fw_spec['input_array'] m_sum = sum(input_array) print("The sum of {} is: {}".format(input_array, m_sum)) return FWAction(stored_data={'sum': m_sum}, mod_spec=[{'_push': {'input_array': m_sum}}])
A few notes about what’s going on (things will be clearer after the next step):
- In the class definition, we are extending FiretaskBase to tell FireWorks that this is a Firetask.
- A special parameter named _fw_name is set to
Addition Task. This parameter sets what this Firetask will be called by the outside world and is used to bootstrap the object, as described in the previous section. If we did not set this ourselves, the default would have been
fireworks:AdditionTask(the root module name plus the class name separated by a colon).
- The
run_task()method is a special method name that gets called when the task is run. It can take in a Firework specification (spec) in order to modify its behavior.
- When executing
run_task(), the AdditionTask we defined first reads the input_array parameter of the Firework’s spec. It then sums all the values it finds in the input_array parameter of the Firework’s spec using Python’s
sum()function. Next, the Firetask prints the inputs and the sum to the standard out. Finally, the task returns a FWAction object.
- We’ll discuss the FWAction object in greater detail in future tutorials. For now, it is sufficient to know that this is giving two instructions. The first says we should store the sum we computed in the database (inside the Firework’s
stored_datasection). The second will pass the results on to any downstream FireTask or FireWork in the workflow as part of the spec inside a key called
input_array.
Now let’s define a Firework that runs this Firetask to add the numbers
1and
2. Look inside the file
fw_adder.yamlfor this new Firework definition:
spec: _tasks: - _fw_name: Addition Task parameters: {} input_array: - 1 - 2
Let’s match up this Firework with our code for our custom Firework:
- The _fw_name parameter is set to the same value as in our code for the Firetask (
Addition Task). This is how FireWorks knows to run your custom Firetask rather than
ScriptTaskor some other Firetask.
- This spec has an input_array field defined to
1and
2. Remember that our Python code was grabbing the values in the input_array, summing them, and printing them to standard out.
When you are comfortable that you roughly understand how a custom Firetask is set up, try running the Firework on the central server to confirm that the
Addition Taskworks:
lpad reset lpad add fw_adder.yaml rlaunch --silencer singleshot
Note
The
--silenceroption suppresses log messages.
Confirm that the sum is not only printed to the screen, but also stored in our Firework in the
stored_datasection:
lpad get_fws -i 1 -d all
should contain in its output a section that looks like this:
... "action": { "update_spec": {}, "mod_spec": [], "stored_data": { "sum": 3 }, ...
Writing your own custom Firetasks¶
If you’d like to attempt writing your own Firetask, a guide to doing so can be found here.
Python example (optional)¶
Here is a complete Python example that runs a custom Firetask:
from fireworks import Firework, FWorker, LaunchPad from fireworks.core.rocket_launcher import launch_rocket from fw_tutorials.firetask.addition_task import AdditionTask # set up the LaunchPad and reset it launchpad = LaunchPad() launchpad.reset('', require_password=False) # create the Firework consisting of a custom "Addition" task firework = Firework(AdditionTask(), spec={"input_array": [1, 2]}) # store workflow and launch it locally launchpad.add_wf(firework) launch_rocket(launchpad, FWorker())
Next up: Workflows!¶
With custom Firetasks, you can go beyond the limitations of running shell commands and execute arbitrary Python code templates. Furthermore, these templates can operate on data from the spec of the Firework. For example, the
Addition Task used the
input_array from the spec to decide what numbers to add. By using the same Firework with different values in the spec (try it!), one could execute a data-parallel application.
While one could construct an entire workflow by chaining together multiple Firetasks within a single Firework, this is often not ideal. For example, we might want to switch between different FireWorkers for different parts of the workflow depending on the computing requirements for each step. Or, we might have a restriction on walltime that necessitates breaking up the workflow into more atomic steps. Finally, we might want to employ complex branching logic or error-correction that would be cumbersome to employ within a single Firework. The next step in the tutorial is to explore connecting together FireWorks into a workflow. | https://pythonhosted.org/FireWorks/firetask_tutorial.html | CC-MAIN-2017-13 | refinedweb | 2,232 | 54.63 |
Interesting
A project is moving from their initial layouts to Bootstrap. They have quite a few class name conflicts in their css, so in order to isolate the new Bootstrap styles to specific elements, they added the Bootstrap styles to their own (in SASS) under a .bootstrap namespace, and are nesting any new elements under divs with a class of .bootstrap, and now everything is pretty again.
Nesting in this way (rather than namespacing all of the preexisting css) ensures that no Bootstrap styling leaks into pre-existing elements, but means that occasionally a pre-Bootstrap style will leak into the new namespaced elements due to higher selector specificity. | http://pivotallabs.com/author/lobascio/ | CC-MAIN-2014-52 | refinedweb | 109 | 58.21 |
James
I do not believe that t is FPT barking at you but rather MPE itself.
Look at the file name it is trying to save TEST.1.1 and that looks a
lot like filename.group.account. I do not know how to fix this except
to transfer each file separately (get rid of mget) and specify the target
file name as ./TEST.1.1 or what ever you need.
HTH James B. Byrne
Sent: Friday, September 26, 2008 2:46 PM
To: [email]HP3000-L@RAVEN.UTC.EDU[/email]
Subject: Re: [HP3000-L] MPE FTP transfer into HFS namespace
First of all, thank you Donna for excellent instructions and for the time
that you took to do this (even if as you claim it was only 5 minutes it
was worth an eternity to me). Your message will remain an invaluable aide
memoire for this process.
However, the update has not changed the behaviour of the ftp client:
----- 1 14 50 506740992 Sep 26 08:07 STDHAL.1.1
-rw-r----- 1 14 50 325265920 Sep 26 08:19 STDHAL.2.1
-rw-r----- 1 14 50 561713920 Sep 26 08:41 STDHAL.3.1
-rw-r----- 1 14 50 564188160 Sep 26 09:03 STDHAL.4.1
-rw-r----- 1 14 50 9747456 Sep 25 18:03 TEST.1.1
-rw-r----- 1 14 50 18894848 Sep 25 18:04 TEST.2.1
-rw-r----- 1 14 50 7290624 Sep 25 18:04 TEST.3.1
-rw-r----- 1 14 50 8643840 Sep 25 18:04 TEST.4.1
226 Directory send OK.
540 bytes received in 0.06 seconds (8.11 Kbytes/sec)
ftp> mget ./TEST*
200 PORT command successful. Consider using PASV.
150 Here comes the directory listing.
226 Directory send OK.
40 bytes received in 0.04 seconds (1.03 Kbytes/sec)
mget TEST.1.1? y
The group name provided did not start with an alphabetic character.
(FILE SYSTEM ERROR -117)
Any ideas?
--] *
[url][/url]
b1ucuADJNQGpbw7QnKGWiA5mJbmIJ+ENNTgBxFzrw==
Click on the link above to report this email as spam to BlackSpider.
***************************Disclaimer***************************. The views stated herein do not necessarily represent the view of the Company. Please ensure you have adequate virus protection before you open or detach any documents from this transmission. The Company does not accept any liability for viruses.
Premier Farnell plc
150 Armley Road Leeds
LS12 2QQ
Telephone +44 (0) 870 129 8608
Registered in England
Company Number 876412
Registered Office: Farnell House, Forge Lane, Leeds LS12 2NE ************************************************************
* To join/leave the list, search archives, change list settings, *
* etc., please visit [url][/url] * | http://fixunix.com/hewlett-packard/538613-re-mpe-ftp-transfer-into-hfs-namespace-print.html | CC-MAIN-2014-52 | refinedweb | 432 | 77.84 |
Content
Modified
4 october 2009
4 october 2009 compatibility with Flex 3.
In this article, I will provide a general overview of the main objectives in Flex 4, architecture differences, and an introduction to changes in components, layouts, use of states, and effects. I'll also answer some questions regarding what to expect when you compile your Flex 3 application in Flex 4. This article will not cover all of the new features and functionality in Flex 4. For that information, read the article What's new in Flex 4.
Throughout this document, the term MX components refers to components originally included in Flex 3. The term Spark components refers to the new set of components in Flex 4.
When migrating Flex 3 applications to Flex 4, SDK requires Flash Player 10 support.
Type selectors require a namespace
A CSS type selector names the Flex class to style. For example, the following are type selectors for Button and DateField:
Button { cornerRadius: 10; } DateField { color: #780800; }
As of the Flex 4 SDK, when an application uses type selectors, a namespace is required. If you are using only the MXML 2006 namespace in your Flex Application, add the following default namespace declaration to your CSS:
<mx:Style> @namespace ""; … </mx:Style>
If you are using multiple namespaces in your application, then you will need to provide each of the namespaces in your CSS. For an example, see Namespaces and packages in Flex 4 later in this article.
Further, if an application used a method like StyleManager.getStyleDeclaration("Button"), the type selector will need to include its package. For example, the call to getStyleDeclaration() would change to StyleManager.getStyleDeclaration("mx.controls.Button").
Theme change
The default theme for Flex 3 (MX) components is now the Spark theme. Therefore, your application may look and size itself differently when you compile it using the Flex 4 SDK. If, however, you want to use the Flex 3 look you still can because Flex 4 includes the Halo theme from Flex 3. To compile using the Halo theme, you can use the additional compiler argument -compatibility-version=3.0. In Flash Builder 4, you can do this in the Properties Panel. In the Properties Panel, select, Flex Compiler and click the checkbox for “Use Flex 3 compatibility mode" (see Figure 1).
Figure 1. Using Flex 3 Compatibility Mode
Alternatively, the theme can be changed from the default Spark theme to Halo in the Properties -> Flex Theme panel. In the “Flex Theme” panel, click on the Halo theme (see Figure 2).
Figure 2. Selecting the Halo Theme in the Properties Panel
If you do choose to use the new Spark theme, note that many of the styles that worked with the Halo theme do not work in the Spark theme. The Spark theme only supports a limited number of styles. To understand which styles are available for the Spark skin, you should reference the ASDoc. For each style listed per component, a "Theme" will be designated. If no theme is designated, then, the style is available for both the Halo and Spark theme. Flex 4 has also added a Wireframe skin that was designed to be used for quick mock-ups. The wireframe theme does not support style changes.
In addition to the theme change, the default preloader has changed to the mx.preloaders.SparkDownloadProgressBar for Flex 4 applications. This lighter weight preloader should shorten start-up time a little. If you want to use the Flex 3 preloader, you only need to change one line of code. In your
Applicationtag add the following:
preloader="mx.preloaders.DownloadProgressBar".
If you are migrating an application from Flex 3 to Flex 4 , I do not recommend that you replace each of your Flex 3 MX components with their corresponding Flex 4 components. This is probably not a good investment of your time. Instead, move to the Flex 4 component architecture for new applications.
In Flex 3, automation libraries were present under {sdk}/frameworks/libs and in the Flex 4 , it is available under {sdk}/frameworks/libs/automation. Users should ensure that they don’t have a copy of automation libraries under the frameworks/libs.
One of the major themes in the Flex 4 SDK is "Design in Mind". This goal involves creating a smoother workflow between designers and developers. To help achieve this, the framework provides a clear separation of the visuals for a component and the rest of its behavior. In Flex 3, an individual component's code included logic around its behavior, layout, and visual changes. In Flex 4, the components are factored out into different classes, each handling specific pieces of behavior.
As specified in the Gumbo Architecture Document:
"The main component class, the one whose class name matches the component's MXML tag name, encapsulates the core behavior of the component. This includes defining what events the component dispatches, the data that component represents, wiring up any sub-components that act as parts of the main component, and managing and tracking internal component state (we discuss states in more detail below).
Coupled with that component class is a skin class which manages everything related to the visual appearance of the component, including graphics, layout, representing data, changing appearance in different states, and transitioning from state to state. In the Halo model, Flex component skins were assets responsible for only one part of the graphics of a component. Changing any other aspect of a component's appearance, like layout or visualization of states, required sub-classing the component and editing the ActionScript code directly. In the Gumbo model, all of this is defined declaratively in the skin class, primarily through new graphics tags called FXG tags."
To learn more about the new graphics tags in Flex 4, you can read the FXG documentation.
As an example of the architecture discussed above, you can look at the code for the spark.components.Button class. This class only contains logic around the component's behavior. All of the visuals for this component are defined in the skin class spark.skins.spark.ButtonSkin
For performance reasons, the Flex 4 SDK has provided building blocks for developers to pick and choose the functionality that you need. Heavyweight functionality such as scrolling and virtualization that is not needed by all applications is not turned on by default.
While keeping Flex 3 classes intact in the same mx.* packages, the Flex 4 SDK introduces the spark.* packages for components, core classes, effects, filters, layouts, primitives, skins, and utils.
The Flex 4 SDK provides a new set of components and effects that share many of the same class names as Flex 3 components. To avoid name collisions in MXML, the Flex 4 SDK comes with four distinct namespaces: MXML 2006, MXML 2009, Spark, and Mx.
MXML 2006: The legacy MXML language namespace used in previous versions of Flex. Flex 3 applications compiled using Flex 4 can continue using this namespace.
URI:
Default Prefix: mx
MXML 2009: The new MXML language namespace. This is purely a language namespace, and does not contain component tags.
URI:
Default Prefix: fx
Default Prefix: fx
Spark: This namespace includes all of the new Spark components. It should be used in conjunction with the MXML 2009 language namespace.
URI: library://ns.adobe.com/flex/spark
Default Prefix: s
Default Prefix: s
MX: This namespace includes all of the MX components. It should be used in conjunction with the MXML 2009 language namespace.
URI: library://ns.adobe.com/flex/mx
Default Prefix: mx
Default Prefix: mx
Here is a small example that uses the MXML 2009, Spark, and Halo namespaces to create a simple Flex 4 application. This sample uses a MX DateChooser and a Spark Button.
<s:Application xmlns: <mx:DateChooser <s:Button </s:Application>
Flex 4 SDK has also added multiple namespace support in CSS. If you are using the MXML 2009, Spark, and MX namespaces along with Type selectors, you will need to define a set of namespaces in your CSS definitions to avoid name collisions.
Here is an example of CSS that uses type selectors for both MX and Spark components:
<fx:Style> @namespace s "library://ns.adobe.com/flex/spark"; @namespace mx "library://ns.adobe.com/flex/mx"; s|Button { color: #FF0000; } mx|DateChooser { color: #FF0000; } </fx:Style>
Prior to the release of the Flex 4 SDK, the Flex language allowed the
Applicationroot tag to include visual children and non-visual children. The visual children were added to the
Applicationwith
addChild()and non-visual children were treated as property declarations. Going forward, non-visual children that represent new property declarations are not allowed as immediate children of an
Application. You can add these non-visual children under a
<fx:Declarations>tag. This includes non-visual children such as effects, validators, formatters, data declarations, and RPC classes. Here is a short example:
<s:Application xmlns: <fx:Declarations> <s:Fade </fx:Declarations> <s:Button <s:Button </s:Application>
As I mentioned earlier, Flex 4 SDK introduces a number of new component classes that use the new architecture, which should make skinning and other customizations much more straightforward. Here is a table showing Flex 3 MX components and their Flex 4 Spark counterparts:
Adobe encourages you to use MX components and containers along with Spark components. Because Adobe continues to build components atop the same base class (UIComponent), there should be full interoperability between Spark and MX. Here is a table of the components and containers that do not currently have direct Spark equivalent classes.
To use a MX Navigator (ViewStack, Accordion, TabNavigator) with Spark Components, the children of the navigator should be a NavigatorContent component. Otherwise, you will not be able to use Spark primitives in your MX navigator. Here is an example:
<mx:ViewStack <s:NavigatorContent <s:layout> <s:VerticalLayout /> </s:layout> <s:Label <s:TextInput /> </s:NavigatorContent> </mx:ViewStack>
Flex 4 syntax:
- Only states are defined within the states array.
- In the new states syntax, you cannot use
AddChildand
RemoveChild. Instead, you define a component's role in a particular state on the component itself using the
includeInand
excludeFromattributes.
In the following Flex 3 example, states are used to include a Button and remove a TextInput only when the
currentStateof code using
includeInhave states syntax. Visit the Enhanced States documentation to find more details.
Many improvements have been made in the Flex 4 effects infrastructure. While MX effects will only work on controls based off of UIComponent, the Spark effects can operate on any target including the new graphic primitives in the framework. All of these effect classes live in the spark.effects.* package. Because Spark effects work on MX components, Spark components, and graphic primitives, Adobe recommends that you use Spark effect classes for future applications.
I've kept this description brief because you can get much more information about the new functionality in the effects classes from Chet Haase's Effects in Adobe Flex 4 article.
Changes in layout
In previous versions of Flex, the layout of components and containers were defined inside individual controls. Therefore, you had components such as List, TileList, and HorizontalList, which all share the same functionality except their layout. Still, their layout logic was defined within these component classes. In the Flex 4, layout has been decoupled from components. Now, Spark components such as Application, List, ButtonBar, and Panel can define their layouts declaratively. In all of the components, containment is managed by the Group class and the layout of the Group's children is delegated to an associated layout object. The layouts support both Spark and MX components in addition to the FXG graphic primitives. Layouts can even be changed at runtime.
As a developer, you can easily write custom layouts and swap them in and out of various individual components. Here is an example of defining a vertical List, horizontal List and a tiled List.
Vertical List (the default layout of a Spark List is VerticalLayout):
<s:List />
Horizontal List:
<s:List> <s:layout> <s:HorizontalLayout /> </s:layout> </s:List>
Tiled List:
<s:List> <s:layout> <s:TileLayout /> </s:layout> </s:List>
As I noted earlier, the Flex 4 architecture is set up to provide developers with building blocks to pick and choose what functionality they need. By default, virtualization and scrolling is not turned on. To add the option for scrollbars on a Group and turn on virtualization, you will need to:
useVirtualLayoutto
trueon your layout object
Scrollercomponent to your Group.
Here is an example of using virtualization and scrolling on a Spark Panel:
<s:Panel <s:Scroller <s:Group> <s:layout> <s:HorizontalLayout </s:layout> <s:TextInput /> <s:Button <mx:DateChooser /> <s:Button </s:Group> </s:Scroller> </s:Panel>
For more information regarding all of the enhancements in the Flex 4 layouts including better support for transformations, check out the Spark layout documentation.
All of the Spark components use the new text engine in Flash Player 10. These new classes offer low-level support for controlling text metrics, vertical text, typographic elements such as ligatures, and bidirectional text. The Flex 4 SDK has leveraged this functionality in all of the Spark components that use text. For more information on the text primitives and text components provided in Flex 4, see the “Text primitives” section of the Spark Text Primitives spec.
The Spark components also now use the DefineFont4 embedded font format in Flash Player 10 and AIR 1.5. By default, the MX components do not use DefineFont4. This causes some overhead when mixing Spark and MX components in an Application and embedding fonts. If you want to use the same embedded font for all of your components, you will need to add an additional theme compiler argument to your project. With this new theme, both the MX and Spark components will use the same DefineFont4 font engine. You can add this compiler argument by checking an option “Use Flash Text Engine in MX components” in the Properties -> Flex Compiler panel. (see Figure 3).
Figure 3. Allow MX components to use DefineFont4 font engine.
When using text in a Flex 4 application, I recommend using one of Flex 4's three Spark text components. They all use the flash player's new text engine and will provide higher quality text, kerning and rotation for device fonts and bi-directional text. Here are the differences between the available text components in Flex 4.
As in Flex 3, you can compile your application with an additional compiler argument:
-compatibility-version=3.0.0.
This compiler argument will allow your applications to use some of the Flex 3 behavior instead of the new Flex 4 behavior. To get a full list of backwards compatibility changes in Flex 4 that support the use of the
-compatibility-versionargument, see the backwards compatibility document.
Note: You cannot selectively keep a subset of the Flex 4 behavioral changes when invoking Flex 3 compatibility. If you compile with the argument
-compatibility-version=3.0.0, you will get all of the Flex 3 behavior described in the documentation.
Where to go from here
Hopefully, the migration from Flex 3 to the Flex 4 is relatively painless. The framework is designed to be mostly backwards compatible. Plus, once you get acquainted with the new architecture, you'll find that it is more ‘flex'ible! For more info on Flex 4 features, visit the web Help. The Flex 4 Features and Migration Guide would also be a good reference. | https://www.adobe.com/devnet/flex/articles/flex3and4_differences.html | CC-MAIN-2019-09 | refinedweb | 2,573 | 53.41 |
You want to match all section headers in an INI file.
This one is easy. INI section headers appear at the beginning of
a line, and are designated by placing a name within square brackets
(e.g.,
[Section1]). Those rules are
simple to translate into a regex:
^\[[^\]\r\n]+]
There aren’t many parts to this regex, so it’s easy to break down:
The leading ‹
^› matches the position at the beginning of
a line, since the “^ and $ match at line breaks” option is
enabled.
‹
\[› matches a
literal
[ character. It’s
escaped with a backslash to prevent
[ from starting a character
class.
‹
[^\]\r\n]› is
a negated character class that matches any character except
], a carriage return (
\r), or a line feed (
\n). The immediately following ‹
+› quantifier lets the class
match one or more characters, which brings us to....
The trailing ‹
]› matches a literal
] character to end the section header.
There’s no need to escape this character with a backslash because
it does not occur within a character class.
If you only want to find a specific section header, that’s even
easier. The following regex matches the header for a section called
Section1:
^\[Section1]
In this case, the only difference from a plain-text search for “[Section1]” is that the match must ...
No credit card required | https://www.oreilly.com/library/view/regular-expressions-cookbook/9780596802837/ch08s12.html | CC-MAIN-2019-30 | refinedweb | 218 | 63.59 |
Re: "delete file" takes forever to finish
- From: "cquirke (MVP Windows shell/user)" <cquirkenews@xxxxxxxxxxxxxxx>
- Date: Sat, 09 Sep 2006 14:51:18 +0200
On Sat, 2 Sep 2006 10:33:29 +0200, "Sven Pran"
"Bob" <uctraing@xxxxxxxxxxxx> wrote in message
XP-Home, SP2
When I delete a file from my local hard drive it takes "forever" to
finish deleting. We're talking on the or of 30 seconds or more for a
simple single file delete sometimes.
When this hang occurs, I can see the hard drive light spinning away.
There's plenty of space (24gb) free on the drive so it's not a space
issue and the machine is not particularly old and slow (1.4ghz laptop,
year old).
Ideas ?
Several
I do not know it this is still relevant, but when I selected files for
deletion in Windows Explorer the first files went straight away.
However, after a while the delays became longer and longer, it
seemed as if explorer had problems updating the file tree displayed.
That changes the weeighting of my ideas ;-)
I can't say that I have noticed this problem with the current WE.
This isn't just fragmentation - it's more likely something that's
integrated into the shell and thus invoked whenever the folder views
have to be refreshed. It may also be related to the Recycle Bin, if
that is corrupted in some way - test that by holding down Shift
through the delete process, so the Bin is bypassed.
Possible causes...
1) Namespace items (left panel)
Anything on the desktop that is not a shortcut and not a file or
directory, is a CLSID namespace object - e.g. Outlook and IE icons,
and some 3rd-party add-ons too.
Other items that can be slow to refresh are drive letters mapped to
network shares, web folders perhaps, anything that's a peripheral
extension of the system, bad CDs in the optical drive, etc.
A normal hard drive can become slow if it is failing, because of
repeated attempts to read or relocate failing sectors.
2) Folder contents (right panel)
Display of the contents of a folder requires the reading of directory
information (usually fast) and sometimes reading from actual file
data, e.g. to get icons from .EXE etc. (slow and risky). In addition,
other code may be invoked as "handlers" for various types of files.
Finally, both malware and av may scan files as they are listed, and
that can cause slowdown too.
Test folders with few items vs. many, as well as different types of
files. If you find that the presence of a type of file in the view is
what makes things slow, then suspect a bad handler. The best tool to
test for that is Nirsoft's free Shell Integration Viewer.
3) Indexers and thumbnailers
These run underfoot irrespective of what the shell is doing, but may
be invoked when the contents of a folder are changed. For example,
deleting a file may require the corresponding thumbnail or index entry
to be deleted as well.
Less obvious facilities that fall into this category are some av that
maintain integrety data for monitored files, and System Restore, which
also monitors files as they are changed or deleted.
HTH?
------------ ----- --- -- - - - -Drugs are usually safe. Inject? (Y/n)
------------ ----- --- -- - - - -.
- References:
- Re: "delete file" takes forever to finish
- From: Sven Pran
- Prev by Date: Re: AOL Removal
- Next by Date: Re: genuine XP
- Previous by thread: Re: "delete file" takes forever to finish
- Next by thread: Just Testing
- Index(es): | http://www.tech-archive.net/Archive/WinXP/microsoft.public.windowsxp.general/2006-09/msg03012.html | crawl-002 | refinedweb | 590 | 67.89 |
Table Of Contents
Recently I’ve updated my blog from jekyll to Hugo. The process was easy enough, but I did have to change some things in the frontmatter of the content.
A simple Google search was all I needed to find a python parser for YAML frontmatter. Here is how I did it:
Install Python-Frontmatter
Simply run
sudo pip install python-frontmatter
Help us keep writing
- “Whitelist” us in your ad blocker
- Why I removed Google Analytics
- Use our Amazon link
- Download one of our free EBooks
- Become a Patreon!
- More ways to support us
Using Python-Frontmatter
Example 1: Add new values to frontmatter
Once installed, it is easy to use. Let’s see as an example one of the problems I faced. In Jekyll I was the fall back author for all posts that did not have one defined in its frontmatter, but in Hugo I need to specify the author for every post written. To accomplish this, I wrote the following script:
import frontmatter import io from os.path import basename, splitext import glob # Where are the files to modify path = "en/*.markdown" # Loop through all files for fname in glob.glob(path): with io.open(fname, 'r') as f: # Parse file's front matter post = frontmatter.load(f) if post.get('author') == None: post['author'] = "alex" # Save the modified file newfile = io.open(fname, 'w', encoding='utf8') frontmatter.dump(post, newfile) newfile.close()
That’s it!, so simple. Let’s see another example
Example 2: Modify existing values in frontmatter
In this case, I had two frontmatter variables,
mainclass and
categories. I wanted to include the value of
mainclass into
categories, and keep all the current categories of
categories. Here is the script:
for fname in glob.glob(path): with io.open(fname, 'r') as f: post = frontmatter.load(f) # If no categories exists, create one with the value of mainclass if post.get('categories') == None: post['categories'] = [post['mainclass']] print(post['categories']) else: # Categories exists cat = post['categories'] main = post['mainclass'] # If categories contains a single item, ex: categories: 'category1' if type(cat) == str: if cat.lower() != main: cat = [cat, main] else: # If categories is a list, ex: categories: [cat1, cat2] cat = [s.lower() for s in cat] if main in cat == False: cat.append(main) post['categories'] = cat print("%s") % (post['categories']) # Save the file. newfile = io.open(fname, 'w', encoding='utf8') frontmatter.dump(post, newfile) newfile.close() | https://elbauldelprogramador.com/en/how-to-parse-frontmatter-with-python/ | CC-MAIN-2017-34 | refinedweb | 406 | 59.09 |
access - determine accessibility of a file
#include <unistd.h> int access(const char *path, int amode);: R_OK Test for read permission. W_OK Test for write permission. X_OK Test for execute or search permission. F_OK Check existence of file See intro(2) for additional information about "File Access Permission". If any access permissions are to be checked, each will be checked individually, as described in intro(2). If the pro- cess has appropriate privileges, an implementation may indi- cate success for X_OK even if none of the execute file per- mission bits are set.
If the requested access is permitted, access() succeeds and returns 0. Otherwise, -1 is returned and errno is set to indicate the error.
The access() function will fail if: EACCES Permission bits of the file mode do not permit the requested access, or search permission is denied on a component of the path prefix. EFAULT path points to an illegal address. EINTR A signal was caught during the access() function. ELOOP Too many symbolic links were encountered in resolving path. path points to a remote machine and the link to that machine is no longer active. ENOTDIR A component of the path prefix is not a directory. EROFS Write access is requested for a file on a read-only file system. The access() function may fail if: EINVAL The value of the amode argument is invalid. ENAMETOOLONG Pathname resolution of a symbolic link produced an intermediate result whose length exceeds PATH_MAX. ETXTBSY Write access is requested for a pure procedure (shared text) file that is being executed.
Additional values of amode other than the set defined in the description may be valid, for example, if a system has extended access controls.
See attributes(5) for descriptions of the following attri- butes: ____________________________________________________________ | ATTRIBUTE TYPE | ATTRIBUTE VALUE | |_____________________________|_____________________________| | MT-Level | Async-Signal-Safe | |_____________________________|_____________________________|
intro(2), chmod(2), stat(2), attributes(5) | http://man.eitan.ac.il/cgi-bin/man.cgi?section=2&topic=access | CC-MAIN-2020-24 | refinedweb | 316 | 56.96 |
This tutorial begins the discussion of lists and of presenting the ubiquitous Master/Detail relationship in data.
To do this, we’ll revisit the Nerd Dinner application, this time using the Beta Refresh and making sure we focus on best practices, especially the use of MVVM, as we go.
To begin create a new application, using the Windows Phone List Application template. Name it NerdDinnerOne. Update the text properties of the ApplicationTitle and ListTitle to “Nerd Dinner” and “All Dinners” respectively.
Hey! Where’s The oData?
This tutorial was to update the previous version and include a call out to the oData web service for Nerd Dinner. It turns out there is a temporary bug in the Beta (described here) that prevents using oData easily with the simulator, or at all on the phone.
Rather than taking you down a temporary rat-hole, I’d rather finesse that issue for now, and we’ll use the sample data provided by the template (nice, that!).
Press F5, hey! presto! it woiks! Thanks for joining me, Next week….
Creating the Details Page
The next step is to create the details page which we’ll transfer control to, when the user selects an item in the ListBox.
Oh, hey! the details page was created for you by the application, called conveniently enough, DetailsPage.xaml. Also nice.
Open the details page and change MY APPLICATION to Nerd Dinner in the ApplicationName TextBlock but notice that the ListTitle is bound to LineOne of the bound object. That is just right, when we have the oData working, we’lll bind to the name of the dinner.
Okay, time to press F5 again. Now you can click on any entry in the list and see the details. Press the back arrow (bottom left of the device) to return to the list.
The View Model
While the application created a View Model (VM) file for the first page, it did not do so for the details page. Let’s create DetailsPageViewModel.cs in the ViewModel folder. The advantages of doing so are laid out in some detail in my posting MVVM – It’s Not Kool-Aid, but the short answer is that the code is more maintainable and more testable.
Transitioning the Code
The list template creates the list for the master , and the details page for the… details. The code behind for the details page looks like this,
DetailsView.xaml.cs
protected override void OnNavigatedTo(NavigationEventArgs e) { base.OnNavigatedTo(e); string selectedIndex = ""; if ( NavigationContext.QueryString.TryGetValue( "selectedItem", out selectedIndex)) { int index = int.Parse(selectedIndex); DataContext = App.ViewModel.Items[index]; } }
The essence of MVVM is to move as much as possible of the logic out of the view and into the view model. In that spirit we’ll move the logic for obtaining the new data context out of the view and into a static method in the view model (we do need to pass the current navigation context as that is an artifact of the view and we don’t want the vm reaching up into the view where it doesn’t belong. Here is the complete DetailsPageViewManager,
DetailsPageViewManager.cs
using System; using System.Windows.Navigation; namespace NerdDinnerOne.ViewModels { class DetailsPageView { public static ItemViewModel GetDataContext(NavigationContext navContext) { if ( navContext == null) { throw new ArgumentNullException("Navigation Context was null"); } string selectedIndex; if (navContext.QueryString.TryGetValue("selectedItem", out selectedIndex)) { int index = int.Parse(selectedIndex); return App.ViewModel.Items[index]; } else throw new ArgumentException("The selected index did not find an item"); } } }
The codebehind in DetailsPage.xaml.cs now is much simplified,
DetailsView.xaml.cs Revised
protected override void OnNavigatedTo(NavigationEventArgs e) { base.OnNavigatedTo(e); DataContext = ViewModels.DetailsPageView.GetDataContext( this.NavigationContext); }
Pingback: blue ofica
Pingback: Windows Phone 7 资源汇总 | DanceCoder
@toolsche
Actually, it is worse than that; I have to review the code, but I suspect it should have been named DetailsPageViewModel. Argh.
@TMC
It’s the DetailsPageViewManager which just connects the DetailsView with the chosen ItemViewModel of the selected item. Maybe Jesse meant to name it DetailsPageViewModelManager and mixed it up somehow.
Hi Jesse,
On thing is confusing me here – so you have a VM called DetailsPageViewManager but you set the DataContext of the detail page to a different VM (ItemViewModel) – I thought a View should only have 1 VM? (I’m still getting to grips with MVVM!)
not bad .
Pingback: If I want to study all three, finance, business, and accounting..how would I go about getting a master’s? | The Worlds Finance Reviews
So which is it?
Let
Pingback: Developer Resources « Phone 7 | http://jesseliberty.com/2010/08/11/wp7-mini-tutorial-lists-masterdetail/ | CC-MAIN-2019-18 | refinedweb | 755 | 57.06 |
The Common-Header always has the same form and length within one version of MySQL. More...
#include <binlog_event.h>
The Common-Header always has the same form and length within one version of MySQL.
Each event type specifies a format and length of the Post-Header. The length of the Common-Header is the same for all events of the same type.
The binary format of Common-Header is as follows:
Summing up the numbers above, we see that the total size of the common header is 19 bytes.
The following type definition is to be used whenever data is placed and manipulated in a common buffer.
Use this typedef for buffers that contain data containing binary and character data.
Log_event_header constructor.
The first 19 bytes in the header is as follows: +============================================+ | member_variable offset : len | +============================================+ | when.tv_sec 0 : 4 | +--------------------------------------------+ | type_code EVENT_TYPE_OFFSET(4) : 1 | +--------------------------------------------+ | server_id SERVER_ID_OFFSET(5) : 4 | +--------------------------------------------+ | data_written EVENT_LEN_OFFSET(9) : 4 | +--------------------------------------------+ | log_pos LOG_POS_OFFSET(13) : 4 | +--------------------------------------------+ | flags FLAGS_OFFSET(17) : 2 | +--------------------------------------------+ | extra_headers 19 : x-19| +============================================+
The get_is_valid function is related to event specific sanity checks to determine that the object was initialized without errors.
Note that a given event object may be valid at some point (ancestor event type initialization was fine) but be turned invalid in a later stage.
Set if the event object shall be considered valid or not.
Event type extracted from the header.
In the server, it is decoded by read_log_event(), but adding here for complete decoding. | https://dev.mysql.com/doc/dev/mysql-server/latest/classbinary__log_1_1Log__event__header.html | CC-MAIN-2019-30 | refinedweb | 239 | 62.27 |
A Python wrapper for the Fletcher runtime library
Project description
Fletcher runtime library for Python
Fletcher is a framework for integrating FPGA accelerators with Apache Arrow that generates easy-to-use and efficient hardware interfaces allowing hardware addressing via table indices rather than byte addresses. Pyfletcher aims to make the Fletcher runtime library available in Python, allowing any Python programmer to easily interface with Fletcher enabled FPGA images. See the repository for using Fletcher to generate hardware.
Installing
The base pyfletcher library binary wheels can be easily installed on Linux:
pip install pyfletcher
In order to use pyfletcher to interface with FPGA's, please install the correct driver for your platform from the repository. It is recommended to install the echo platform for debugging and testing.
Building from source
Before installing pyfletcher, you should install Cython, numpy and pyarrow.
pip install Cython numpy pyarrow
Install the Fletcher C++ run-time library as follows:
mkdir build cmake .. -DFLETCHER_PYTHON=ON -DPYARROW_DIR=<pyarrow_install_dir> make sudo make install
Here, <pyarrow_install_dir> should be the path to where pyarrow is installed on your system. This can easily be found by running the following code in Python:
import pyarrow as pa print(pa.get_library_dirs())
You can now install pyfletcher.
python setup.py install
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages. | https://pypi.org/project/pyfletcher/ | CC-MAIN-2021-25 | refinedweb | 235 | 52.39 |
Technical Support
On-Line Manuals
RL-ARM User's Guide (MDK v4)
#include <rtx_can.h>
CAN_ERROR CAN_receive (
U32 ctrl, /* CAN Controller */
CAN_msg *msg, /* CAN Message */
U16 timeout); /* Time to Wait */
The CAN_receive function receives a message on the CAN
controller specified by ctrl and copies it into
msg.
The CAN_receive function does not clear hardware message
FIFOs. So, if a message was received prior to invoking
CAN_receive, that message is returned immediately. If the
message FIFO is empty, CAN_receive waits (up to the specified
timeout) for a message to be received.
If a message is not received by the specified time, an error is
returned.
The CAN_receive function executes quickly since all data
transfers use software buffers. Only in situations where the FIFO is
empty is the CAN_receive function delayed.
The CAN_receive function is part of RL-CAN. The prototype
is defined in RTX_CAN.h.
The CAN_receive function returns one of the following
manifest constants.
CAN_send
#include <rtx_can.h>
__task void task_rece_CAN (void) {
CAN_msg msg_buf;
for (;;) {
// Wait to receive a message.
// When the message arrives
// activate LEDs using data[0]
if (CAN_receive (1, &msg_buf, 0) == 0) {
LED_Byte (msg_buf. | https://www.keil.com/support/man/docs/rlarm/rlarm_can_receive.htm | CC-MAIN-2020-34 | refinedweb | 188 | 58.38 |
User talk:Thedoctor80
From RationalWiki
Hi - I'm not completely sure that you understand what we're about. The links above may help. Cheers.--BobSpring is sprung! 13:50, 20 September 2010 (UTC)
- So, you utilize the Larson Theory for the extinction of Dinosaurs? Tyrannis (talk) 17:41, 28 October 2010 (UTC)
Sysoppery[edit]
As you seem to be "mostly harmless", you have been demoted to sysop. This might or might not be useful. 16:53, 29 October 2010 (UTC)
- A reminder: Please sign talk page entries using four tildes like this: ~~~~ or by clicking on the sign button:
, on the toolbar above the edit panel. Thank you.
Wéáśéĺóíď
Methinks it is a Weasel 17:47, 29 October 2010 (UTC)
WTF[edit]
Err... what's this? –SuspectedReplicant retire me 18:05, 3 December 2010 (UTC)
- Oh hang on... I think I get it. Links and quotes would have made it a little easier to understand though. –SuspectedReplicant retire me 18:06, 3 December 2010 (UTC)
List of pages that have been created by some guy called 'thedoctor80'[edit]
You can be uber cool and use this
<dpl> createdby = Thedoctor80 namespace = |Conservapedia|Debate|Essay|Fun|RationalWiki|Recipe </dpl>
gnostic 21:02, 13 January 2011 (UTC) | https://rationalwiki.org/wiki/User_talk:Thedoctor80 | CC-MAIN-2021-39 | refinedweb | 204 | 64.41 |
ok here goes...
**Please note I understand what everyone says about two sites two dags, etc but consider this a challenge... :)
thanks as always for your help...
2 sites
same namespace
dedicated 10 mb line between the two sites
users at both locations
1 exchange server at each site with MB,HT and CAS
would like to setup a two server active/active stretched dag if possible.
Would it be possible to set it up so that if 1 site goes down they other will fail over automatically?
I know it is n/2 +1 to maintain a quorum so should a FSW be on one site an alternate FSW be on the other site to maintain quorum?
I can't be the only person in the world to attempt this. Any guidance would be greatly appreciated..
2 Replies
Just as important as the bandwidth is latency, Microsoft originally recommended no more than 250ms round trip latency, although they later revised it up to 500ms. So you'll want to ensure round trip latency is less than either of those numbers.
As for the File Server Witness, you should place it at the primary failover site, that way if the link goes down, the primary site will have the majority of the cluster "members/witness". If the primary site goes down, then you would have to manually bring up the DAG on the secondary site.
In order for users at the down site to be able to still access email, they would need to access via the Exchange server over the internet rather than the LAN if the point-to-point link goes down.
We are looking at implementing a similar model, the scenario I have is both datacenters have independent internet connections and a dedicated 1Gb link between sites.
If the 1Gb link between the two sites went down and the primary site made it's passive db's active, assuming the secondary site still has there internet connection, would the clients in the second site reconnect to the primary (using OA) without difficulty?? | https://community.spiceworks.com/topic/336818-stretched-active-active-dag | CC-MAIN-2018-51 | refinedweb | 345 | 65.76 |
Love it or hate it, GDPR compliance is now a requirement if you want to collect data from EU citizens. Today we’ll take a look at how we can use the concept of renderless components to implement a basic GDPR consent workflow.
Additionally to the concept of renderless components we’ll use Portal Vue to display a modal dialog.
If you’re curious about the final result, you can take a look at the full code at GitHub or a demo application hosted on Netlify.
Check and require consent for a newsletter form
In our first example, we want to ask the users for their consent to allow us to send them newsletters. Let’s start with building the newsletter form component and enhance it with the possibility to ask for the users consent later.
<template> <div class="o-vertical-spacing"> <template v- <p class="success"> Thank you for subscribing! </p> </template> <template v-else> <h3>Subscribe to our Newsletter!</h3> <input type="email"> <button @ Subscribe </button> </template> </div> </template> <script> export default { name: 'NewsletterForm', data() { return { subscribed: false, }; }, methods: { subscribe() { // In a real application, you'd most // likely trigger an API request here. this.subscribed = true; }, }, }; </script>
The example code, taken from the
NewsletterForm.vue component in
src/components, you can see above, is pretty straightforward: if the user is not subscribed yet, we render an
<input> field and ask them to subscribe. If the user subscribes, a thank you message is rendered instead.
Asking for the users consent
Now that we’ve built a simple newsletter form, we can add the functionality to ask the users for their consent. Your first instinct might be to add some logic directly in the newsletter component to do this but such a solution would not be very reusable.
Renderless components are a perfect solution for problems like this. So let’s build a renderless GDPR consent component.
// src/components/GdprConsentFrame.js export default { props: { provider: { type: Object, }, }, data() { return { error: null, loading: false, }; }, methods: { async checkConsent() { try { this.setLoadingState(); const consentGranted = await this.provider.checkConsent(); if (consentGranted) { // If a consent was found, we emit // the corresponding event. this.$emit('consent-granted'); } else { // If no consent was found, we wan't // to ask the user for their consent. this.$emit('request-consent'); } // Reset the loading state after everything is done. this.loading = false; } catch (error) { this.setErrorState(error); } }, async denyConsent() { // We don't want to persist the information if a user // hasn't given their consent, so we emit the event // to signal that the user has denied their consent. this.$emit('consent-denied'); }, async grantConsent() { try { this.setLoadingState(); const consentGranted = await this.provider.grantConsent(); if (consentGranted) { this.$emit('consent-granted'); } // Reset the loading state after everything is done. this.loading = false; } catch (error) { this.setErrorState(error); } }, setErrorState(error) { this.error = error; this.loading = false; }, setLoadingState() { this.error = null; this.loading = true; }, }, render() { return this.$scopedSlots.default({ // Data error: this.error, loading: this.loading, // Methods checkConsent: this.checkConsent, denyConsent: this.denyConsent, grantConsent: this.grantConsent, }); }, };
The code for the renderless component, you can see above, is slightly more complex. I’ve tried my best to add comments to explain the code. But I think everything becomes easier to understand as soon as we’re using the
GdprConsentFrame component inside of our
NewsletterForm component.
The API provider
In the
GdprConsentFrame component, we use methods on the
provider property to check, deny and grant consents for us. By passing the provider as a property, we’re able to use different providers for certain situations. In our case we want to use an API to persist and check consents for us. But in the next example, we’ll see how we can use the same
GdprConsentFrame to handle the logic for a cookie bar by passing it a cookie provider.
// src/providers/gdpr-api-provider.js import gdprApi from '../services/gdpr-api'; export default { checkConsent() { return gdprApi.checkConsent(); }, grantConsent() { return gdprApi.grantConsent(); }, };
Above you can see the code for our API provider. The
gdprApi service would be the place where you use
XHR,
fetch or a package like
axios to make calls to your GDPR API backend. In our case,
gdprApi is a naive fake implementation of an API which should be sufficient for demo purposes.
The consent modal dialog
The most convenient way of showing users a GDPR consent information form is to use a modal dialog. We’ll use Portal Vue to render a
GdprConsentModal component which asks the user for their consent.
<template> <app-modal @ <div class="o-content"> <h2>GDPR Information</h2> <p> We want to do a lot of stuff with your data, please give us your consent to do so, thank you very much! </p> </div> </app-modal> </template> <script> import AppModal from './AppModal.vue'; export default { name: 'GdprConsentModal', components: { AppModal, }, }; </script>
As you can see in the code snippet above, this is a very simple implementation of a GDPR consent form but it should be enough to give you an idea of how this could be enhanced for a real world solution.
The
AppModal component which we’re using as a wrapper, is a very, very naive implementation of a modal dialog. You should absolutely use something more sophisticated in your own application. This implementation is not accessible at all!
<template> <portal to="modal"> <div class="AppModal"> <div class="AppModal__inner"> <button class="AppModal__close" @ X </button> <slot/> <div class="AppModal__actions"> <button @ Decline </button> <button @ Accept </button> </div> </div> </div> </portal> </template> <script> // Naive, not accesible (!) modal implementation. // Don't use this in production! export default { name: 'AppModal', }; </script>
I can’t stress this enough: this is a very simple implementation for demonstration purposes, if you implement this yourself, keep accessibility in mind.
Put it all together
Now we’ve set up all the parts we need and we’re ready to put everything together to make our simple newsletter form component, we’ve created at the beginning of this article, GDPR compliant.
<template> - <div class="o-vertical-spacing"> + <gdpr-consent-frame + : <p class="success"> Thank you for subscribing! </p> </template> <template v-else> <h3>Subscribe to our Newsletter!</h3> <input type="email"> - <button @ - Subscribe + <button @ + {{ loading ? 'Loading ...' : 'Subscribe' }} </button> + <p + v-if="error" + class="error" + > + There was an error, please try again! + </p> </template> + + <gdpr-consent-modal + v-if="showConsentModal" + @deny-consent="denyConsent" + @grant-consent="grantConsent" + /> </div> + </gdpr-consent-frame> </template> <script> +import gdprApiProvider from '../providers/gdpr-api-provider'; + +import GdprConsentFrame from './GdprConsentFrame'; +import GdprConsentModal from './GdprConsentModal.vue'; + export default { name: 'NewsletterForm', + components: { + GdprConsentFrame, + GdprConsentModal, + }, data() { return { + showConsentModal: false, subscribed: false, }; }, + created() { + this.gdprApiProvider = gdprApiProvider; + }, methods: { subscribe() { + // We hide the modal because the user must + // have given their consent at this point. + this.showConsentModal = false; // In a real application, you'd most // likely trigger an API request here. this.subscribed = true;
Above you can see that we’re now using the
GdprConsentFrame component as a wrapper around our
NewsletterForm component which we’ve created earlier. Via the
slot-scope property, we have access to the data and methods provided by the
GdprConsentFrame. To update the state of the
NewsletterForm component, we react to certain events emitted by the wrapper component. Most importantly, we listen to a
consent-granted event on which we subscribe the user to our newsletter.
Check and require consent to save cookies
Because we’ve implemented our
GdprConsentFrame in a way that it consumes a provider instead of directly accessing the API, we’re now able to reuse the component, to build a simple cookie bar component.
But there is still one minor thing we must add to our
GdprConsentFrame component to make it possible to power a cookie bar.
export default { props: { + immediate: { + default: false, + type: Boolean, + }, provider: { type: Object, }, }, data() { return { error: null, loading: false, }; }, + created() { + if (this.immediate) this.checkConsent(); + }, methods: { async checkConsent() { try {
By adding a new
immediate property and checking the consent status immediately if it is set, we make it easier to show the cookie bar as soon as the page is loaded.
The cookie bar component
Now let’s implement a very simple cookie bar which is reusing the
GdprConsentFrame component.
<template> <gdpr-consent-frame : <div v- <p> Please give us your consent to use cookies, thanks! </p> <button @ {{ loading ? 'Loading ...' : 'Accept' }} </button> <p v- There was an error, please try again! </p> </div> </gdpr-consent-frame> </template> <script> import gdprCookieProvider from '../providers/gdpr-cookie-provider'; import GdprConsentFrame from './GdprConsentFrame'; export default { name: 'CookieBar', components: { GdprConsentFrame, }, data() { return { visible: false, }; }, created() { this.gdprCookieProvider = gdprCookieProvider; }, }; </script>
In the code snippet above, you can see that we use the
immediate property on the
GdprConsentFrame component to trigger a consent check as soon as the component is initialized. If the user has not given their consent yet, the
request-consent event is triggered and we update the
visible property to render the cookie bar component. As soon as the user has given their consent, the cookie bar is hidden.
In the following code snippet, you can see the cookie provider which we’re using to persist and retrieve the cookie bar consent status.
import Cookies from 'js-cookie'; const COOKIE_NAME = 'eu_cookie'; export default { checkConsent() { return Cookies.get(COOKIE_NAME); }, grantConsent() { Cookies.set(COOKIE_NAME, true, { expires: 30 }); return true; }, };
Wrapping it up
The concept of renderless components is a very powerful one. As we’ve seen with this example, we can build flexible and reusable components that way. By simply using a different provider, we’re able to use the same logic for handling the GDPR consent for a newsletter, for a EU cookie bar.
GDPR compliance might be a PITA, but we can do ourself a favor by implementing it in a generic way, which we can reuse across our application. | https://markus.oberlehner.net/blog/implementing-a-gdpr-consent-workflow-with-vue/ | CC-MAIN-2019-47 | refinedweb | 1,618 | 56.25 |
Thor: Comparison of Myths and Comic Dec 2017 come in all varieties, shapes, and forms, but behind each superhero lies a secret to why they were created. The reasons for creation range from events that previously occurred in history to recent changes in today’s society. Comic book superheroes were indeed influenced by history, but the comic book superheroes also continually influence history itself. This reciprocal influence continues to affect the generations of comic book fans for years on end.
Comic book creators have been known for using a strategy to create characters which tend to resemble infamous gods to separate the common ideal mortal heroes from the indestructible immortals. By using this strategy, comic book creators are able to give their characters a fierce outer shell with a scholarly uplift (Reynolds 53). With the creation of the Mighty Thor comic book character in 1962, Lee and Thomas used this strategy perfectly (54). Asgardian characters were just ready-made superheroes waiting to be transformed into the comic-book world (57). Being named one of the most unusual creations in comic book history, Thor truly defined “…the first successful attempt to harness existing mythology on a large scale to construct the mise en scene of a superhero” (54).
In relation to history, Thor was the son of Odin, the universal father, and Frigga queen of the gods. His name dates back to ancient Norse Mythology where he was known for his incredible strength and enormous size. This continually amazed the gods (Guerber 59). Recognized as the god of thunder with a magical hammer, he was “honoured as the highest god in Norway” (60). Thor was always right in the middle of action when it came to battling against raging monsters, deadly giants, and prehistoric forces. There are three main properties that define Thor’s character when he becomes involved in battle. The first is his infamous hammer Miollnir which symbolizes the crushing skulls of monsters and giants. The second is his belt of strength which when buckled, makes his godlike powers multiply. Last are his iron gloves which he must wear in order to swing his hammer (Page 40).
There is a direct correlation between the mythical Thor and the comic-book character the Mighty Thor. From both the physical aspects and the characteristics of their personalities, Norse legends have heavily influenced the modern comic-book superheroes (Knowles 29). The Mighty Thor is visualized as a tall robust man, with strawberry blonde locks, and blue eyes. He also speaks in a very distinct old English accent. An example is when the mighty Thor proclaims, “Thy work is done, father! Let it be known far and wide that the full might of Mjolnir is restored” (0000). Whereas the mythical Thor is closely described “…as a man in his prime, tall and well formed, with muscular limbs and bristling red hair and beard…(Guerber 60).” Both characters also share the same love of being involved in battle, and depend on their mighty hammer. Although, the mythical Thor depends on his hammer for security and power, the Mighty Thor uses his hammer to transform into Don Blake and back into Thor (Page 13). The mythical Thor was also known for his outlandish and dangerous outrages which eventually became uncontrollable. Consequently, his mother sent him away from home and placed him in the care of Vingir and Hlora. This is where his other names “Vingthor” and “Hlorridi” derived from (Guerber 59). Much like the mythical Thor being sent away from his homeland, the Mighty Thor was sent away from Asgard to earth as a punishment from his father because of his arrogance (Reynolds 54). From these comparisons one can obviously conclude that the artist, Jack Kirby, was truly fascinated with Norse legends. Since his childhood, Norse legends formed the basis for his imagination and gave him great inspiration when it came to graphically representing the Mighty Thor on paper (Misiroglu 599).
History has indeed influenced the creation of the Mighty Thor, but another question should be raised. Has the Mighty Thor influenced history? With the debut of the Mighty Thor in 1962, the hippie era was on the rise. Long hair, bell bottom jeans, and tie-die were some of the trends getting ready to appear. The country was also getting ready to be faced with the Vietnam turmoil which would greatly influence comic-book creators and their story-lines to come. The Mighty Thor has always been known for fighting out against powerful Communists and mad scientists (Knowles 191). Throughout most of the Marvel comic-books, villains were represented as Communists. Some superheroes would actually have to travel straight into the heart of the Viet-Cong for battle. In the famous 1965 series, Journey into the Mystery, the Mighty Thor was found in South Vietnam assisting a group of anti-communist peasants. Both the peasants and Thor were taking on the merciless Viet Cong military. Along the way, Thor also liberated a Vietnamese family from Communism where he promised a village he would return (Wright 222). With the Vietnam conflict raging among citizens all over the United States, young adolescents were getting ready to burst out. The Mighty Thor’s heavy anti-communism propaganda, influenced readers of all ages. One way Thor truly influenced the youth culture was actually unintentional towards young men. Preceding a couple of years after the Might Thor’s debut, his long golden hair would become a fashionable trend. This long hair then became a symbol of rebellion and rage for young people all over the nation (213). The hippie era had begun.
Cite This Work
To export a reference to this article please select a referencing stye below: | https://www.ukessays.com/essays/english/mighty-thor-superheroes.php | CC-MAIN-2019-04 | refinedweb | 949 | 61.36 |
#include <db.h>
int DB_ENV->set_flags(DB_ENV *dbenv, u_int32_t flags, int onoff);
The flags value must be set to 0 or by bitwise inclusively OR'ing together one or more of the following values: If onoff is set to zero, the specified flags are cleared; otherwise they are set.
The number of transactions potentially at risk is governed by how often the log is checkpointed (see db_checkpoint for more information) and how many log updates can fit into the log buffer.
The DB_ENV->set_flags function returns a non-zero error value on failure and 0 on success.
The database environment's flag values may also be set using the environment's DB_CONFIG file. The syntax of the entry in that file is a single line with the string "set_flags", one or more whitespace characters, and the interface flag argument as a string; for example, "set_flags DB_TXN_NOSYNC". Because the DB_CONFIG file is read when the database environment is opened, it will silently overrule configuration done before that time.
The DB_ENV->set_flags function may fail and return a non-zero error for the following conditions:
The DB_ENV->set_flags function may fail and return a non-zero error for errors specified for other Berkeley DB and C library or system functions. If a catastrophic error has occurred, the DB_ENV->set_flags function may fail and return DB_RUNRECOVERY, in which case all subsequent Berkeley DB calls will fail in the same way. | http://pybsddb.sourceforge.net/api_c/env_set_flags.html | crawl-001 | refinedweb | 237 | 51.52 |
Sometimes during text processing you need to find out words containing certain characters. The logic of this computation is simple, but the code is difficult to write using the regular expression because the order of the characters is flexible. Moreover, the method is inefficient. You may do better to write the program by yourself, but the problem is that high-level languages don’t support set operations and this also makes the coding not easy. By contrast, esProc can parse a string dynamically and thus can match specific characters more easily with simple and intuitive code. Let’s look at how it works through the following example.
Find out words containing e, a, c from the following Sample.txt. Some of the original data are as follows:
esProc code for doing the task:
A1=file("e:\\sample.txt").read()
This line of code reads the file into the memory as a big string, as shown below:
Besides, read function, used with @n option, can read the data by lines. For example, the result of executing file("e:\\sampleB.txt").read@n() is as follows:
import function can be used if the data are structured. To import, for example, a file with tab being the separator and the first row being the column names, the code can be file("e:\\sampleC.txt").import@t(). The result is as follows:
This line of code splits the big string into multiple words and creates a set with them. The words function can filter away the numbers and signs automatically and select only the alphabetic characters. Select only the numbers by adding @d option and both the words and the numbers by adding @a option. The result of A2 is as follows:
A3=A2.(~.array(""))
This line of code splits each word in A2 into characters. “~” represents each member of the set (word); there is no space within the double quotation marks (""). When the code is executed, A3 holds the subsets of a set, as shown below:
A4=A3.select(set==set^~)
This line of code selects the words containing set’s characters. select function is used to execute a query statement, in which “~” represents A3’s member for the current computation, operator “^” represents the intersection and “set==set^~” represents that if the intersection of set and the current member is equal to set itself, the current member is an eligible word according to the query condition. “==” is a comparison operator, operators of the same kind also include “!=” (not equal to), “<” (less than) and “>=” (greater than or equal to). “^” is a binary operator representing intersection, other operators of the same kind include “&” (union) and “\” (difference).
Suppose the value of parameter set is ["e","a","c"], then the above line of code is equal to A3.select(["e","a","c"]==["e","a","c"]^~). Once it is executed, the result is as follows:
It can be seen that both “complicated” and “Rebecca” contain the three characters: e, a, c.
Besides by computing the intersection, the operation can be realized through position query. The corresponding code is A3.select(~.pos(set)). pos function is used to locate members of set in ~ (also a set). If all of them can be found, then return a sequence consisting of their sequence numbers (that is true); if not found, then return null (that is false).
After A4 finds out the words satisfying the query condition, join the characters of each set, the word in fact, together using the following code:
A5=A4.(~.conj@s())
conj function can concatenate multiple sets together to form a single set. When used with @s option, it can combine all the members of a set into a string. The final result of this example is as follows:
The above step-by-step computation is intuitive and easy to understand. Actually you can omit the step for splitting the words up and then again concatenating every character, thus the code will become a single line:
file("e:\\sample.txt").read().words().select(set==set ^ ~.array("")) | http://datakeyword.blogspot.com/2015/05/esproc-improves-text-processing.html | CC-MAIN-2020-34 | refinedweb | 669 | 53.61 |
One of the main request of many customers is to use MS Excel spreadsheet as data output for reports and analysis.
Most of the standard SAP components (such as ABAP ALV, WebDynpro ALV, System menu, etc.) provide the option to export data in MS Excel 2003 or in many other MS Excel compatible file formats (csv, plain text, mhtml and so on).
What are the limits? Most of them depend on SAPGui or Web Dynpro and are not available for example in case you want to send it as eMail attachment.
Community is really active, bloggers tried to create workbooks using the Excel OLE and ABAP – Create fancy reports, this is a great approach but OLE is too much SAPGui dependent:
- Excel cannot be created in a not dialog process
- Excel cannot be used as email attachment (without some dirty trick)
- Is platform dependent
To avoid some limitations and create spreadsheet with a professional look and feel Sergio Ferrari proposed in 2006 a Downloading data into Excel with Format Options (from SAP Web Applications):create an HTML file and open in Excel.
What are the limits again?
- Only one sheet for each workbook
- No graphs
- No conditional formatting
- HTML extension is not associated by default with MS Excel
- No excel advanced features
The technology
Talking with Sergio some days ago about MS Excel and ABAP I had an idea MS Excel extensions are basically cab files with several xlm files. No binary, no proprietary code only zipped plain xml!
The Office Open XML format is a full fidelity (all features of the product are supported) file format for Excel2007, and it is the default file format that Excel uses to save newfiles. These files are composed of several XML parts, all bundled within Code Exchange.
New features will came in next releases; I created a roadmap on Google Code and on Wave. I have also scheduled an xlsx2abap project but this will be a really nice to have right now.
Thanks to Sergio Ferrari and Ferrari’s Team for their support.
SCN references:
- Spreadsheet integration – which approach for which SAP technology by SergioFerrari.
- Downloading data into Excel with Format Options (from SAP Web Applications) by SergioFerrari.
- Excel OLE and ABAP – Create fancy reports by Alvaro Tejada Galindo
- Using WD ABAP ALV export – the hacked way by Chris Paine
- xlsx2abap – Read and edit your Excel files from ABAP by Ivan Femia
- abap2xlsx – I’m no longer a baby, I grow up and now I’m a fully featured tool by Ivan Femia
- abap2xlsx team has a present for you… by Ivan Femia
External links:
For support follow these best practices:
- For any question related to abap2xlsx demo, use cases, explanation create a new discussion in SCN Open Source
- For reporting a bug please open a issue on GitHub Issues · ivanfemia/abap2xlsx · GitHub
Supported releases:
As from SAP WebAS 7.0
Is there a way to disable the Excel menu (specifically "File") when displaying an Excel workbook on-line via ABAP2XLSX?
-David
Is this possible without a Macro?
Using a Macro you should follow the example in this video [embed width="425" height="350"][/embed]
Thanks Ivan. I will look into this.
Very Useful..
Hi Ivan,
I have a test program that shows an issue I'm facing. I think it is a bug in abap2xlsx but may be I'm not using it right.
Where can I submit my test program? Can I open a ticket somewhere?
Regards,
Edward
EDward,
you can create a new ticket on GIThub if you think is a bug.
For discussion about the usage I would suggest to open a discussion in SCN
Best
Ivan
I am not able, to update the framework: i have installed an older version (?) and want's to overwrite with the newest nugg: ABAP2XLSX_V_7_0.nugg. I choose the option: overwrite originals. i get the message: Start import .... ouch, your pants are on fire..better go get help.
What's going wrong. I use SAPlink 0.1.4.
Any suggestions?
I would suggest that you delete all objects existing and related to ABAP2XLSX and try again. That can normally be done easily in SE80 when you have everything in one package. First delete all classes and reports and then the dictionary objects.
What you should check alsi is that you have the latest SAPlink version from the build directory in the SVN repo at.
But that's not a state-of-the-art upgrade :-(. 0.1.4 is the latest no-beta-version?
SAPlink is provides only as a daily build. Take the latest and greatest that should have the least bugs.
Hi Ivan,
Thank you so much for this.
However, I am trying hard to find where to get xlsx2abap from without success 🙁
Could someone help me please?
Thank you!
Best,
Bruno
Based on google search, project home is:
On right side you can see download zip option.
Download and extract that zip file, and locate ABAP2XLSX_V_7_0.nugg file.
This is the nugget file that you need to install, using latest SAPLink version.
For installing SAPLink, similar search can be done.
Hi Manish,
Thanks for replying. I did find that, but I am looking for the opposite, xlsx2abap, and not abap2xlsx, or is it included in the same package?
Thank you!
Best,
Bruno
Hi Bruno,
the reader is also included in the package. Check report ZDEMO_EXCEL15.
Ah great!
Thanks Uwe.
Best!
Bruno
Hi all,
I'm trying to run the angry birds example. I've had some trouble with methods ZIF_EXCEL_BOOK_PROTECTION~INITIALIZE not being implemented, but I implemented them empty as I saw someone saying this would fix it, but then I ran into the method ZIF_EXCEL_WRITER~WRITE_FILE not being implemented in class ZCL_EXCEL_WRITER_2007, and implementing this empty "fixes it", but nothing comes from the ZANGRY_BIRDS program.
Can anyone help me with this?
Thank you!
Best,
Bruno
Hi Bruno,
this is a known issue with SAPLink. To solve the issue import the abap2xlsx nugget again.
Best
Ivan
Perfect, it's working now.
Thanks so much Ivan, and I'm sorry if this question had been asked, I swear to God I searched before I asked but maybe I didn't look deep enough in the replies... and I'm also guessing that the methods that don't get implemented are random, so that doesn't help 🙁
Thanks again!
Best,
Bruno
You're welcome 🙂
Wow! I just stumbled across this project as it was mentioned on the famous german 'Tricktresor' website.
It took quite a while to get it up and running but the results are really worth it.
Although there are plenty of demo programs included, I just wanted to know if there is a plain documentation of all methods and attributes.
Many thanks to all the contributors!
Thank you Karl.
Unfortunately, there isn't an API doc... There is a plan to add comment in the code in order to use abap2doc project, but it is not yet started.
So far we tried to create a demo report for most of the features of abap2xlsx in order to give you the ability to "copy" the standard way.
Any suggestion is welcomed
Ivan
Hi Ivan,
When looking for a way to create Excel from SAP (in background) for a customer request I got aware of abap2xls. I was positively surprised about the feature set and how well the samples work. Excellent work.
Because we consider to use this for a customer project I have two questions:
It is under Apache License so we could use, distribute and even sell it as it is or modified free of charge? When doing this we have to add copyright and NOTICE information.
When installing this at customer systems there could be conflicts between names of objects used in this projects and objects which already exist in the customer system. I was thinking of creating a copy in our namespace to avoid these conflicts. Doing this makes it obviously harder to apply changes in your source and to transfer any changes made in our copy back. Do you have any recommendations or thoughts on this?
Regards,
Lars
Hello Lars,
Yes, but the unmodified part of the package must still be under Apache License. The modified part can be under a license of your choice and must be stated in the NOTICE file.
Regarding the namespace:
The ABAP2XLSX package contains many (really many!) objects. Renaming these objects would be a huge work and error-prone. I think the better choice would be a test whether there is a conflict (you can list the objects with SAPLINK).
Uwe gave you the right explanation on the licence.
I'm planning to move it to the /CEX/ namespace, but it needs time.
You can try to see the object in the nugg with SAPlink and also try to import the nugg without the overwrite option in SAPlink.
So far in several installations that I did no conflicts were raised.
Unfortunately there are customers that have issues installing a Namespace. so we have to carefully think avout if we want to move. For our Server side component of SAPlink for ABAP in Eclipse I think about removing the /CEX/ Namespace.
Thanks Gregor Wolf for your feedback...
Lars, this is the official statement on the Apache License and Distribution FAQ
Hello Gregor + Ivan,
it's not the problem with the installation of the namespace, but the maintanance of the objects. If you install the namespace in a customers system, you only have the "Repair" license and not the "Developer" license.
So: please don't change ABAP2XLS to /CEX/ (and yes Gergor, it would be great, if we can get rid of /CEX/ in SAPlink for ADT).
Uwe,
there are pro and contra on both the side.
So far I never had the need of /CEX/ namespace or renaming of the objects, but there should be a better way to organize the import of an external project into your ABAP system.
Thanks for the fast reply.
Regarding the namespace:
I agree, that renaming is not a good option. I was thinking of modifing SAPLINK to add a prefix to the objects and modify the code accordingly, but this isn't fully thought through.
Using a namespace for ABAP development is something we do for years without problems (we deliver our stuff with transports). So I would vote for /CEX/.
Many thanks,
Lars
You can easily change the name of the classes editing the nugg file.
Hi Ivan,
I have import all the objects into my system by using of ABAP2XLSX_V_7_0.nugg. When I try to run program ZDEMO_EXCEL. The system run a dump. And I run ST22,
It tells me:
"An attempt was made in class "ZCL_EXCEL" to call non-implemented method
"ZIF_EXCEL_BOOK_PROTECTION~INITIALIZE"."
And there are a lot of same problems.
And then I click into those methods and reactive this class. And It's ok then. But the size of all generated file is 0.
I think it could be related with the reimplement of the method are all null. So how can I deal with it?
eg:
Best regards,
Terry
Reimport everything. It is a known issue with ZSAPLINK.
Cheers,
Bruno
Hi Bruno,
Thanks! It really works now. 🙂
Best regards,
Terry
Most welcome, I had the same problem 🙂
Cheers,
Bruno
This is an issue with SAPLink.
Please refer to the installation guide
Great Job Ivan Femia!!
I'm trying to create a Excel with Background Image on the Excel Sheet. Is there a way to set that? Any input on this is highly appreciated:
I was looking for a method to set Background Image, but couldnt find. So, tried with a Template file containing Background Image. But, output file didnt contain Background Image.
I tried following -
CREATE OBJECT lo_excel.
CREATE OBJECT lo_excel_reader TYPE ZCL_EXCEL_READER_2007.
lo_excel = lo_excel_reader->LOAD_FILE( I_FILENAME = 'C:\Users\PPSAP\Desktop\ExcelDraftTemplate.xlsx'
I_FROM_APPLSERVER = ' ' ).
CREATE OBJECT lo_excel_writer TYPE zcl_excel_writer_2007.
lv_file = lo_excel_writer->write_file( lo_excel ).
lt_file_tab = cl_bcs_convert=>xstring_to_solix( iv_xstring = lv_file ).
lv_bytecount = xstrlen( lv_file ).
cl_gui_frontend_services=>gui_download( EXPORTING bin_filesize = lv_bytecount
filename = lv_full_path
filetype = 'BIN'
CHANGING data_tab = lt_file_tab ).
" Newly created file does not contain Background Image and below is what ExcelDraftTemplate.xlsx conbtains.
Thank you!!
PP.SAP
Hi
we support images, see for example zdemo_excel16 and zdemo_excel38.
Excel watermark are not yet implemented.
Best
Ivan
Hi Ivan
Thank you so much for the quick response.
Tool is absolutely great! It has majority of the functionalities that we normally use.
Looking forward to additions of such features!
thank you
PP
I was trying to get it from .nug file, I am not able to do so as my system is not able to handle such a big internal table and giving short dump.
Can any one please provide me the code.
Also if any one is having Idea if we can send the .XLSX attahment in the mail as written in note 1459896 but that is also not working.
Please can anyone tell me.
Thanks
Willi
Dear Willi,
if you encounter a SAPlink error then please file a detailed Bug description at SAPlink Project. But please try to talk before with your basis admin if some parameters can be adjusted.
For the other problem I think you should check out the sample reports coming with abap2xlsx. They also have the send as attachment functionality.
Best regards
Gregor
Hi Gregor,
Is it possible for someone to just post the code for sending mail as XLSX, I am not able to run nugg file as it is too big and my system is giving dump.
Please if it is possible for someone please do I need it ASAP wery much required.
Thanks
HI Will,
have you installed abap2xlsx in your system?
If so, the demo reports are already there.
Ivan
HI Ivan,
How to install abap2xlsx , I have not done so can you please guide me.
Thanks
Willi
Please read the Installation Guide linked from the abap2xlsx homepage
I have gone through the Installation guide but as the nugget file is big it is giving me dump while importing the file.
as I sad before: ask your basis admin to fix the limit of split the file into several ones. It is just XML.
Hi Ivan
just to add to the comments already made that this is superb stuff ... really easy to use, lots of functions and feature. Just what I needed and I have that warm "I've re-used code" glow 🙂
nice one and also thanks to the SAPLink team
regards
Ian
I am not able to open the file in SOST it shows below error.
try.
lo_send_request = cl_bcs=>create_persistent( ).
* -------- create and set document with attachment --------------- *
* create document from internal table with text
append 'Hello world!' to lt_doc_text.
CONCATENATE text-002 lc_tab
text-003 lc_tab
text-004 lc_crlf
INTO l_string .
TRY.
cl_bcs_convert=>string_to_soli(
EXPORTING
iv_string = l_string
RECEIVING
et_soli = lit_soli_tab
).
CALL METHOD cl_bcs_convert=>string_to_xstring
EXPORTING
iv_string = l_string
iv_codepage = '4103'
iv_add_bom = 'X'
receiving
ev_xstring = lv_string.
CATCH cx_bcs.
MESSAGE e445(so).
ENDTRY.
lo_document = cl_document_bcs=>create_document( i_type = 'RAW'
i_text = lt_doc_text
* i_length = '12'
i_subject = 'Main Document' ).
append 'This is an attachment' to lt_att_text.
* four character file extension '.text' is set
lv_filename = 'AttachmentFilename.xlsx'.
concatenate '&SO_FILENAME=' lv_filename into lv_text_line.
append lv_text_line to lt_att_head.
CALL METHOD cl_bcs_convert=>xstring_to_solix
EXPORTING
iv_xstring = lv_string
receiving
et_solix = binary_content
.
l_legth = xstrlen( lv_string ).
lv_size = l_legth.
lo_document->add_attachment( exporting i_attachment_type = 'XLS'
i_attachment_subject = lv_filename
i_attachment_size = lv_size
i_att_content_hex = binary_content
i_attachment_header = lt_att_head ).
* add document object to send request
lo_send_request->set_document( lo_document ).
* create recipient object
g_recipient = cl_cam_address_bcs=>create_internet_address( 'test@test.com' ).
TRY.
CALL METHOD lo_send_request->add_recipient
EXPORTING
i_recipient = g_recipient
i_express = 'X'.
CATCH cx_send_req_bcs .
ENDTRY.
* ---------- send document ---------------------------------------
g_sent_to_all = lo_send_request->send( i_with_error_screen = 'X' ).
COMMIT WORK.
I also have posted it as question.
Sending .xlsx file from ABAP
I believe expert would help me.
Thanks
Willi
Dear Willi,
as said before: Install abap2xlsx and with all the examples you will have a working example how to correctly add an .xlsx file to an email.
Best regards
Gregor
Hi Gregor,
I am not able to activate all the object at once it showing some type of error or other, Can you help.
Thanks
WIlli
Hi All
Perhaps not the correct place to ask this but I am using ABAP2XLSX to create XLSX files to send via email using BCS and this works perfectly
However the attachment type parameter in cl_document_bcs->add_attachment which feeds through to FM SO_ATTACHMENT_INSERT_API1 allows only a 3 char field with domain SO_OBJ_TP so the attachment arrives as <myfile.xls> not <myfile.xlsx> 😥
has anyone any suggestions? Repair SAP to CHAR(4) ?
regards
Ian
Please check out SAP Note 1459896 - BCS: Support for four-digit file name extensions.
sweet, this trick works perfectly ... many thanks !
🙂
Hi Ian,
I agree with you, I went through the same case and used note 1459896 as suggested by Gregor again I am not able to open it in SOST.
Please can you try what is written in this note and see if it works for you.
Thanks
Willi
Hi Willi
this works for me. NB in SOST I can see the attachment just as a name "ATT" w/o extension and a type of XLS but the email shows up correctly in my inbox as "ATT.XLSX" and Excel sees this correctly as an XML CAB file.
Seriously cool software ...
regards
Ian
Hi Ian,
Gr8 that this trick is working for someone, can you please post your code as I used the same trick but I am not able to open it in SOST and my BASIS doesn't allow me to send mails to external system from development environment.
You help is highly appreciated.
Thanks
Willi
Hi Willi, this my code, its not complicated ... the form generate_xlsx fills in cells with format/style for my application in the returned class instance lcl_excel. The key bit the note details is to fill in the filename REQUEST.XLSX in class parameter i_attachment_header - its hardcoded at present as we are still prototyping ... hope this helps
may I ask one more question wree you able to open it in SOST.
Also one more question I am not able to actiavate all the objects imported from .nugg file can you please help with some trick or if I am missing something.
Thanks
yes, I can open in SOST.
The NUGG file objects have some errors initially just because the objects are a bit "chicken" and "egg", referring to objects not yet activated. This is to be expected, you get this in any development of course.
activate all objects ignoring errors and all will be well
Yes its gr8 it works .
I have a question what exactly is the key to send in XLSX format, for sure it is not just changing the header table like
lv_filename = 'AttachmentFilename.xlsx'.
CONCATENATE '&SO_FILENAME=' lv_filename INTO lv_text_line.
APPEND lv_text_line TO lt_att_head.
I believe someone will provide some insight.
Thanks
Willi
no, this has no effect on the actual file contents ... if you want a true XLSX then use Ivan's class library. this code fragment means that the file attachment gets sent with the correct name. without this, the file is a cab zip of xml but labelled myfile.xls and Excel warns you the file extension does not match the file and may be corrupt. still works but not great user experience ...
Hi Ian,
I understand that below code segment is for sending the xlsx attachment type but still
if I do not use the library provided by Ivan then again it doesnot open that means creating a CAB XML file from internal table is also the key when you want to send XLSX file.
correct me if I am wrong.
lv_filename = 'AttachmentFilename.xlsx'.
CONCATENATE '&SO_FILENAME=' lv_filename INTO lv_text_line.
APPEND lv_text_line TO lt_att_head.
Thanks
Willi
Dear Markus,
please don't crosspost issues. You've raised the issue already at INSTALLING: Could not create WB object from OCN (type), (name), ZCL_EXCEL (encl.) · Issue #335 · ivanfemia/abap2xlsx · …
Best regards
Gregor
Hi Gregor Wolf,
sorry for the crosspost. I deleted this post here.
Do you have any suggestions to solve this problem or where this problem comes from?
Best regards,
Markus
Hello,
The provided codes are completely free? Can I implement it in our customer system?
Thank you in advance,
Tom
Dear Tom,
the provided code is licensed under Apache 2.0 (). So if your company allows the use of this license, then nothing should hinder you to use abap2xlsx in your customer system.
Best regards
Gregor
Hi @tom dupond
Yes, you can implement without any restriction in your customer system 🙂
Ok thank you.
With this tool, is it possible to open an xlsx file (template) and change it with data in the system (replace variable by values: single variable and table content)?
Yes, please install it and have a look at the examples.
I imported the transport and did not found an example for my requirement (open an xml file and change...)
My template:
Logo in the Header and page number in the footer
I want to read this template and change the data in red (customer...) and also add lines with data (DE, FR lines..)
Is it possible with your tool. If yes which demo programme can I take?
Thank you in advance
Please search the Reports ZDEMO_EXCEL* for read. But I think for this simple form you should generate it directly in ABAP2XLSX. Images are supported.
Yes, I did this recently and find that generating a new xlsx with the data in it is the most strait forward. If you really need to fill fields in a template, you either have to know the cell locations that you will fill, or you have to loop through all the cells looking for a particular pattern. Use worksheet->get_cell method and if it contains the pattern then you can use worksheet->set_cell method to fill it.
I agree with you to generate the document with ABAP2XLSX but I need a header with a logo and a footer with an incremented page number(will be in all pages).
Is this possible with the code to set the header or the footer? With worksheet->set_cell ?
I found ZDEMO_EXCEL4 which contain code for header and footer bur I got an error 🙁
Line 3: "Field "C_SELECTED" is unknown. It is neither in one of the specified"
Line 65 "Method "SET_HEADER_FOOTER" is unknown or PROTECTED or PRIVATE."
...
Why these objects does not exist? Do I install additional transport?
Did you activate every object (here interface ZIF_EXCEL_SHEET_PROPERTIES and class ZCL_EXCEL_SHEET_SETUP) ?
Yes there are active. And I imported the objects by transport, that means all objects were already active...
Code in report ZDEMO_EXCEL4:
lo_worksheet->sheet_setup->set_header_footer( ip_odd_header = ls_header
ip_odd_footer = ls_footer ).
I did not found "sheet_setup"
Please install the latest version of abap2xlsx using SAPlink. The version you can get by transport is not up-to-date.
I'll update the nugg and transport ASAP... I was in vacation for a while 🙂
I don't have the autorization to instal SAPlink in the customer system 🙁 I can only work with the transports.
Do you have access to LSMW? Or debugging? If you have access to any of these things, you have SAP_ALL 😉
No, I don't have the authorization 😥
The best way is to have a transport up to date but still no response from Ivan.
I'm not sure if I understand Tom...
You must have authorization somewhere! "Install" SAPLink where you have authorization, "install" ABAP2XLSX, there, put it into a transport, no?
Regards,
Bruno
Hello Bruno,
I have the debugger authorization, maybe with this one I can skip the auth. check...
How can I install SAPlink? I found only the .nugg files... What is the exact procedure?
Best Regards,
Tom
Hi Tom,
Google is your friend!
I would say you need to download these files:
This one for the plugins:
build | SVN | Assembla
And follow the instructions here:
SAPlink User Documentation - ABAP Development - SCN Wiki
The only way I can help you more, is if I do it for you 🙂
Regards,
Bruno
Dear Ivan,
Please let me know when the transport is up to date. The transport will update the old objects? Because I saw that another guy installed your package in the past and when I tried to install the new one there were some error 🙁
I hope that the new transport will fix these issues.
Thank you very much for you help.
Dear Ivan,
Do you know (more less) when you can deliver the latest transport version?
Thanks in advance,
Tom
Hi Bruno,
Thank you very much. It works now 🙂 All objects have been updated with SAPLink.
One last question, I tested ZDEMO_EXCEL4 in order to add a header and a footer with page number and this work perfectly but I need also to add a picture in the right part of the header. And I did not found a solution to do this 😐 Do you have an idea?
Best Regards,
Tom
Hi again Tom,
I'm glad it worked for you now.
I haven't used this much. I don't know how to add images to excel. Have you looked well enough in the examples? My guess is that... if it isn't in an example, it is not possible.
But hopefully someone else will be able to answer that for ya.
Cheers,
Bruno
Dear Team,
Does anybody have an idea about how to add a picture in the header with the code?
Thanks in advance
Hi Bruno,
Yes, I checked the examples and I know how to add a picture in the excel but there is no way to add it in the header 🙁
I also create an excel template with a header and footer and used the report to read the excel and it does not read the header with the picture...
Now, I'm not sure whether there is a solution.
Best Regards,
Tom
Dear Tom,
so if it's possible to have an image maintained in the header directly in excel, then it seems to be a missing functionality of abap2xlsx right now. You can either start creating this functionality yourself or hire one of the contributors to implement it for you.
Best regards
Gregor
😐 This is realy a bad news because as far as I know we have to generate a vml file and this is something very complicate 🙁
Is there another way to display a picture in each page in the excel file?
Hi Tom,
please open a discussion on SCN with the tag abap2xlsx and [abap2xlsx] in the subject.
Thank you
Ivan
Hello Ivan. I love your product! But I ran into the issue of when I published a transaction as an internet service (SICF - ITS), the option to 'Direct Display' the spreadsheet does not work. Excel never starts. Any ideas?
Dear Kenneth,
I wouldn't think that this is a abap2xlsx problem. But please post in SCN with the tag abap2xlsx and [abap2xlsx] in the subject.
Best regards
Gregor
Thanks, Gregor. I created a post.
Hi guys,
I've created a fancy little file reader that uses your xlsx reader here
Basically, I use your capabilities of reading the xlsx file into a char like structure, and then the reader will automatically take care of the conversion from external format to the internal SAP format.
Feel free to take a look, any comments or suggestions are welcome.
Best,
Bruno
Hi Bruno,
I will install your solution in my abap system...
It seems interesting.
Thank you
Ivan
That's an honor Ivan 🙂
Best regards,
Bruno
Hi Ivan,
I am new to ABAP2XLSX. Just want to check if this can support both 32bit and 64bit MS Excel?
(Sorry, if this is wrong place to post the question.)
Thank you.
Hi Suneel,
As far as I know, it doesn't make a difference, the XLSX file does not depend on the Office version.
Regards,
Bruno
As Bruno stated, Excel version does not affect generated xlsx.
Thank you both.
Hi Ivan
I use your class to create XLSX for outbound email and to unpack XLSX from inbound email and it works beautifully!
I also store the XLSX raw data in a table and the user has a transaction to display the XLSX in place within SAPGUI. This works and the spreadsheet displays the correct data with all the expected formats etc. ... all good.
The only problem is the user gets an annoying warning from Excel that the workbook is corrupt - this is not true and he/she needs to just ignore this.
Any thoughts? Currently the users ignore this and its no big deal but my system is not perfect 🙂
regards
Ian
This is the error message ...
If he/she proceeds, Excel reports an error with the spreadsheet
the log of the error from Excel is not useful - there is no error
my code is as follows where LT_RAWDATA holds the raw XLSX info.
Ian,
It could be graphic characters or unusual formatting.
I am storing the XLSX template in an SAP table in Xstring
format. I had the same “unreadable content” message.
I had to remove all range names, Freeze pane settings, and
especially external document links.
If this does not fix the issue, try this:
*** Warning: converting to ODS (Open DataSource) format replaces
the SPACE character in sheet names with the UNDERSCORE character.
-David
Hi David
possibly but the XLSX is generated in SAP, emailed to the user who fills in some text and sends this back to SAP where the entries are processed. Some of the cells are formatted in terms of font size, basic formula for syntax check ( i.e. ISNUMBER ), colour and protection but otherwise I can't think of anything "toxic" in the spreadsheet. Excel complains but it does display and all the attributes and content are displayed correctly.
regards
Ian
Ian,
Are you using set_cell or set_cell_style? I had the "unreadable content" message once when I placed text in a cell that was formatted as a number. I changed all cell formats to text and the unreadable content message no longer displayed.
-David
Ian,
I would suggest to open an issue on GitHub and provide the details above and an example XLSX file.
Usually this error comes from a wrong xml file in the structure.
Provide as many datails as possible in order to analyze the issue.
Ivan
Hi Ivan
I'll do as you suggest ... apart from this the system is working flawlessly i.e. the outbound XLSX works correctly when emailed from SAP and when the form is filled in, I can process the data entries made by the users
regards
Ian
Dear Team,
I used the email send option with the demo reports...I checked in SOST and the mail and attachement are ok, I download or opened the attachement and evething is ok, the attachement can be opened as an 'xlsx" file.
But when I process the line is SOST and receive the main in my Gmail inbox, the attachement has not the correct extention, normally the extention must be "filename.xlsx" but in the mail it is "filename.xlsx.XLS".
Ans when I open this file there is a warning....
Do you have a solution to avoid this issue?
Thank you in advance,
Tom
Hi Tom,
it works for me. In the method 'send_email' you'll find the following comments:
* Add attachment to document
* since the new excelfiles have an 4-character extension .xlsx but the attachment-type only holds 3 charactes .xls,
* we have to specify the real filename via attachment header
* Use attachment_type xls to have SAP display attachment with the excel-icon
So I defined a constant in the DATA-Section :
gc_save_file_name type string value 'ABRV_Kandis.XLSX'.
That's it. Hope it works for you too.
Regards
Karl
Hello Karl,
Yes, I know and I have the same code => I used the demo report program.
CONSTANTS: gc_save_file_name TYPE string VALUE '03_iTab.xlsx'.
attachment_subject = gc_save_file_name.
CONCATENATE '&SO_FILENAME=' attachment_subject INTO wa_attachment_header.
APPEND wa_attachment_header TO t_attachment_header.
But in the inbox of Latus or Gmail, the attached file name is "03_iTab.xlsx.XLS"
😕
FYI: I processed manually the line in SOST
Best Regards,
Tom
Hi Tom,
that's strange. I am not using the demo report but it's just copy and paste of the routines. So far, my code looks the same.
I also use manual processing in SOST. It's connected to an excahnge server and I receive the mail by Outlook. The filename is exactly 'ABRV_Kandis.XLSX' as defined.
The next code lines in my program are:
sood_bytecount = bytecount. " next method expects sood_bytecount instead of any positive integer *sigh*
cl_document->add_attachment( i_attachment_type = 'XLS' "#EC NOTEXT
i_attachment_subject = attachment_subject
i_attachment_size = sood_bytecount
i_att_content_hex = t_rawdata
i_attachment_header = t_attachment_header ).
Regards
Karl
Hi Karl,
I have the same code. Is there any configuration to do in order to avoid this additional extention (.XLS)?
I tried to create the attachement with "i_attachment_type = ' ' "
and the file was created with "03_iTab.xlsx.EXT"
Very strange !
Best Regards,
Tom
Tom and Karl: can you compare your Basis Releases? Maybe something changed in one of the last service packs.
Hi Tom,
as you can see in my example above, I am using i_attachment_type ='XLS'
Please note it ist not '.XLS' with a dot.
Maybe you can go into transaction SOST, mark the line with your mail and then press the button with the glasses. What is the attachment named like?
@ Uwe
We are using component SAP_BASIS on release 702 with SP-Level 14.
Greets
Karl
Hi Karl,
SAP_BASIS on release 732 with SP4.
I use i_attachment_type ='XLS' and not with a dot.
In SOST evething is ok. When I download via SOST the file is xlsx but the only issue is when I receive via mail in the Lotus or Gmail inbox it is xlsx.XLS
Please see screenshot from SOST and mail inbox
Best Regards
Tom
PLEASE,
This will help us to provide you and the community a better support.
Thanks,
Ivan
Hello!
First of all I want to thank you for this great project, well done!
I have question about Charts - I was studying program ZDEMO_EXCEL39, i know how to make Excel file with BarChart, PieChart, LineChart, but I haven't figurued yet how to make Chart like this:
Thank in advance for any help/guide,
Jakub
Hi Jakub,
thank you for your feedback.
Please open a new discussion in SCN space Open Source, someone of our team will help you.
Ivan
Hello everyone,
is it possible to create an excel file with the Method bind-table but don't get any filters already set ???
Johannes please do not cross post, answer on your discussion abap2xlsx -> bind_table without filters
Ivan
HI Ivan,
i have a requirment like to write data to XLSX but unfortunatly when i tried to see the code link which you have mentioned its saying "UNAUTHORIZED" even though i am logged in.
Could please help on this , i need this as reference.
Thank you.
Code is shared on GitHub and it is open source.
You should not have any authorization issue on SCN, the post is in the open source section.
Please check with SCN team for SCN auth issue.
Ivan
Thank you Ivan 🙂
Hi Ivan.
Can you give any hint or solution about inserting rows into worksheet like in excel? I'm trying to implement it but I found that I must rebuild all formulas under the inserted row.
Sample worksheet:
A1 = 5, A2 = 8, A3 = SUMM(A1:A2).
I want to insert new row between A1 and A2 and get A1 = 5, A2 = empty, A3 = 8, A4 = SUM(A1:A3).
The worst thing for me right now is the formula.
Dear Evgeniy,
you're already programming in ABAP so you can create the formula also programmatically.
Best regards
Gregor
Evgeniy,
please open a discussion in order to keep this thread clean...
And your answer is in the demo provided within the nugget
Ivan
Hi Ivan,
I have a scenario where, I need to populate data into pre formatted excel template in background mode. Do you know if OLE2 supports excel sheet generation in background mode?
Also the excel template has macro's build into it and has an file extension of .XLSM.
Thanks in Advance,
Ramesh
PS: I tried to post this question in SAP open source, but could not find an option to open a new discussion.
OLE requires a connection from ABAP server to a server with OLE application installed (note that all Microsoft Office applications (Excel, Word...) are OLE compatible). In dialog, all OLE applications from the frontend computer can be accessed. In background, the frontend computers cannot be accessed, or it's difficult/rather unusual to do it. So we always prefer using abap2xlsx to generate directly the Excel file, and it's much faster too.
Hi Sandra,
Thank you for your response. I would like to specifically know the ABAP2XLSX capabilities around reading a template(with macros) and populating data with in multiple sheets. I tried using class I_OI_SPREADSHEET, but it works only in foreground.
Appreciate your response.
Ramesh
DOI is based on an OLE client too. Sorry, I don't know for ABAP2XLSX.
Thank you Sandra for your response.
The abap2xlsx tool is supplied with ZDEMO_EXCEL29 which opens any existing XLSM template, and saves it into another one, and the macros are kept successfully.
Anybody tried to hide a sheet before? Assuming you have 3 sheets, but 3rd sheet is to be hidden. I don't seem to find a functionality to hide a sheet.
Kindly share if you know the way to do it. Thanks in advance.
Hello everybody,
currently I am trying to process an xlsm template from the SAP Directory.
My problem is that the commandbuttons (Active-X form controls) from the xlsm-templage will no longer appear in the exported file. I am using the generel functions from the report ZDEMO_EXCEL29.
Is there a functionality for copying all buttons from the template?
Thanks in advance,
Mathias
Hi ,
Activate the following things after installation,
ZEXCEL_S_DRAWINGS structure
ZEXCEL_S_WORKSHEET_HEAD_FOOT structure
ZEXCEL_T_DRAWINGS TableType
ZCL_EXCEL_DRAWINGS class
Hola, tengo un problema al exportar a excel.
utilizo CALL METHOD cl_gui_frontend_services=>gui_download
pero cuando me abre el excel, quiero que el tipo del formato sea tipo rango.
Sin que el usuario tenga que pulsar: Diseño-> convertir a rango.
Esto es posible?
muchas gracias
Try SET_AREA method, check the ZDEMO_EXCEL13 example
Hola... gracias por tu rápida respuesta.
pero estoy mirando de nuevo el ZDEMO_EXCEL13 y no veo ningún method SET_AREA
muchas gracias
Muchas gracias!
pero me imagino que nuestro sistema no esta actualizado porque en nuestra clase no tenemos el método SET_AREA
por eso no lo encontraba, de echo en el programa ZDEMO_EXCEL13 de nuestro sistema no viene ese codigo
Muchas Gracias
Hi.
I am trying to install it from abapGit repository in ECC but I got below errors, it seems that the structures are not being imported, all domains and data elements have been imported but the structures do not, therefore, type tables are not being installed as well.
Has anyone has this error before?
Thanks in advance.
Errors | https://blogs.sap.com/2010/07/12/abap2xlsx-generate-your-professional-excel-spreadsheet-from-abap/ | CC-MAIN-2021-25 | refinedweb | 6,486 | 73.37 |
- NAME
- DESCRIPTION
- INSTALLATION
- SETUP
- DATA LAYER (MODEL)
- QUICK VARS AND UTILITIES
- CONFIGURATION
- MASON PAGES AND COMPONENTS
- POET SCRIPTS
- FILES FROM THIS TUTORIAL
- SEE ALSO
- AUTHOR
NAME
Poet::Manual::Tutorial - Poet tutorial
DESCRIPTION
This tutorial provides a tour of Poet by showing how to build a sample web application - specifically a micro-blog, which seems to be a popular "hello world" for web frameworks. :) Thanks to Dancer and Flask for the inspiration.
INSTALLATION
First we install Poet and a few other support modules.
If you don't yet have cpanminus (
cpanm), get it here. Then run
cpanm -S --notest DateTime DBD::SQLite Poet Rose::DB::Object the initial environment:
% poet new Blog blog/.poet_root blog/bin/app.psgi blog/bin/get.pl ... Now run 'blog/bin/run.pl' to start your server.
The name of the app,
Blog, will be used in app-specific class names. It is also used for the default directory name (
blog), though you can move that wherever you want.
Run this to start your server:
% blog/bin/run.pl
and you should see something like
Running plackup --Reload ... --env development --port 5000 Watching ... for file updates. HTTP::Server::PSGI: Accepting connections at
and you should be able to hit that URL to see the Poet welcome page.
In Poet, your entire web site lives within a single directory hierarchy called the environment. It contains subdirectories for configuration, libraries, Mason components (templates), static files, etc.
From now on, every file we create in this tutorial is assumed to be under the environment root.
DATA LAYER (MODEL)
For any website it's a good idea to have a well-defined, object-oriented model through which you retrieve and change data. Poet and Mason don't have much to say about how you do this, so we'll make some minimal reasonable choices here and move on.
For this demo we'll represent blog articles with a single sqlite table. Create a file
db/schema.sql with:
create table if not exists articles ( id integer primary key autoincrement, content string not null, create_time timestamp not null, title string not null );
Then run
% cd blog % sqlite3 -batch data/blog.db < db/schema.sql
We'll use Rose::DB::Object to provide a nice object-oriented API to our data (DBIx::Class would work as well). Create a file
lib/Blog/DB.pm to tell Rose how to connect to our database:
lib/Blog/DB.pm: package Blog::DB; use Poet qw($poet); use strict; use warnings; use base qw(Rose::DB); __PACKAGE__->use_private_registry; __PACKAGE__->register_db( driver => 'sqlite', database => $poet->data_path("blog.db"), ); 1;
and a file
lib/Blog/Article.pm to represent the articles table:
lib/Blog/Article.pm: package Blog::Article; use Blog::DB; use strict; use warnings; use base qw(Rose::DB::Object); __PACKAGE__->meta->setup( table => 'articles', auto => 1, ); __PACKAGE__->meta->make_manager_class('articles'); sub init_db { Blog::DB->new } 1;
Basically this gives us
a
Blog::Articleclass with a constructor for inserting articles and instance methods for each of the columns, and
a
Blog::Article::Managerclass (autogenerated) for searching for and retrieving multiple articles
See Rose::DB::Object::Tutorial for more information.
QUICK VARS AND UTILITIES
In
lib/Blog/DB.pm above, we have
use Poet qw($poet);
followed by
database => $poet->data_path("blog.db"),
$poet is the global Poet::Environment object, providing information about the environment and its directory paths. We use it here to get the full path to our sqlite database, without having to hardcode our environment root.
More generally
$poet is one of several special Poet "quick vars" that can be imported into any package, just by including it on the
use Poet line. Another important one is
$conf, which gives you access to configuration:
use Poet qw($conf $poet); ... my $value = $conf->get('key', 'default');
You can also import sets of utilities in the same way, e.g. ':file' for file utilities and ':web' for web-related utilities. See Poet::Import for the full list of Poet vars and utility sets.
CONFIGURATION
Poet configuration files are kept in the
conf subdirectory. The files are in YAML form and are merged in a particular order to create a single configuration hash.
For this tutorial we can ignore everything but
conf/local.cfg. It currently contains:
layer: development server.port: 5000
This says that you are in development mode (so that you'll see errors directly in the browser, etc.) and running on port 5000.
You'll need to add one more entry:
server.load_modules: - Blog::Article
This says to load
Blog::Article, our model, on server startup.
See Poet::Conf for More information on configuration.
MASON PAGES AND COMPONENTS
Mason is the templating engine that you'll use to render pages (the view), and is also responsible for routing URLs to specific pieces of code (the controller). So it's not surprising that most of the rest of this tutorial will focus on Mason.
Mason's basic building block is the component - a file with a mix of Perl and HTML. All components lives under the subdirectory
comps; this is known in Mason parlance as the component root.
Given a URL, Mason will dispatch to a top-level component. This component decides the overall page layout, and then may call other components to fill in the details.
poet new generated a few starter components for us, but we're not going to use those, so let's clear them by running
rm -fR comps; mkdir comps
Now here's our first component to serve the home page,
comps/index.mc:
comps/index.mc:
.mc extension is considered a top-level component.
index.mc.
%-lines, substitution tags, <%init> blocks
Next we create
comps/all_articles.mi. Because it has an
.mi extension rather than
.mc, it is an internal rather than a top-level component, and cannot be reached by an external URL. It can only be reached via a component call from another component.
comps/all_articles.mi first when this component is.
Attributes
Next we create
comps/article/display.mi. (It is in a new subdirectory, showing that you can freely organize components among different directories.)
comps/article/display.mi: 1 <%class> 2 use Date::Format; 3 my $ 8 <h3><% $.article->title %></h3> 9 <h4><% $.article->create_time->strftime($date_fmt) %></h4> 10 <% $.article->content %> 11 </div>
The <%class> block on lines 1-4 specifies a block of Perl code to place near the top of the generated component class, outside of any methods. This is the place to use modules, declare permanent constants/variables, declare attributes with 'has', and define helper methods. Most components of any complexity will probably have a
<%class> section.
On line 4 we declare a single incoming attribute,
article. It is required, meaning that if
all_articles.mi had forgotten to pass it, we'd get a fatal error.
Throughout. :)
Content wrapping, autobases, inheritance, method modifiers
Now we have to handle the URL
/new_article, linked from the home page. We do this with our second page component,
comps/new_article.mc. It contains only HTML (for now).
comps/new_article.mc:
comps/index.mc and
comps/new_article.mc have the same outer HTML template; other pages will as well. It's going to be tedious to repeat this everywhere. And of course, we don't have to. We take the common pieces out of the
comps/index.mc and
comps/new_article.mc and place them into a new component called
comps/Base.mc:
comps/Base.mc: 1 <%augment wrap> 2 <html> 3 <head> 4 <link rel="stylesheet" href="/static/css/mwiki.css"> 5 <title>My Blog</title> 6 </head> 7 <body> 8 <% inner() %> 9 </body> 10 </html> 11 </%augment>
When any page in our hierarchy is rendered,
comps/Base.mc will get control first. It will render the upper portion of the template (lines 2-7), then call the specific page component (line 8), then render the lower portion of the template (lines 9-10).
Now, we can remove everything but the inside of the
<body> tag from
comps/index.mc and
comps/new_article.mc.
comps/index.mc: <h2>Welcome to my blog.</h2> <& all_articles.mi &> <a href="/new_article">Add an article</a> comps/new_article.mc <h2>Add an article</h2> <form action="/article/publish" method=post> <p>Title: <input type=text size=30 name=title></p> <p>Text:</p> <textarea name=content rows=20 cols=70></textarea> <p><input type=submit</p> </form>
More details on how content wrapping works here.
Form handling, pure-perl components
/new_article.mc posts to
/article/publish. Let's create a component to handle that, called
comps/article/publish.mp. It will not output anything, but will simply take action and redirect.
comps/article/publish.mp: 1 has 'content'; 2 has 'title'; 3 4 method handle () { 5 my $session = $m->session; 6 if ( !$.content || !$.title ) { 7 $session->{message} = "Content and title required."; 8 $session->{form_data} = $.args; 9 $m->redirect('/new_article'); 10 } 11 my $article = Blog::Article->new( 12 title => $.title, 13 content => $.content, 14 create_time => DateTime->now( time_zone => 'local' ) 15 ); 16 $article->save; 17 $session->{message} = sprintf( "Article '%s' saved.", $.title ); 18 $m->redirect('/'); 19 }
The
.mp extension indicates that this is a pure-perl component. Other than the 'package' and 'use Moose' lines that are generated by Mason, it looks just like a regular Perl class. You could accomplish the same thing with a
.mc.
handle is one of the structural methods that Mason calls initially on all top-level page components; the default just renders the component's HTML as we've seen before. Defining
handle is the way to take an action without rendering anything, which is perfect for form actions. (It's always better to redirect after a form action than to display content directly.)
The
method keyword comes from Method::Signatures::Simple, which is imported into components by default; see Mason::Component::Moose.
On line 5 we grab the Plack session via
$m->session. This is one of a handful of web-related methods only available in Poet.
On lines 7 and 17, we set a message in the session that we want to display on the next page. Rather than just making this work for a specific page, let's add generic code to the template in
Base.mc:
comps/Base.mc: 7 <body> => 8 % if (my $message = delete($m-.
Filters
We need to change
comps/new_article.mc to repopulate the form with the submitted values when validation fails.
comps/new_article.mc:.
POET SCRIPTS
Up til now all our code has been in Mason components. Now let's say we want to create a cron script to purge blog entries older than a configurable number of days. The script, of course, will need access to the same Poet features as our components.
Run this from anywhere inside your environment:
% poet script purge_old_entries.pl ...bin/purge_old_entries.pl
Poet created a stub script for us inside
bin. Let's take a look:
#!/usr/local/bin/perl use Poet::Script qw($conf $poet); use strict; use warnings;
Line 2 of the script initializes the Poet environment. This means Poet- into the script namespace. See Poet::Import.
Poet initialization has to happen exactly once per process, before any Poet features are used. In fact, take a look at
bin/run.pl -- which was generated for you initially -- and you'll see that it does 'use Poet::Script' as well. This initializes Poet for the entire web environment.
Now we can fill out our purge script:
#!/usr/local/bin/perl use Poet::Script qw($conf); use Blog::Article; use strict; use warnings; my $days_to_keep = $conf->get( 'blog.days_to_keep' => 365 ); my $min_date = DateTime->now->subtract( days => $days_to_keep ); Blog::Article::Manager->delete_articles( where => [ create_time => { lt => $min_date } ] );
In line 2, we've eliminated the unneeded
$poet.
In line 7, we get
$days_to_keep from configuration, giving it a reasonable default if there's nothing in configuration.
Finally in lines 8-10 we delete articles less than the minimum date.
FILES FROM THIS TUTORIAL
The final set of files for our blog demo are in the
eg/blog directory of the Poet distribution, or you can view them at github.. | https://metacpan.org/pod/distribution/Poet/lib/Poet/Manual/Tutorial.pod | CC-MAIN-2015-11 | refinedweb | 2,017 | 58.18 |
So far, what we have declared in the states (or routes) is the path and the component that we want to go with them. What Angular does allow us to do is add a new property called data to the route configuration. This allows us to add any data that we would like regarding any route. In our case, it works out very well because we want to be able to toggle routes based on the keys a user presses.
So, let's take an example route that we have defined previously:
import { HomeComponent } from './home.component';export const HomeRoutes = [ { path: 'home', component: HomeComponent },];export const HomeComponents = [ HomeComponent];
We will now modify this and add the new data property to the route configuration:
import ... | https://www.safaribooksonline.com/library/view/hands-on-data-structures/9781788398558/bedae6b6-4e91-48f4-a81e-b7aafb353614.xhtml | CC-MAIN-2018-09 | refinedweb | 124 | 59.43 |
old.
oldCovfefe
I finally found the issue. The code works fine on the main level of the app, but has these issue when triggered from a event handler (a function call from an action attribute). The following directive solves the issue:
import location @ui.in_background def button_tapped(sender): location.start_updates() loc_dic = location.get_location() addr_dic = location.reverse_geocode(loc_dic) ...
oldCovfefe
tried that, but it only resulted in a hung loop ... there is something else funky going on, because from the console it works just fine.
oldCovfefe
Code snippet:
import location location.start_updates() loc_dic = location.get_location() addr_dic = location.reverse_geocode(loc_dic)
Get location works fine, converting it to a friendly street address does not. When I enter the same statement (the last line) in the console, it works just fine and creates a dictionary with all the interesting info. Any ideas what could be going on? Is it a timing issue, meaning I have to wait until it’s populated?
Thanks. | https://forum.omz-software.com/user/oldcovfefe | CC-MAIN-2021-17 | refinedweb | 157 | 61.63 |
In this tutorial, we will learn how to control servo motors using machine learning techniques through the Wekinator platform. By inputting the necessary data for Wekinator to process, we can control the servo motors with Wekinator’s output.
Required Hardware and Software
Required Hardware
- Arduino UNO
- 2 servo motors
- breadboard
- jumper wires
Required Software
- Wekinator
- Arduino IDE
Circuit Diagram for Wekinator-Controlled Servo Motor
Start by connecting the red wires on each servo to the Arduino’s 5V pin. Then connect each servo’s black wire to the Arduino’s ground. Lastly, connect the yellow wire from one of the servos to pin 8 on the Arduino and the yellow wire from the other servo to pin 9.
Circuit diagram for controlling servos through Wekinator
How to Run Wekinator in Arduino IDE
Paste the Arduino-specific code provided at the end of this post into the Arduino’s IDE and upload it.
You will then need to download the sketch file from Wekinator’s Quick Walkthrough page.
Download the on-screen mouse control examples found on the Walkthrough page. Unzip the file and run the sketch in processing. This sketch provides the input to Wekinator. You need another sketch for the output portion, which you’ll find at the end of this post. Paste that code into the processing window and run it—both processing output windows should look like this:
Processing output window in Wekinator
Open Wekinator and update the settings as follows:
- Set the input window to 2
- Set the and output window to 2
- Set the type to custom
Once your settings are updated, click configure.
Create new project window in Wekinator.
Once you click configure, the Customize Output Types window opens. In this window, adjust the settings as follows:
Customize Output Types window in Wekinator.
Drag the green box in the processing window to the center of left-hand side and adjust the settings in the Wekinator window to the values displayed below, then briefly start and stop the recording.
Move the green box in the processing window to the center of the right-hand side of the screen and adjust the settings in the Wekinator window as shown below. Once again, briefly start and stop the recording
Next, drag the green box in the processing window to the center top area of the window and adjust the settings to the ones shown in the Wekinator window below. Again, quickly start and stop the recording.
Finally, drag the green box in the processing window to the bottom center of the window and adjust the settings to reflect those displayed in the Wekinator window. For the last time, quickly start and stop the recording.
Click on the Train button, then select Run. When you drag the green box in the processing window, the servos connected to the Arduino will move accordingly. synchronized for Wekinator-Controlled Servos
#include <VSync.h> // Including the library that will help us in receiving and sending the values from processing #include <Servo.h> // Including the servo library ValueReceiver<2> receiver; /*Creating the receiver that will receive up to 2 values. Put the number of values to synchronize in the brackets */ /* The below two variables will be synchronized in the processing and they should be same on both sides. */ int output; int output1; // Creating the instances Servo myservo; Servo myservo1; void setup() { /* Starting the serial communication because we are communicating with the Arduino through serial. The baudrate should be same as on the processing side. */ Serial.begin(19200); // Initializing the servo pins myservo.attach(8); myservo1.attach(9); // Synchronizing the variables with the processing. The variables must be int type. receiver.observe(output); receiver.observe(output1); } void loop() { // Receiving the output from the processing. receiver.sync(); // Check for the info we're looking for from Processing if (output < 180) { myservo.write(output); } if (output1 <180) { myservo1.write(output1); } } | https://maker.pro/arduino/projects/how-to-control-servo-motors-using-an-arduino-uno-and-wekinator | CC-MAIN-2019-26 | refinedweb | 644 | 53.71 |
On 4/18/10 10:37 , Christophe Combelles wrote: > Tres Seaver a écrit : >>> So far the main circularity was that everything depended on >>> zope.testing as a testrunner, zc.buildout for making the development >>> environment, and zope.testing obviously depended on zope.interface >>> etc. I solved that by also adding support for setuptools/distributes >>> testrunner and using that instead. That fixed zope.interface, >>> zope.event and zope.exception. These modules still have buildout >>> configurations if you want them, but you don't need buildout anymore. >>> zope.interface, zope.event and zope.exception can now be developed and >>> tested with only setuptools, you can run the tests with "python >>> setup.py test" both under Python 2 and 3. >> >> Yay! That is a big win -- I'd like to see us automate testing this way, >> so that future development doesn't erode it. Developing ZTK packages >> using buildout should be a convenience, not a mandate. > > Depending on setuptools for tests in another evil thing. We should not assume > a > *setup* tool to be a testrunner, and we should not depend on the behaviour of > setuptools to write tests.
Advertising
All zope.* packages already depend on setuptools to setup the namespace, so I don't see a problem with using setuptools to run tests. The dependency is already there. Wichert. _______________________________________________ Zope-Dev maillist - Zope-Dev@zope.org ** No cross posts or HTML encoding! ** (Related lists - ) | https://www.mail-archive.com/zope-dev@zope.org/msg33280.html | CC-MAIN-2017-30 | refinedweb | 233 | 60.82 |
Over the last couple of years, we have seen ever more advanced games for mobile devices. 3D graphics are no longer something you can only experience on the cutting edge devices, but are available on many mid-range mobile phones.
For game developers focused on Java ME, there are two APIs available for creating 3D graphics, the Mobile 3D API (JSR-184) and the OpenGL ES bindings for Java ME (JSR-239). The Mobile 3D API is basically the Java ME equivalent to the Java 3D API we know from Java SE, while JSR-239 is a Java implementation of the OpenGL ES standard managed by the Khronos Group (there is also a Java SE implementation of the standard OpenGL API called JOGL). It is my belief that the JSR-239 will be more successful in the long run, since it is a more widespread standard than JSR-184 and is also better prepared for the new 3D graphics chips. We have seen the same behavior with Java3D versus JOGL, where developers abandoned Java 3D since it was too difficult to extend, and make use of new graphics features.
3D graphics can make very cool games, but unless you can interact with the game using more sensitive controls than binary buttons, the gaming experience will be limited. A touchscreen would be one way to raise the gaming experience, but there is another solution that I believe is likely to be even more successful..
The game is a simple space game where you fly straight ahead and try to avoid colliding with incoming asteroids. You steer the ship by tilting the phone in the direction you wish to go. Since I'm no 3D artist, and severely color blind, the graphics are quite crude, but I hope that you'll all see the possibilities of using these APIs together anyway. All the code for the game is available as a download at. Feel free to experiment with this and use it as you wish.
The OpenGL ES is a standard managed by the Khronos Group, which also manages several other graphics and audio standards (OpenGL, OpenAL). OpenGL ES is based on the standard OpenGL API, so if you are already familiar with OpenGL, much of the code shown below will not be new to you. The Java ME implementation of OpenGL ES supports version 1.1, which is based on the standard OpenGL version 1.5. There is also an OpenGL ES version 2.0, but that version requires much more of the hardware and is currently not suitable for our mobile phones.
I will not go into the details of 3D programming; there are plenty of other resources available that will give you a good introduction to OpenGL and 3D programming in general. Here I will focus on the details of initiating the OpenGL ES on Java ME and how to configure it properly for your device.
JSR-239 is basically a direct implementation of the OpenGL ES API for the C programming language. There is also a package named java.nio which contains a partial Java ME implementation of the Java SE NIO API. This implementation is used to create native buffers that are used by the OpenGL ES for vertexes, normals, and textures.
java.nio
To draw 3D with JSR-239 we use a GameCanvas and draw our 3D scene onto it. First, we need to initialize the graphics and configure things like color depth and other OpenGL-related properties. The following code will initialize the graphics using 5 bits for red, 6 for green and 5 for blue (a total of 16 bits color depth) and a depth buffer with 16 bits. The reason green gets one more bit than red and blue is that the human eye sees more shades of green.
GameCanvas
private boolean initGraphics() {
egl = (EGL11) EGLContext.getEGL();
if (egl == null) {
System.out.println("Error: could not initialize OpenGL ES");
return false;
}
eglDisplay = egl.eglGetDisplay(EGL11.EGL_DEFAULT_DISPLAY);
if (eglDisplay == null) {
System.out.println("Error: could not open connection to display");
return false;
}
int[] majorMinor = new int[2];
if (!egl.eglInitialize(eglDisplay, majorMinor)) {
System.out.println("Error: could not initialize OpenGL ES display");
return false;
}
System.out.println("EGL version: " + majorMinor[0] + "." + majorMinor[1]);
int[] numConfigs = new int[1];
egl.eglGetConfigs(eglDisplay, null, 0, numConfigs);
if (numConfigs[0] < 1) {
System.out.println("Error: no configurations found");
return false;
}
int configAttributes[] = {
EGL11.EGL_RED_SIZE, 5, EGL11.EGL_GREEN_SIZE, 6, EGL11.EGL_BLUE_SIZE, 5,
EGL11.EGL_ALPHA_SIZE, 0,
EGL11.EGL_DEPTH_SIZE, 16,
// EGL11.EGL_STENCIL_SIZE, EGL11.EGL_DONT_CARE, // don't care about stencils
EGL11.EGL_SURFACE_TYPE, EGL11.EGL_WINDOW_BIT,
EGL11.EGL_NONE
};
EGLConfig eglConfigs[] = new EGLConfig[numConfigs[0]];
if (!egl.eglChooseConfig(eglDisplay, configAttributes, eglConfigs,
eglConfigs.length, numConfigs)) {
System.out.println("Error: could not find a suitable configuration");
return false;
}
EGLConfig eglConfig = eglConfigs[0];
eglContext = egl.eglCreateContext(eglDisplay, eglConfig,
EGL11.EGL_NO_CONTEXT, null);
if (eglContext == null) {
System.out.println("Error: could not create a rendering state");
return false;
}
g2d = getGraphics();
gl = (GL11) eglContext.getGL();
if (gl == null) {
System.out.println("Error: could not create a 3D graphics context");
return false;
}
eglWinSurface = egl.eglCreateWindowSurface(eglDisplay, eglConfig, g2d, null);
if (eglWinSurface == null) {
System.out.println("Error: could not create a drawing surface window");
return false;
}
if (!egl.eglMakeCurrent(eglDisplay, eglWinSurface, eglWinSurface, eglContext)) {
System.out.println("Error: could not make the context current");
return false;
}
return true;
}
This method must be called before we can start drawing our 3D scene or initialize any textures or other resources that require the use of JSR-239. To start drawing our 3D scene, we create a new thread with a loop that runs as fast as possible (no delays between each iteration). This way we get the maximum number of frames per second. The actual game logic is managed by the game loop (see below). Typically, when designing a 3D scene using OpenGL, we use a scene graph to structure all the 3D objects. This way we can construct a complex object of several smaller ones and move them as a single unit. The code below shows how we tell the JSR-239 to capture the GameCanvas and start drawing our scene. I've removed some of the code in this examples to show the important part related to rendering JSR-239 using Java.
private void renderScene() {
egl.eglWaitNative(EGL11.EGL_CORE_NATIVE_ENGINE, g2d);
// clear the scene, reset the transformations and set the lighting
...
// Start rendering the scene graph
root.renderNode(gl);
// Tell the device we have finished drawing 3D for this frame and release the device
gl.glFinish();
egl.eglWaitGL();
// Draw ordinary 2D graphics using the Graphics2D object for the GameCanvas
g2d.setColor(0x00aa00);
...
// Flush the graphics of the GameCanvas to display the new frame
flushGraphics();
}
The eglWaitNative method must be called before each rendering pass to capture the graphics of the device. We must also release the device once we're done and finally call flushGraphics to display the new frame. Using eglWaitNative and eglWaitGL we can combine ordinary Java ME 2D graphics with JSR-239. It is also possible to combine JSR-239 with other graphics APIs, such as the Mobile 3D API (JSR-184) or the Scalable Vector Graphics (JSR-226).
eglWaitNative
flushGraphics
eglWaitGL
The Mobile Sensor API (JSR-256) is a general specification focused on communicating with the different sensors that are integrated on a Java ME device. It can be any type of sensor, like a thermometer, light sensor, or, as in this case, an accelerometer. An accelerometer measures accelerations, and the acceleration we are interested in for this game is the most common of all, gravity. Since gravity is constant, it is used to determine the tilt of our phone. In the Sony Ericsson w910i we have a built in three-axis accelerometer, which means that we can measure the acceleration in all three dimensions. If the phone was placed flat, the accelerometer would tell us that the acceleration along the z-axis (up and down) is about 1000 (this value represents 1G). The accelerations along the X and Y axises (sideways) would be about 0 since the phone is sitting still and gravity only works downwards. Flipping the phone over with the screen facing down, the accelerometer would give us the value of -1000 on the Z-axis. Standing on its side, would give us a value of 1000 or -1000 along either the X- or the Y-axis, depending on which side you put it. Putting the phone in a 45 degree angle along the X-axis would give us a value of ±707 on the Z-axis and ±707 on the Y-axis, since gravity cannot affect either axis with its full force (You can easily calculate what the value should be for a certain angle for each axis using the sine and cosine functions). Using the values from the X and Y-axis from the accelerometer, we can determine the position of the phone at any time, and then use that value to move our ship to avoid the incoming asteroids.
The API for JSR-256 is very simple. To get access to the accelerometer, you use the Generic Connection Framework to open a connection given a device-specific URL. You can also use a SensorManager to retrieve information about all available sensors on the device, including the URL for making a connection to it. In the example below, I've used a hard coded string for the URL, but if you wish to make a more generic implementation, the SensorManager should look for available accelerometers and use the one it can find, or give a warning to the user.
SensorManager
When you have a reference to a sensor (implemented as a SensorConnection) you can choose to either retrieve the sensor data by polling the device, or you can register a DataListener to receive updates automatically. My opinion is that the event-driven approach provides a better design and that is also the method I've used in the game. When registering a DataListener to a SensorConnection, you also provide the size of the buffer. This buffer indicates how many data-values should be collected before sending an event to the DataListener. Setting the buffer size to a low value would give you faster updates. However, using a large buffer size you can easier filter out freak values from the accelerometer by calculating the average.
SensorConnection
DataListener
The code below is an implementation of an adapter that is suitable for games. It automatically registers itself as a DataListener on the accelerometer and stores the values in three different integers. There is also a constant storing of the URL to the sensor. This URL is specific to the accelerometer in the Sony Ericsson phones. To make this more generic, it should query for all sensors and connect to the one that is an accelerometer (or display an error message to the user). The getAverage method should be used to determine the average of the collected values, so that we can filter out any freak values that might occur.
getAverage
public class SensorAdapter implements DataListener {
private int x, y, z;
private static final String sensorURL = "sensor:acceleration;contextType=user;model=ST_LIS302DL;location=inside";
public SensorAdapter() {
x = 0; y = 0; z = 0;
try {
SensorConnection sensor = (SensorConnection) Connector.open(sensorURL);
sensor.setDataListener(this, 10);
} catch (IOException e) {
e.printStackTrace();
}
}
public int[] getXYZ() {
synchronized(this) { return new int[] {x, y, z}; }
}
public void dataReceived(SensorConnection sensor, Data[] data, boolean isDataLost) {
synchronized(this) {
for(int i=0; i
The core of this game (and most other games) is the game loop that updates the 3D scene, checks for collisions, and keeps track of the status of all objects in the game. It is what drives the game. Our game loop consists of a thread that keeps running until the user decides to exit the game. Since our game is quite simple, it basically does the following things in this order:
Once the game loop has completed these steps, we call Thread.sleep to create a delay before starting over. The delay will determine how fast the game runs. Setting it to high will make the game seem sluggish, and a low value will make it impossible to play.
Thread.sleep
When moving the ship forward we are actually moving, or translating in 3D terms, all the asteroids and leaving the ship in the same position. Since the positions of every object in our 3D scene is determined by a simple translation using three float values, one for each axis, we need to consider the fact that we might end up with a loss of precision if the values gets large enough. If this were to happen, the 3D object would become distorted and things would start looking quite strange. To avoid this we make sure that the “camera” and the ship are located near the origin, and when moving ahead we simply apply a negative translation to all the other objects in the 3D scene. This is actually the way most 3D games are implemented, regardless if it is a simple 3D game on a mobile device or a huge MMO game on your PC.
Collision detection can be very difficult, depending on how good and precise detection is needed. In this game I've used one of the simplest forms of collision detection, axis-aligned bounding box. We create a virtual box around every object and when testing two objects for collision, we use a simple check to see if the boxes intersect.
We now have a simple 3D game for Java ME, controlled using a built-in accelerometer. Feel free to download the source code for the game and make your own changes. Hopefully this can give you ideas for your own game or application, using either JSR-239 or JSR-256.
The use of the accelerometer in this game is very basic. We're not bothering about the values from the Z-axis at all. I'm certain that there are several other usages of the Mobile Sensor API that I haven't thought of and that are much more interesting than the one described in this article. One idea I'm working on is to use the phone as a game controller for my PC, sending the accelerometer data to my computer over Bluetooth. Could be useful to implement a tennis game. That would also give me a reason for doing more advanced 3D stuff using JOGL. I also believe that there are great opportunities besides games for the Mobile Sensor API. A cordless mouse that could be used during presentations is one idea that pops into my mind.
I hope this article has given you some ideas of what is possible, and that you come up with your own cool games or applications using either OpenGL ES or the Mobile Sensor API. Feel free to contact me if you have any questions or would like to share ideas you have.
Erik Hellman has been working with Java for a little more than ten years. After working with Java EE on large telecom systems for Ericsson he switched to Java consultant and did several presentations at various conferences on a wide range of different topics. He is currently working as the team leader on the development of the Java SDK at Sony Ericsson in Lund, Sweden. | http://developers.sun.com/mobility/apis/articles/opengles_mobilesensor/ | crawl-002 | refinedweb | 2,548 | 61.87 |
PROBLEM LINK:
Author: Dharanendra L V
Tester: Dharanendra L V
Editorialist: Dharanendra L V
DIFFICULTY:
Easy
PREREQUISITES:
Basic observations, Square Matrix, 2D Arrays
PROBLEM:
Given a square matrix N \times N matrix having exactly N^2 elements i.e. P(i,j). We can only move to the Cell(i+1,j+1) or Cell(i-1,j-1) and need to find the total maximum sum S by visiting the cells within the boundary of the matrix and the cells which have not been visited yet.
QUICK EXPLANATION:
When we say a diagonal starting from the cell(x, y), which means all the cells (m, n) such that, x - y = m - n. Only cells satisfying these conditions are considered because you can only move diagonally.
EXPLANATION:
You are allowed to go from cell (i,j) to cell (i+1,j+1) or to cell (i-1,j-1). We can consider starting points as first row elements and first column elements and try calculating the value of each possible path you can traverse. Initialize the sum and answer as 0. For each starting cell (i,j), you can go diagonally downwards. First consider all the paths which start at cell (i,j) and end diagonally below it. We keep on adding the value P (i,j) by traversing downwards diagonally and updating the sum, and after each traverse update the answer if the answer is less than the sum. And finally, print the answer.
SOLUTIONS:
Setter's Solution
#include <bits/stdc++.h> #define FIO ios::sync_with_stdio(0); cin.tie(0) #define test ll t = 1; while (t--) #define REP(x) for (ll i = 0; i < x; i++) typedef long long ll; using namespace std; int main() { FIO; test { ll n; cin >> n; ll a[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { cin >> a[i][j]; } } ll ans = 0; // Iterating with first row elements for (int i = 0; i < n; i++) { ll x = 0, y = i, sum = 0; for (int j = i; j < n; j++) { sum += a[x++][y++]; } if (sum > ans) ans = sum; } // Iterating with first column elements for (int i = 1; i < n; i++) { ll x = i, y = 0, sum = 0; for (int j = i; j < n; j++) { sum += a[x++][y++]; } if (sum > ans) ans = sum; } cout << ans << endl; } return 0; }
Feel free to share your approach here. Suggestions are always welcomed.
| https://discuss.codechef.com/t/shermat1-editorial/83518 | CC-MAIN-2021-49 | refinedweb | 404 | 63.73 |
gnutls_x509_crl_export — API function
#include <gnutls/x509.h>
Holds the revocation list
the format of output params. One of PEM or DER.
will contain a private key PEM or DER encoded
holds the size of output_data (and will be replaced by the actual size of parameters)
This function will export the revocation list to DER or PEM format.
If the buffer provided is not long enough to hold the output, then GNUTLS_E_SHORT_MEMORY_BUFFER will be returned.
If the structure is PEM encoded, it will have a header of "BEGIN X509 CRL".
On success, GNUTLS_E_SUCCESS (0) is returned, otherwise a negative error value. and a negative error code on failure.: | http://man.linuxexplore.com/htmlman3/gnutls_x509_crl_export.3.html | CC-MAIN-2019-22 | refinedweb | 107 | 58.18 |
§Actions, Controllers and Results
§What is an Action?
Most of the requests received by a Play application are handled by an
Action.
A
play.api.mvc.Action is basically a
(play.api.mvc.Request => play.api.mvc.Result) function that handles a request and generates a result to be sent to the client.
def.
The first simplest one just takes as argument an expression block returning a
Result:
Action { Ok("Hello world") }
This is the simplest way to create an Action, but we don’t get a reference to the incoming request. It is often useful to access the HTTP request calling this Action.
So there is another Action builder that takes as an argument a function
Request => Result:
Action { request => Ok("Got request [" + request + "]") }
It is often useful to mark the
request parameter as
implicit so it can be implicitly used by other APIs that need it:
Action { implicit request => Ok("Got request [" + request + "]") }
The last way of creating an Action value is to specify an additional
BodyParser argument:
Action(parse.json) { implicit request => Ok("Got request [" + request + "]") }
Body parsers will be covered later in this manual. For now you just need to know that the other methods of creating Action values use a default Any content body parser.
§Controllers are action generators
A controller) { def index = Action { Ok("It works!") } }
Of course, the action generator method can have parameters, and these parameters can be captured by the
Action closure:
def hello(name: String) = Action { Ok("Hello " + name) }
§Simple results
For now we are just interested in simple results: an HTTP result with a status code, a set of HTTP headers and a body to be sent to the web client.
These results are defined by
play.api.mvc.Result:
import play.api.http.HttpEntity def index = Action { Result( header = ResponseHeader(200, Map.empty), body = HttpEntity.Strict(ByteString("Hello world!"), Some("text/plain")) ) }
Of course there are several helpers available to create common results such as the
Ok result in the sample above:
def index = Action { Ok("Hello world!") }
This produces exactly the same result as before.
Here are several examples to create various results:
val ok = Ok("Hello world!") val notFound = NotFound val pageNotFound = NotFound(<h1>Page not found</h1>) val badRequest = BadRequest(views.html.form(formWithErrors)) val oops = InternalServerError("Oops") val anyStatus = Status(488)("Strange response type")
All of these helpers can be found in the
play.api.mvc.Results trait and companion object.
§Redirects are simple results too
Redirecting the browser to a new URL is just another kind of simple result. However, these result types don’t take a response body.
There are several helpers available to create redirect results:
def index = Action { Redirect("/user/home") }
The default is to use a
303 SEE_OTHER response type, but you can also set a more specific status code if you need one:
def index = Action { Redirect("/user/home", MOVED_PERMANENTLY) }
§
TODO dummy page
You can use an empty
Action implementation defined as
TODO: the result is a standard ‘Not implemented yet’ result page:
def index(name:String) = TODO
Next: HTTP Routing | https://www.playframework.com/documentation/2.6.1/ScalaActions | CC-MAIN-2019-18 | refinedweb | 513 | 52.09 |
Agenda
See also: IRC log
<trackbot> Date: 19 November 2010
<Deirdre> ok, i'll hang up and call again?
no Deirdre
<gdick> +q
gdick wanted to join us?
<gdick> yes
4star ... use URIs to identify things, so that people can point at your stuff (optional RDF)
5star ... link your data to other or more authoritative data to provide context (one serialisation needs to be RDF)
<sandro> (whether RDF is required at 4 stars or not until 5 is an open issue -- waiting for Tim)
<scribe> scribenick: mhausenblas
PROPOSAL: Accept the minutes of last meeting, see
RESOLUTION: minutes approved
see
sandro: charter will likely
include two groups
... IG and WG
... IG as we have right now
... the WG would focus on GLD
... working on revised version of this
... main focus: solving the 'how'
... bunch of vocab that need to be standardised
Michael: what does standardise vocabs mean?
sandro: question is - does W3C
bless a certain vocab or create own?
... where URI (namespace) is
Michael: Maybe define W3C
namespace with profile
... FOAF as an example
... for FOAF
... and
<sandro> ... would list the props & classes recommended, and equivprop to foaf
<sandro> mhausenblas: spectrum....
<sandro> sandro: I'm not seeing a spectrum. xmlnr.org or w3.org
Michael: list all options, list all costs & benefits and figure the 'best' option
sandro: stable target
needed
... what if DERI's funding runs out or DanBri get's hit by a bus
Michael:
... when will charter be finalised?
sandro: try to circulate the
draft very soon
... finalising (go to AC) in Jan 2011, starting in March 2011
Michael: can we continue?
sandro: it's fine - we can continue meeting
Michael: Sunlight will provide
judges and potentially prizes but not co-organize
... and will invite OKFN
sandro: as we get judges, they
might help us with the venues
... there might be a new venue (International Data Gov conf)
... will likely be every year, might be a pretty good venue
Michael: continue with prep
Sandro: ask people that you approach about venues
Michael: OK
Sandro: SemTech?
Michael: maybe
[adjourned]
trackbot, end conference
This is scribe.perl Revision: 1.135 of Date: 2009/03/02 03:52:20 Check for newer version at Guessing input format: RRSAgent_Text_Format (score 1.00) Succeeded: s/IG and WG/...IG and WG/ Found ScribeNick: mhausenblas Inferring Scribes: mhausenblas Default Present: mhausenblas, Sandro, +3539149aaaa, Deirdre, +1.508.333.aabb Present: mhausenblas Sandro +3539149aaaa Deirdre +1.508.333.aabb Agenda: Found Date: 19 Nov 2010 Guessing minutes URL: People with action items:[End of scribe.perl diagnostic output] | http://www.w3.org/2010/11/19-egov-minutes.html | CC-MAIN-2014-52 | refinedweb | 422 | 76.52 |
A Thompson-style Regex-to-Golang Compiler.
This repo contains a command-line app that takes in a simple regular expression (letters and digits with no spaces and the operators “|”, “*” and “+” together with parenthesization) and outputs the source to a Go program which parses inputs for matches to the same expression.
It is intended for educational purposes and not for use in any production system.
Usage.
We will use the example from Thompson’s paper for demonstrative purposes. Executing
./thompson-regex 'a(b|c)*d'
should produce output like the below (after running
go fmt):
package main import ( "fmt" "log" "os" ) /* trimmed some stuff up here */ func main() { if len(os.Args) != 2 { log.Fatalln("must supply input string") } input := []rune(os.Args[1]) expmatcher := concat{ concat{ char('a'), closure{ or{ char('b'), char('c'), }, 0, }, }, char('d'), } matches := []string{} for i := 0; i < len(input); { if ok, n := expmatcher.match(input[i:]); ok { matches = append(matches, string(input[i:i+n])) i += n continue } i++ } fmt.Printf("%q\n", matches) }
Additional output languages can be added here. For example,
./thompson-regex 'a(b|c)*d' -l python3
import sys # trimmed a ton of stuff from here if len(sys.argv) != 2: print("must supply input string") sys.exit() inputstr = sys.argv[1] exprmatcher = ((Char('a') + (Char('b') | Char('c')) ** 0) + Char('d')) matches = [] i = 0 while i < len(inputstr): ismatch, n = exprmatcher.match(inputstr[i:]) if ismatch: matches += [inputstr[i:i+n]] i += n else: i += 1 print(matches)
Purpose.
Ken Thompson’s famous paper on implementing regular expressions is surprisingly simple and yet extremely sophisticated at the same time. The “heart” of the method he proposed was the use of a stack in order to compile the expression to code that parses it, which in this case was IBM 7094 object code.
I find this idea beautiful, and wanted a chance to play around with it for myself, as well as demonstrate to anyone interested the way the algorithm works. Since the aim is demonstration rather than a concrete (or usable) implementation, it makes sense to compile to a high-level language, which is why I have started by targeting Go.
Note on terminology.
I have used the term assembler to refer to the portion of the code that produces Go source (and hopefully other sources in future), which may be slightly confusing given its usual association with the program that produces machine code out of assembly langauge. The aim is to draw an analogy: Thompson’s goal was efficiency, so his implementation produced object code; mine is illustration and education, so it makes sense to target a high level language with the human mind being the real intended machine.
Contributing.
Feel free to create issues to share feedback or make suggestions. The way the codebase is designed it is quite easy to add other output formats, provided they are text-based: see here. | https://golangexample.com/a-simple-regex-to-golang-compiler-based-on-thompsons-construction-algorithm/ | CC-MAIN-2022-33 | refinedweb | 486 | 52.6 |
A Useful Context Manager
Found all over the Python ecosystem, “Context Managers” are the
with something as var: you might use for, say, file I/O:
with open('test.txt', 'w') as f: pass
Essentially, this has the behavior of:
- Entering a context and executing some code (here, opening
test.txtin write mode)
- Doing some stuff (just
passing here)
- Doing cleanup/shutdown behavior (closing the file)
This is similar to how we interact with SQL code, insofar as we:
- Connect to a database
- Make some modifications
- Commit our changes
- Close our connection
Thus, using the
contextlib library, we can hook into this syntax to good use, with the following:
import sqlite3 from contextlib import contextmanager @contextmanager def connect_to_db(database): path = '.' conn = sqlite3.connect(path+database) cur = conn.cursor() yield cur conn.commit() conn.close()
Now, all we need to do is call this function and supply a
.db database file.
Here, we’ll select from a table that doesn’t exist yet
try: with connect_to_db('test.db') as cursor: cursor.execute('select * from new_table') cursor.fetchone() except Exception as e: print(e)
no such table: new_table
Then we’ll make the database and insert a record into it
with connect_to_db('test.db') as cursor: cursor.execute('create table new_table (id integer)') cursor.execute('insert into new_table (id) values (1)')
Finally, we rerun the code that works this time
try: with connect_to_db('test.db') as cursor: cursor.execute('select * from new_table') print(cursor.fetchone()) except Exception as e: print(e)
(1,) | https://napsterinblue.github.io/notes/python/sql/context_manager/ | CC-MAIN-2021-04 | refinedweb | 250 | 50.12 |
I’ve spent a few hours recently making an ESP8266 web-accessible. Here I’m documenting my progress for the benefit of others.
Requirements
My project is to control some lamps around my house from my smartphone. There are lots of ways of solving this, such as WiFi-enabled power sockets or having a slave with an email account to sit next to the switch. My requirements boil down to these:
- Reasonably cheap. WiFi-enabled switches seem to start at around £25 a go. £75 to control three lamps is too much.
- Accessible from outside my home network. It can’t depend on being on the same WiFi network.
- Secure. No-one else should be able to twiddle my lights. This is not to be another IoT project where security is an afterthought (or non-thought).
- It’s not a hard requirement, but I didn’t want to depend on a free messaging server. Too many of them don’t worry too much about privacy or security.
The Setup
This diagram shows the overall architecture:
I’ve bought some radio-controlled power sockets off eBay. They come with a remote control which uses a 433MHz radio to send a 24-bit control signal. I’ve bought an ESP8266 and a 433MHz transmitter/receiver module pair. The receiver is only useful for sniffing the codes sent by the remote. When you first plug one of the sockets in, you have to hold down a button on the remote to ‘programme’ the switch to recognize that button on the remote. It’d be possible to make the ESP8266 send a new code when you press a particular button on the website, to programme a socket, but I haven’t bothered so far.
I’m programming the ESP8266 using the Arduino ESP8266 platform available on GitHub here.
The ESP8266 connects to my home WiFi network and, through that, to my cloud virtual private server (VPS). This is a virtual machine running on someone’s cloud (in my case WebSound). It costs me £2.50 per month. I actually already had this server available for a different project I maintain, so it hasn’t added anything to the cost. I have a DNS registration through GoDaddy, so I just added a new host name to the DNS configuration so the same machine now has two separate names (ie. a.example.com and b.example.com).
The communication from the ESP8266 to the VPS uses the MQTT protocol. MQTT originally stood for MQ Telemetry Transport. You can read about it online, but basically it’s a protocol for publish-subscribe communication. Some clients subscribe to topics and others publish messages on those topics; the subscribers receive the messages published by the publishers. In my case, I’ve opted for MQTT encrypted using TLS. By requiring that clients connect using certificates that I’ve signed using my CA or master key, this solves both the authentication and encryption problems on the ESP8266 side.
Also running on the VPS is a web server. The front end of this is an nginx instance, mainly because it does everything I need and I was already using it for the other project. The webserver is running two “virtual servers” (it’s easy to get lost in the various types of “virtual” here). This means that you get a different “virtual server” depending on which DNS name you use for the host – if someone looks up a.example.com they get my web-enable ESP8266, if they look up b.example.com they get my other project. The nginx part handles this as well as encryption using TLS.
The back end of the webserver is using Flask, a Python micro-web-framework. Flask uses an API called WSGI which is a generic interface to Python web services. You can run a Flask application by just starting a Python interpreter and loading your web service module. This is fine for debugging, but in production you want cool features like multi-threading and resilience to exceptions; you get these for free with a WSGI container, in my case gunicorn. This loads your web service module and instantiates as many instances as it needs to handle the incoming load.
The web server uses the Paho library to connect to the MQTT server, again encrypted using TLS.
Web Server Setup
My VPS is running Ubuntu Server 14.04 (my VPS host spun up a new instance for me with this already installed). This makes installing the various bits and pieces fairly straightforward:
$ sudo apt-get install nginx python3.4 python-virtualenv mosquitto git supervisor openssl $ virtualenv -p /usr/bin/python3.4 ha $ . ha/bin/activate (ha) $ pip install Flask Flask-SQLAlchemy python-social-auth paho-mqtt gunicorn
Here’s a quick overview of what I’ve installed:
- nginx – front end web server
- python3.4, python-virtualenv – the Python interpreter and a tool called virtualenv for setting up isolated Python configurations. This lets me have a different set of installed Python packages for each project. In this case, I’ve created a new virtualenv called ‘ha’ and activated it.
- mosquitto – MQTT server
- git – source control system used for getting the Let’s Encrypt software
- supervisor – a service monitoring framework
- openssl – tools for creating certificates etc
- Flask – back end WSGI framework
- Flask-SQLAlchmey – a Python framework for accessing databases
- python-social-auth – a Python framework for authenticating against social media services, such as Google.
- paho-mqtt – a library for accessing MQTT servers from Python
- gunicorn – a Python WSGI container
Certificates
All the encryption involved uses the public key infrastructure (PKI). Public-private key cryptography relies on a pair of keys. Anything encrypted using one of the keys can only be decrypted by using the other key in the pair. So you can publish your public key and keep your private key private. Now you can encrypt someone with your private key and anyone with your public key can check that it was really you that encrypted it; this is a sort of digital signature. And someone with your public key can use it to encrypt a message and send it to you; only you can read it.
This is extended to the concept of signed certificates. A certificate is a public key that is signed with someone else’s private key. That “someone else” is a certificate authority or CA. The CA is saying that this public key really belongs to the person claiming to own it and, so long as no-one has managed to steal either of their private keys, it’s cryptographically verifiable.
Who you choose to be your CA depends on what you’re using the certificate for. Web browsers have a list of “trusted” CAs and their public keys built in to them. If you want to run an encrypted website, you really need to have a certificate that’s signed by one of these trusted CAs or your users will get horrible warnings when they try to access your site. It used to be that getting a certificate signed by one of these trusted CAs was hideously expensive – tens of thousands of pounds. These days, there is the Let’s Encrypt project. They are a CA who give away certificates. You can’t use them to prove that you are who you say you are, but you can use them to prove that you control the server the certificate is issued for. This is enough to set up a trusted HTTPS web server. The only people who are likely to have trouble with it are those running Windows XP and frankly they deserve everything they get.
On the MQTT side, I have created my own root certificate and use it to sign the certificates used by the ESP8266 and the web server. These are never publicly visible and all I want to be certain of is that the certificates used to connect to mosquitto are ones that I have signed, not someone trying to connect without a certificate I issued.
Create your CA certificate/key pair like this:
$ openssl req -new -x509 -days 1095 -extensions v3_ca -keyout ca.key -out ca.crt
This creates a new key and certificate pair that we will use to sign other certificates. A couple of things to note here:
- Keep your key (ca.key) safe! Anyone who gets hold of it can sign certificates and you won’t be able to tell you didn’t sign them.
- Mark in your diary now a day just short of three years from now to renew your certificates. That 1095 on the command line is three years and after that your CA certificate will expire. It is not likely you will remember this until everything stops working – rather embarrassing.
Next, create a key and a certificate request for mosquitto:
$ openssl genrsa -out mosquitto.key 2048 $ openssl req -out mosquitto.csr -key mosquitto.key -new
And sign it with your CA key:
$ openssl x509 -req -in mosquitto.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out mosquitto.crt -days 1095
You now have a key/certificate pair, called mosquitto.key and mosquitto.crt. Put them in /etc/mosquitto/certs. Also, put ca.crt (NOT ca.key) in /etc/mosquitto/ca_certificates.
Repeat the process above to create a key pair for your ESP8266 (esp8266.key / esp8266.crt) and python framework (server.key / server.csr).
Nginx configuration
We start by getting a certificate from Let’s Encrypt. Stop nginx:
$ sudo service stop nginx
Next, download the Let’s Encrypt software and request a certificate
$ git clone $ cd letsencrypt
$ sudo ./letsencrypt-auto certonly --standalone
I had to run this a few times before it worked, apparently just because the Let’s Encrypt servers are a bit overloaded. It will ask you some questions along the way, most importantly what the server you want the certificate for is called. You have to get this right, and it has to be the server where you are actually running these commands!
Once this completes successfully, you should have a directory called /etc/letsencrypt that contains the key and certificate that has been created. In particular, you should have /etc/letsencrypt/live/a.example.com (substitute in the name of your site) which will contain:
- cert.pem – your web server’s certificate
- chain.pem – not sure what this is
- fullchain.pem – combination of cert.pem and chain.pem
- privkey.pem – your web server’s private key
Now create a file called /etc/nginx/sites-available/a.example.conf (the actual name of this file doesn’t matter, so long as it’s in the right directory) and put this in it:
# Declare a back-end server listening on port 8100 that we will # hand requests on to upstream ha { server 127.0.0.1:8100; } # Declare our server server { listen 443 ssl; # Listening on the default SSL port for SSL connections server_name a.example.com; client_max_body_size 1000M; # You could reduce this... keepalive_timeout 15; # Configure it to use our shiny new certificate ssl_certificate /etc/letsencrypt/live/a.example.com/cert.pem ssl_certificate_key /etc/letsencrypt/live/a.example.com/cert.pem ssl_session_cache shared:SSL:10m; ssl_session_timeout 10m; ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Only use newer protocols ssl_ciphers 'EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH'; # Only use reasonably secure ciphers ssl_prefer_server_ciphers on; location / { proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Protocol $scheme; proxy_pass; # This is the back end we declared above } location /static/ { root /home/me/ha/static; } location /robots.txt { root /home/me/ha/static; } location /favicon.ico { root /home/me/ha/static; } }
This sets up the server so that it serves /robots.txt, /favicon.ico and anything under /static/ straight from the filesystem, and forwards everything else on to our Python framework which is (or will be) listening on port 8100. We serve these files directly in nginx because it is a lot more efficient at doing so than Flask is.
Python configuration
Log in to the VPS and activate our Python virtualenv:
$ . ha/bin/activate (ha) $
Now, create a basic web service in ~/ha/project/ha/wsgi.py with this content:
from flask import Flask application = Flask(__name__) application.config.from_object('ha.settings') @application.route('/') def index(): return 'Hello, world!'
This just returns the string ‘Hello, world!’ whenever someone tries to access our server. By the way, the ‘ha’ name that keeps coming up isn’t special, it’s just what I decided to call my project (originally it stood for ‘home automation’ though my ambitions have got less grand).
Next create ~/ha/project/ha/gunicorn.conf.py:
command = '/home/tkcook/ha/bin/gunicorn' pythonpath = '/home/tkcook/ha' bind = '127.0.0.1:8100' workers = 2 user = 'me'
This is just a Python file with variables to configure the WSGI container, gunicorn. It will run two worker threads and listen on port 8100 (this has to match what you put in the nginx configuration).
Lastly, we’ll use a programme called ‘supervisor’ to run gunicorn as a service. Create /etc/supervisor/conf.d/ha.conf:
[group:ha] programs=gunicorn_ha [program:gunicorn_ha] command=/home/me/ha/bin/gunicorn -c gunicorn.conf.py -p gunicorn.pid ha.wsgi directory=/home/me/ha/project user=me autostart=true redirect_stderr=true environment=LANG="en_US.UTF-8",LC_ALL="en_US.UTF-8",LC_LANG="en_US.UTF-8"
Now you can start your Python framework service:
$ sudo supervisorctl start ha:*
Supervisor is actually quite sophisticated and we’re not really using much of its capabilities here. It can set up groups of programmes that can be started and stopped together but we have just one group with one programme.
Finally, restart nginx:
$ sudo service nginx restart
and you should be able to open (or whatever your server is called) and it should respond with ‘Hello, world!’. Phew!
Mosquitto configuration
Create /etc/mosquitto/conf.d/local.conf (actually the name doesn’t matter, so long as it’s in that directory and ends in ‘.conf’):
allow_anonymous false password_file /etc/mosquitto/passwd listener 8883 cafile /etc/mosquitto/ca_certificates/ca.crt keyfile /etc/mosquitto/certs/mosquitto.key certfile /etc/mosquitto/certs/mosquitto.crt require_certificate true
Create the password database like this:
$ sudo mosquitto_passwd -c /etc/mosquitto/passwd esp8266_user $ sudo mosquitto_passwd /etc/mosquitto/passwd python_user
Enter a suitable password when prompted. Restart mosquitto:
$ sudo service mosquitto restart
You should now have an MQTT server listening on port 8883. It will only accept clients that present a certificate signed by your CA.
Code
I won’t present all my ESP8266 code here, just the bit to do with connecting to the MQTT server.
I’m using the Arduino platform support for ESP8266; if you’re using some other programming system for the ESP8266, you’ll have to figure out things for yourself.
Note that the ESP8266 is just powerful enough to do TLS encryption. You’ll need to make sure the CPU is running at 160MHz, not 80MHz or else the hardware watchdog trips while connecting to the server and the thing reboots. Even running at 160MHz I’ve had it reboot occasionally if the server takes too long to respond.
I’m using the pubsubclient Arduino library available here for the MQTT connection. It has a port to ESP8266 and a reasonable ESP8266 example; the hard thing is that the example doesn’t cover using TLS. Here’s a brief sketch of how it’s done:
#include <ESP8266WiFi.h> #include <PubSubClient.h> #include "certificates.h" WiFiClientSecure espClient; PubSubClient client(espClient); void setup() { WiFi.begin("my_ssid", "my_password"); while(WiFi.status() != WL_CONNECTED) delay(500); espClient.setCertificate(certificates_esp8266_bin_crt, certificates_esp8266_bin_crt_len); espClient.setPrivateKey(certificates_esp8266_bin_key, certificates_esp8266_bin_key_len); client.setServer("a.example.com", 8883); client.setCallback(callback); } void reconnect() { while(!client.connected()) { if(client.connect("ESP8266Client", "esp8266_user", "your_password_here")) { // Resubscribe to all your topics here so that they are // resubscribed each time you reconnect } else { delay(500); } } } void loop() { if(!client.connected()) { reconnect(); } client.loop(); // Your control logic here }
Basically, to connect to MQTT using TLS, you just use WiFiClientSecure instead of WiFiClient and set the certificate and private keys before connecting. The tricky bit really is generating the file certificates.h. Openssl by default generates keys and certificates in a human-readable text format, but here we need them in binary. Openssl can get us part of the way by converting a text file to a binary one; Ubuntu provides the xxd utility to get us the rest of the way by converting the binary file to a C array definition we can use directly in our code. First convert the text files to binary ones, putting the result in a directory called certificates:
$ mkdir certificates $ openssl x509 -in esp8266.crt -out certificates/esp8266.bin.crt -outform DER $ openssl rsa -in esp8266.key -out certificates/esp8266.bin.key -outform DER $ xxd -i certificates/esp8266.* $ cat certificates/esp8266.* > certificates.h
Now if you look in certificates.h, you will find two C arrays called certificates_esp8266_bin_crt and certificates_esp8266_bin_key, and two variables with their lengths, which you can use directly when setting up the WiFiClientSecure instance.
There are quite a few things that can go wrong in this process and I can’t remember all of the dead ends I went down. Here are a few:
- All the certificates have to be signed by your CA!
- Remember to set the ESP8266 to run at 160MHz.
- You may also have to disable the software watchdog timout – use ESP.wdtDisable() to do this.
- Error messages at both the mosquitto end and the ESP8266 end are pretty unhelpful. Make sure all your certificates are set up right and that your username and password is correct; otherwise you just get generic TLS failure messages with no indication what is wrong.
Python MQTT Connection
Again I’m not going to paste all my code here, but here’s a sketch of how to connect to the MQTT server from Python:
import paho.mqtt.client as paho client = paho.Client() client.tls_set("ca.crt", certfile="server.crt", keyfile="server.key") client.username_pw_set("python_user", password="your_password_here") client.connect("a.example.com", port=8883) client.loop_start()
There are a couple of options for how to make the client loop; you can either set off a background thread as I have done above, or you can call .loop() regularly to process incoming messages.
Using MQTT
MQTT, as I said above, is a publish-subscribe messaging system. So, in my example, I’ve assigned an ID to each ESP8266. Each ESP8266 then subscribes to a topic whose name is this ID, in hexadecimal. So if the device ID is 0xDEADBEEF1234, it subscribes to ‘/DEADBEEF1234’. The webserver then publishes commands on this topic which the ESP8266 broadcasts over the 433MHz radio.
For more complex scenarios, more complex topics can be constructed. For instance, I could have a topic called ‘/DEADBEEF1234/temperature’ where the ESP8266 could publish a measured temperature, ‘/DEADBEEF1234/command’ where the webserver could publish commands and so on. You can subscribe to ‘/DEADBEEF/+’, which would match either ‘/DEADBEEF1234/temperature’ or ‘/DEADBEEF1234/command’, or you can subscribe to ‘/DEADBEEF/#’ which will match either of them as well as ‘/DEADBEEF1234/measurements/measurement1’ and so on. That is, a ‘+’ matches any string but only one path level, while ‘#’ matches any string and any number of path levels.
At the moment, I’m using the value returned by ESP.getChipId() as the unique identifier. This has a couple of issues:
- It’s only 24 bits, so there are only ~16.9 million unique devices possible. That’s not a small number, but I don’t think it’s impossible that more ESP8266 devices than that will be made. Collisions would be bad – it would let two people turn each others lights on and off (for example).
- It’s the bottom 24 bits of the MAC address. This is a bit more serious. Anyone who can connect to the WiFi network can see the devices MAC address, and once you know the MAC address you are about half way to being able to control it. My database setup means that I record which users are associated with which devices and only those users can control those devices through the web interface. But if someone got hold of a client key and certificate then they could use them to connect directly to the MQTT server and control any device for which they know the MAC address. Or they could just flood the system with messages for random device IDs and see what havoc they could cause! And where would they get the client key and certificate? Well, they come burned into the flash of the ESP8266 device. So once I start selling these, I’m also giving away the key to connect directly to the MQTT server, if someone is keen enough to download the flash from the ESP8266 and figure out which bits are the key, certificate, username, password and hostname for the MQTT server. I haven’t figured out a good way around this yet!
Web Client Authentication
Authenticating web users is one of the hardest bits of this to get working, and one of the hardest bits to get right. Once again I’ll sketch how I went about it here, but whether what I’ve done will be suitable for you will depend a lot on what you want to achieve. In particular, I just wanted to require that a user have a Google account to for Google to authenticate them for me. If you want to use other services, you’re on your own from here.
First you need to set up an application in your Google developer’s console. Go to. Create a new project. Open the API Manager screen and click on Credentials. Create an OAuth Client ID. You will have to fill in some details for the OAuth consent screen the user will be presented with when logging in. Note the client ID and client secret. The type should be set to ‘Web Application’.
You need an object type to store user details in. I’m using a PostgreSQL database to store my data and SQLAlchemy to access it in Python. That’s not very important, so long as you have some sort of User object. Here’s the guts of mine:
from sqlalchemy import create_engine, Column, Integer, String, Boolean from sqlalchemy.orm import scoped_session, sessionmaker from sqlalchemy.ext.declarative import declarative_base from ha.settings import DB_USER, DB_PASS from flask.ext.login import UserMixin # ha is the database instance name engine = create_engine('postgresql+psycopg2://' + DB_USER + ':' + DB_PASS + '@localhost/ha') db = declarative_base() db_session = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=engine)) class User(db, UserMixin): __tablename__ = 'users' id = Column(Integer, primary_key = True) email = Column(String) active = Column(Boolean, nullable = False, default = False) fname = Column(String) lname = Column(String) accesstoken = Column(String) username = Column(String(400)) @property def is_authenticated(self): return True @property def is_active(self): return self.active @property def is_anonymous(self): return False @property def get_auth_token(self): return self.accesstoken
I’ve put this in models.py, putting it in a module called ha.models. Don’t forget to create the matching schema in your database.
Then in my wsgi.py:
import ha.models, ha.settings from flask import Flask, redirect, render_template, session, jsonify, g, url_for, abort from flask.ext.login import LoginManager, current_user, login_user, logout_user, login_required from social.apps.flask_app import routes from social.apps.flask_app.routes import social_auth from social.apps.flask_app.template_filters import backends from social.apps.flask_app.default.models import init_social from social.apps.flask_app.default import models application = Flask(__name__) application.config.from_object('ha.settings') application.register_blueprint(social_auth) init_social(application, ha.models.db_session) login = LoginManager() login.login_view = 'login' login.init_app(application) @login.user_loader def load_user(id): return ha.models.db_session.query(ha.models.User).get(int(id)) @login.token_loader def load_user_from_token(token): return ha.models.db_session.query(User).filter(User.accesstoken == token).first() @application.before_request def global_user(): g.user = current_user @application.teardown_appcontext def commit_on_success(error=None): if error is None: ha.models.db_session.commit() else: ha.models.db_session.rollback() ha.models.db_session.remove() @application.context_processor def inject_user(): try: return {'user': g.user} except AttributeError: return {'user': None} application.context_processor(backends) @application.route('/login') def login(): return redirect(url_for("social.auth", backend="google-oauth2")) @login_required @application.route('/') def index(): if g.user.is_anonymous: return redirect(url_for('login')) if not g.user.is_active: return redirect(url_for('nouser')) return render_template('index.html') @login_required @application.route('/logout') def logout(): logout_user() return redirect('/') @application.route('/nouser') def nouser(): return render_template('nouser.html')
There’s a lot to get your head around here. Essentially, the python_social_auth package handles authentication for you. Given the configuration at the beginning, you can then decorate any web endpoint with ‘@login_required’ and Flask will automatically redirect any non-logged-in user to the Google login service before letting them access that page.
When someone new accesses your service, they’ll get registered in your database. You’ll then have to have some mechanism to check that they really are someone you want accessing your service and make them active. At the moment I’m the only user of my service and I’ve manually updated my database to make my account active; if you’re aiming for the big time, you’ll need something better than this.
I think the only thing left that is very mysterious here is the ‘ha.settings’ module. It is just a file called settings.py which contains:
SECRET_KEY='something nice and random here' SESSION_COOKIE_NAME='ha_session' SESSION_PROTECTION='strong' SOCIAL_AUTH_LOGIN_URL='/login' SOCIAL_AUTH_REDIRECT_URL='/' SOCIAL_AUTH_LOGIN_REDIRECT_URL='/' SOCIAL_AUTH_USER_MODEL='ha.models.User' SOCIAL_AUTH_AUTHENTICATION_BACKENDS=('social.backends.google.GoogleOAuth2',) SOCIAL_AUTH_USERNAME_IS_FULL_EMAIL=True SOCIAL_AUTH_REDIRECT_IS_HTTPS=True SOCIAL_AUTH_GOOGLE_OAUTH2_KEY='Your Google oauth2 key here' SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET='Your Google oauth2 secret here' DB_USER='Your database username here' DB_PASS='Your database password here' SERVER_NAME='a.example.com'
Randomness really does matter in your SECRET_KEY. Try this to get some reasonable randomness:
$ head -1 /dev/urandom | base64
And, as a final trap for your players, don’t forget to exclude this file from source control before you push it all to github!
Conclusion
Putting all these together took me quite a few hours of puzzling through stuff. I hope a description of a real-world setup, with encryption throughout, is helpful to people. If there’s things that are not clear please comment below and I’ll try to clear it up. | https://nofurtherquestions.wordpress.com/2016/03/14/ | CC-MAIN-2017-13 | refinedweb | 4,380 | 57.67 |
Red Hat Bugzilla – Bug 65357
(VM)If ptrace() modifes a page, the child program can as well.
Last modified: 2008-08-01 12:22:52 EDT
From Bugzilla Helper:
User-Agent: Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 4.0; T312461)
Description of problem:
If you are debugging a program and modify read only pages (by setting
a breakpoint, for example), then the modified pages are now writable
by the user process being debugged as well.
Version-Release number of selected component (if applicable):
How reproducible:
Always
Steps to Reproduce:
1. Compile attached bug.c program (with -g)
2. Run it and watch it segfault
3. Now run gdb on the program.
4. Set a breakpoint at *&main
5. Let the program run to the breakpoint, then continue it.
6. Watch the program run with no errors and overwrite &main.
Actual Results: Program does not segfault.
Expected Results: Program should segfault. Just because it is running under
the debugger, read/execute pages should not become writable.
By the way: The /proc address map info still shows the page
as read/execute even though it really is writable after you
set the breakpoint.
Additional info:
Here is the bug.c source code (its small):
#include <stdio.h>
int
main(int argc, char ** argv) {
int * mainprog = ((int *)(void *)&main);
printf("Main program starts at %#x\n", mainprog);
printf("First word looks like 0x%08x\n", *mainprog);
printf("About to try writing on it...\n");
fflush(stdout);
*mainprog = 0xdeadbeef;
printf("First word now looks like 0x%08x\n", *mainprog);
fflush(stdout);
return 0;
}
Since ptrace changes quite a bit per kernel version, could you specify which
kernel version(s) you have tested ?
I tried several different linux systems, and it failed on all of
them (including a 2.4.18 kernel we have some custom mods in).
The redhat 7.1 system it failed on first is running 2.4.9: | https://bugzilla.redhat.com/show_bug.cgi?id=65357 | CC-MAIN-2018-09 | refinedweb | 320 | 68.36 |
A class declaring or inheriting at least one virtual function contains a virtual function table (or vtable, for short). Such a class is said to be a polymorphic class. An object of a polymorphic class type contains a special data member (a "vtable pointer") which points to the vtable of this class. This pointer is an implementation detail and cannot be accessed directly by the programmer (at least not without resorting to some low-level trick). In this post, I will assume the reader is familiar with vtables on at least a basic level (for the uninitiated, here is a good place to learn about this topic).
I hope you learned that when you wish to make use of polymorphism, you need to access objects of derived types through pointers or references to a base type. For example, consider the code below:
#include <iostream> struct Fruit { virtual const char* name() const { return "Fruit"; } }; struct Apple: public Fruit { virtual const char* name() const override { return "Apple"; } }; struct Banana: public Fruit { virtual const char* name() const override { return "Banana"; } }; void analyze_fruit(const Fruit& f) { std::cout << f.name() << "\n"; } int main() { Apple a; Banana b; analyze_fruit(a); /* prints "Apple" */ analyze_fruit(b); /* prints "Banana" */ return 0; }
So far, no surprises here. But what will happen if instead of taking a reference to a Fruit object on analyze_fruit, we take a Fruit object by value?
Any experienced C++ developer will immediately see the word "slicing" written in front of their eyes. Indeed, taking a Fruit object by value means that inside analyze_fruit, the object f is truly a Fruit, and never an Apple, a Banana or any other derived type:
/* same code as before... */ void analyze_fruit(Fruit f) { std::cout << f.name() << "\n"; } int main() { Apple a; Banana b; analyze_fruit(a); /* prints "Fruit" */ analyze_fruit(b); /* prints "Fruit" */ return 0; }
This situation is worth analyzing in further detail, even if it seems trivial at first. On the calls to analyze_fruit, we pass objects of type Apple and Banana as arguments which are used to initialize its parameter f (of type Fruit). This is a copy initialization, i.e., the initialization of f in both of these cases is no different from the way f is initialized on the code fragment below:
Apple a; Fruit f(a);
Even though Fruit does not define a copy constructor, one is provided by the compiler. This default copy constructor merely copies each data member of the source Fruit object into the corresponding data member of the Fruit object being created. In our case, Fruit has no data members, but it still has a vtable pointer. How is this pointer initialized? Is it copied directly from the input Fruit object? Before we answer these questions, let us look at what the compiler-generated copy constructor of Fruit looks like:
struct Fruit { /* compiler-generated copy constructor */ Fruit(const Fruit& sf): vptr(/* what goes in here? */) { /* nothing happens here */ } virtual const char* name() const { return "Fruit"; } };
The signature of the Fruit copy constructor shows that is takes a reference to a source Fruit object, which means if we pass an Apple object to the copy constructor of Fruit, the vtable pointer of sf (for "source fruit"), will really point to the vtable of an Apple object. In other words, if this vtable pointer is directly copied into the vtable pointer of the Fruit object being constructed (represented under the name vptr on the code above), this object will behave like an Apple whenever any of its virtual functions are called!
But as we mentioned on the second code example above (the one in which analyze_fruit takes a Fruit object by value), the Fruit parameter f always behaves as a Fruit, and never as an Apple or as a Banana.
This brings us to the main lesson of this post: vtable pointers are not common data members which are directly copied or moved by copy and move constructors respectively. Instead, they are always initialized by any constructor used to build an object of a polymorphic class type T with the address of the vtable for the T class. Also, assignment operators will never touch the values stored by vtable pointers. In the context of our classes, the vtable pointer of a Fruit object will be initialized by any constructor of Fruit with the address of the vtable for the Fruit class and will retain this value throughout the entire lifetime of the object. | https://diego.assencio.com/?index=e5f2a59886a83b5c7d2c0093dbf689f9 | CC-MAIN-2019-09 | refinedweb | 740 | 53.65 |
Deep learning in Go
The battle for Cloud — Story of “GO”KU
Deep learning and Machine learning hasn’t quite been the stronghold for Go! But, the enthusiasm for AI in the GO community has been growing.
This fun-filled, illustration based article, talks about the fundamentals of Machine learning and sheds light on the state of Deep learning in Go.
This is the Story of the “GO”KU and his quest to conquer Deep Learning!
Introducing “Go”Ku!
“GO”ku in the quest to collect all the Dragon Balls to be able to win the Cloud wars.
“GO”KU waged hard-fought battles in pursuit of the Cloud Dragon Balls!
This was the beginning of Cloud wars!
And then, “GO”ku was successful with the conquest of the Cloud Native, API, Devops and Database Dragon Balls. This led to the creation of multiple amazing projects in Go.
DGraph (A Graph Database), Minio (An Object Storage ), CockroachDB (Distributed SQL), Etcd (Distributed Key-Val store), Kubernetes (For automating application deployment, scaling, and management) and Docker (No need for the mention) emerged from “GO”Ku’s possession of the DB’s!
“GO”Ku is not done yet! He is getting prepared for the most gruelling battle so far! The battle for AI/ML Dragon Ball.
Deep learning in Go!
Let’s do some explicit programming to understand what Machine learning is?
Game of functional mapping
Consider the table above. What’s the relationship between X and Y?
Well, that’s easy isn’t it. Y = 2X
Let’s see something that’s slightly difficult.
What’s the relationship between X and Y here?
In this case its slightly complex, its Y = 2 * X * X
That’s what we mean when we that say the relationship between X and Y is more complex!
Machine learning or Deep learning is used when you want to automate this process of finding a functional mapping between inputs and outputs on a large number of examples, thus finding the relationship/pattern which can later be used to make a future prediction to take valuable business decisions.
As the complexity of relationship between X and Y increases Deep learning starts to shine!
X and Y can be different! If X is text in English and Y is its corresponding text in French, once you find the pattern between them using Deep learning, what you essentially have is an AI for language translation! The same applies for a variety of X’s and Y’s.
Now imagine X to images of Apples and Oranges, and Y is either 0 (for Apple) or 1 (Orange).
Now let’s write a program with explicit logic to distinguish between them,
Let’s say explicit programming works for classifying between Apple’s and Oranges.
But how about writing explicit rules to distinguish between Dog breeds!?
It's a hard problem, in this case, you would let Deep learning do its Magic.
You feed the Deep learning code with a large number of example images of different dog breeds and let it find a pattern in them. Later it could use this understanding to be able to predict the breed of new dog images.
Hey, there are so many breeds of dogs and these images could look very different? How could it understand this pattern in pixels just with few images and identify the pattern?
We’ll as rightly guessed, it's not possible to generalize the pattern just with few images. You need a lot and lots of data to be able to do this.
How does Deep learning do what it does?
Deep learning uses the concepts of neurons and weights.
Weights are the edges in the Neural Network, consider them as the tunable knobs. The nodes are the data using which we try to find the pattern between X and Y.
The Learning / Training in Deep learning involves finding values for these tunable knobs called weights so that the functional mapping between X and Y is as accurate as possible. The algorithm used is called as a Model. The entire process of finding values for these knobs are computationally intensive, so you would save these values of weights/knobs, which would be later used to make predictions. This is called the Saved model / Trained model. These values can be later loaded into another program without having to train the model again.
We’ve already seen 5 major aspects in the Deep learning process,
- Data
- The Algorithm / Model.
- Learning / Training
- Prediction
- The trained model.
Here are some exerts from the Tensorflow official site which gives an amazing explanation about Machine learning
How to do Deep learning?
Welcome to Tensorflow?
TensorFlow is an end-to-end open source platform for machine learning.
Tensorflow is not just a Machine Learning specific library, instead, is a general-purpose computation library that represents computations with graphs. Its core is implemented in C++ and there are also bindings for different languages. The bindings for the Go programming language, differently from the Python ones, are a useful tool not only for using Tensorflow in Go but also for understanding how Tensorflow is implemented under the hood.
Tensorflow fundamentals: Tensors and computation graphs
First, we’re going to take a look at the tensor object type. Then we’ll have a graphical understanding of TensorFlow to define computations. Finally, we’ll run the graphs with sessions, showing how to substitute intermediate values.
Tensors
In TensorFlow, data isn’t stored as integers, floats, or strings. These values are encapsulated in an object called a tensor, a fancy term for multidimensional arrays. If you pass a Python list to TensorFlow, converts it into a tensor of the appropriate type.
You’ll hold constant values in
tf.constant.
You can perform computations on the constants, but these tensors won’t be evaluated until a session is created and the tensor is run inside the session.
Tensorflow Session
Everything so far has just specified the TensorFlow graph. We haven’t yet computed anything. To do this, we need to start a session in which the computations will take place. The following code creates a new session:
sess = tf.Session()
TensorFlow’s API is built around the idea of a computational graph, a way of visualizing a mathematical process.
Running a session and evaluating a tensor
The code creates a session instance, sess, using tf.Session. The sess.run()function then evaluates the tensor and returns the results. Once you have a session open,
sess.run(NN) will evaluate the given expression and return the result of the computation.
After you run the above, you will see the Hello World printed out:
import tensorflow as tf# Create TensorFlow object called hello_constant
hello_constant = tf.constant('Hello World!')with tf.Session() as sess:
# Run the tf.constant operation in the session
output = sess.run(hello_constant)
print(output)
Computation graph
The computations are structured in the form of a graph in tensorflow, Let’s dive a bit more into the computational graph and understand how computation graphs are formed,
Consider a simple computation. Let a, b, c be the variables used,
J = 3 * ( a + bc )
There are 3 distinctive computational steps to arrive at the final value J, let’s list them out,
These are 3 computational steps which can be represented as a graph,
Note: Refer to one of my previous blogs to continue reading more about Tensorflow.
TensorFlow™ is an open source software library for numerical computation using data flow graphs. Nodes in the graph represent mathematical operations, while the graph edges represent the multidimensional data arrays (tensors) communicated between them.
Let’s create a simple Graph of computation to multiple two matrices,
A = [ 1 2 ]
[ -1 -2 ] x = [ 10 ]
[ 100 ]
It's really simple to achieve this Python. Here is the link to notebook where you could run the code
State of Deep learning in Go
The Go binding API for Tensorflow is designed to use trained models and not for training models from scratch
TensorFlow provides APIs for use in Go programs. These APIs are particularly well-suited to loading models created in Python and executing them within a Go application.
Let’s see how the program to multiply two matrices look in Go,
Credits: Galeone Github
This doesn’t seem to be easy and intuitive at all!
Here is an example test from Tensorflow Go repo to load an inception model and make the prediction.
Inception v3 is a widely-used image recognition model that has been shown to attain greater than 78.1% accuracy on the ImageNet dataset. ImageNet is an ongoing research effort to provide researchers around the world in an easily accessible image database.
Let’s take the trained model, use Go to load it and make predictions,
$ git clone
$ cd inception-go
$ docker build -t inception-go
$ docker run -p 8080:8080 --rm inception-go
Summary
- If you are a Deep learning engineer who is comfortable with Python, there is no need to use Go for Deep learning!
- But if you are Go developer with aspirations on developing Deep learning applications then it makes sense to abstract yourself from the Deep learning concepts, take the trained model built using python, load it in Go, Containerize it and build applications.
- Deep learning community comprises of a wide range of audience. Mathematicians, Scientists, Statisticians, Developers, Doctors, Physicists and much more. Python doesn’t look intimidating for non-developers.
- Deep learning training is not expected to run in real time.
- The algorithms are computation and memory intensive, the performance gain via just transitioning to Go would be not so significant!
All I can say is!
GOku’s goal to conquer AI/ML Dragon Ball seem to be farfetched as of today! Let’s hope that he gets there for the good of the Go community.
Let’s cheer for him,
GO GOku GO !
For more articles and updates follow me at twitter.com/@hackintoshrao. | https://medium.com/@hackintoshrao/deep-learning-in-go-f13e586f7d8a | CC-MAIN-2022-33 | refinedweb | 1,653 | 63.49 |
What that use DLP projectors to do just this. (And there have been open-source designs since at least 2012.)
The question is, does it work with a cellphone’s relatively weak light source?
Honestly, we can’t see why it wouldn’t, but we’re not chemists and the secret is going to be in the sauce. That being said we’re excited at the concept of such an inexpensive resin 3D printer. OLO also promises inexpensive photopolymers, which is a big deal because cost-per-volume has been Achilles’ heel of resin printers.
What do you think? Too good to be true? Will you be content with a build surface that’s limited to the size of your phablet’s screen? As with all crowd-funding projects, you should do some serious research before you back anything — especially when it comes to 3D printers. But for only $99…
[via Digital Trends]
170 thoughts on “A $99 Smartphone Powered 3D Printer?”
The technology of these $99 3D printer Kickstarters is hardly even the problem anymore. I refuse to trust any new campaign that doesn’t take a practical look at all the other FAILED campaigns in their market sector, analyze what went wrong, and explain why this team is any different.
I love how everyone is kicking down this project, but crackpot EmDrive is the top liked project in the HaD prize.
I think the difference is, on this one the author said, “we can’t see why it wouldn’t [work]”, while the EmDrive article says right up front that it violates Newton’s 3rd law. It’s one thing to try to build an EmDrive (or a perpetual motion machine, or a magic box that you can pull finished plastic parts out of), it’s another to pretend you have a working product and are asking for money to bring it to production.
But you must remember that the Hackaday audience is not a heterogeneous blob – it is comprised of everybody from those who beam with pride over the blinking LED on their Arduino, to those who play with electron microscopes in their garages and build transistors in their kitchens. (“Hydrofluoric acid isn’t as scary as people seem to think it is.”)
Tried to find out any info on the principals of OLO 3D INC. The address they give is an incubator space. An online search at the California Sec. of State website comes up empty for OLO 3D and OLO3D. Claiming to be incorporated when not is a crime. Legit business post these things on there websites. Maybe I can’t see it thru all the flash on the OLO site. If anyone finds any incorporation information, I’d like to see it.
What exactly is your goal with your statements?
1) Em Drive guy us doing it for fun, as a hobby, with his own time and money – and he is documenting everything, its a great and fun read, he is making neat devices, doing careful measurements, and is certainly not claiming his EM drive ‘works’.
2) Olo is people both hiding behind a moniker, not putting their names on their work, and using renderings to sell a fake product.
What exactly is the correlation?
The price tag isn’t hard to believe…look at the Peachy printer(still waiting for mine though). The problem with Kickstarter and the like is that they don’t require a working, ship-able product before taking the money from you. This is inherently going to draw a crowd of shysters looking to subvert the system for quick buck making schemes. That’s also why you see so many failed attempts.
Kickstarter isn’t a store, it’s an investment vehicle. Those have ALWAYS drawn quick-buck schemers. It’s up to the investor not Kickstarter to determine if what they’re offering is too good to be true.
‘A Working ship-able product’ is supposed to the end product of what you’re funding, but like any other investment, it may fail, sometimes spectacularly. (I should know, I was one of the folks who funded the Buccaneer 3D printer fiasco)
Then SEC should be involved. Its not an investment, it is new-economy grey area and criminal profiteering, among other more positive things.
Kickstarter and other crowd sourced funding vehicles are not an investment. It’s a promise, at best. You are not receiving equity in the company. You and many others are giving people money in order for them to try to get their start or put together a product with some type of economy of scale numbers present. Sometimes that works out well, other times it does not. But you are not “investing” in anything except the idea that you might get something close to what they promised you. Maybe. Looking at you, Peachy Printer.
No. Investors get a return (a share of future earnings based on their ownership in the company). All you get is the product IF they’re successful. That’s like going into a store and buying a box of cookies, but there’s a high x% chance the box will actually be empty. And if it is empty, too bad, because it was “an investment”.
The whole premise of this is completely bone-headed. How can they guarantee a $99 price point without working prototypes? They have no bill of materials, therefore they can’t possibly have suppliers or anything resembling a fabrication facility, so they don’t know that cost either.
If Kickstarter is an investment site, it’s about the worst one in human history.
Look at the price of the thing that you didn’t get delivered? That’s a bit odd.
Problem I have with kickstarters like these is simple, they have a slick design. Slick marketing. That’s already a red flag for me. Design does not make a product. Design pushes and sells a product, but does not make a working product.
Agreed — Kickstarter is a dream-come-true for products like this. Very large hype factor, The validity of the item is irrelevant. Customers pay up-front. Usability of item received, if shipped at all, questionable. Allows for large “oops, sorry-you-don’t-like-it” factor. Backers: what do you think you’re gaining by being guinea pigs? Trust me, OLO won’t turn you away 6 months from now, if you decide to purchase one thru more standard channels. You are not supporting some guy in his garage, low on funds, trying to develop something, that standard funding would find too obscure to support. Instead, you are helping some guys with great marketing savvy, prove that humans are morons. Please wait until you hear the buzz about the printers received, before parting with your cash …
I agree but you’re already partially falling for the marketing hype, because you’re thinking “past the delivery”, i.e. you’re assuming they will actually build it and ship it. There’s no proof at this point that they can actually build this thing at all. Additionally, even if they do manage to build it, there’s no evidence they can keep the cost under $99.
Jonny O,
When I said ” Please wait until you hear the buzz about the printers received, before parting with your cash …”, I should have added ” if they are ever received. Don’t put me in the “wow this is so awesome” or even “could happen” group. I’m likely the most fervent, in the belief that there is no printer. You’re totally correct about the price point. I bet, they never even tried to figure out how much it would cost to manufacture. Again, it’s just marketing. $99 is a great number for catching the most suckers. Not so low as to raise suspicion. Low enough, so that even suspicious backers are fine taking a chance. If they did actually have a printer, believe me, they wouldn’t be scrounging money on kickstarter.
How’s this logic:
This is a MUST-HAVE Christmas Holiday gadget. 100 million+ households (US only.) With even only a $10 profit margin, one can see the incredible potential. Had they actually peddled a working printer to any large manufacturer, I’m sure they would have realized how lucrative a business venture this could have been. $2M on Kickstarter would be a joke in comparison.
SO: WHY DID THEY GO THE KICKSTARTER ROUTE? Because the virtual printer itself doesn’t get scrutinized. As long as most of what they claim appears plausible / possible to the masses, they will have success. The performance. or even existence of the printer is shielded. When you think about it, in the real world the printer is the product, on Kickstarter, the CAMPAIGN is the product. Backers WANT TO BELIEVE they are buying a printer, but they are buying into a campaign, and will get what they paid for.
Although it may just about work, I suspect it will be very disappointing – poor resolution, slow and messy.
You define that as “working”?
If you are able to print out an object this way, even if it’s fuzzy and messy, yes, it’s working.
I strongly disagree.
Look at their marketing images and draw your own conclusion on the implied performance.
You have extremely low standards. They are offering a product, not a experimental mess.
this is fishy at least…
I dont think it is that fishy, it just is not a good CX, You can’t use your phone while it prints.
Not really a problem, most people have at least one last-gen phone lying around in a drawer somewhere. In my household I think we have about six!
This is obviously a joke. anyone want to bet the cost of the printer that this will never work out.
The people in the video look like scam artists. The kickstarter rules, as usual, are ignored, in that there is obviously no working prototype of this ‘idea’.
It barely rises to the level of ‘an idea’, so much as being ‘fanciful nonsense’.
All that rendering and marketing effort to advertise a scam. People are not getting paid what their skills are worth in private sector, so they now are turning on the citizens.
For what it’s worth I had a chat to one of my material engineering colleagues and his impression was that it’s probably genuine. Supposedly the secret is osmosis: you have a selectively permeable membrane at the bottom of the container that allows oxygen to diffuse though and contact the resin. Sounds like it’s all very fidgety though, calibration is tricky and it’s very susceptible to environmental conditions as well as ongoing changes to the membrane itself.
Oh there is some physical reality at play – you apply light to light sensitive resins and they harden.. Yes, yes. .Good.. You can also add a membrane and get AMAZING increases in speed. Yes! YES.
However, this is still a scam. Why? Because a group of people are taking in money on 3d renderings and outright misrepresentations, then being silent when questioned.
This is scam artist behavior.
Protip: sell your old phones and buy a 3d printer
lol
Printer might be $99 but im going to expect ink prices to be off the charts
It costs 15$ per 100ml bottle. That puts it on par or cheaper than other resin printers.
My main issue is that MOST photosensitive resins require UV and they clearly state that they are using the white light from the screen. If it works, this does have some scalability. Imagine a unit that worked like this with a 4k TV as the screen….
My first thought when I saw this was that it’ll have to use visible light to cure the resin. Then I started thinking about how tricky it’ll be to keep that resin from curing by accident. Will I need a dark room? A little tent? How will the printer be able to cure one layer without ambient light from the screen curing other layers?
if it was curing with visible light, bottles would be brown like oxygen peroxyde and other photosensitive stuff
A much simpler explanation is that there is no working prototype and all the pictures are just fakes – Photoshop and inert design mockups. Slick marketing and nothing else. The device will need a battery for powering the Z axis motor. Have you noticed any battery port or charging connector anywhere? Don’t tell me it has a wireless charger – if it did, then they would certainly mention that somewhere! Also the box has no visible user interface – at the very least it needs to be paired to the phone somehow!
Another enormous red flag is the $80k they were originally asking for. Unless they are not paying any salaries and/or have external funding, there is no way one can bring this type of product to market with that budget. Just the mold tooling takes several thousands – every iteration. The same for the mandatory FCC/CE certifications. And if they have external funding and using Kickstarter as only a marketing vehicle – why isn’t there any footage of a real prototype? Not that obviously faked crap?
Printers like this already work, look at
this is just minimized copy of their design.
“Available in June 2016”. Show me a video of something being printed. A real video.
The white car shown half way in their movie has some artifacts that I could explain from FDM printing. But it’s only shown shortly and not from a lot of angles. So I could be wrong.
Footage here:
Thank you piecutter. This answers the “can it really print” question, as that video is convincing. The build plate looks like a piece of perf board, which is what I would expect to see in a prototype. Why OlO isn’t showcasing a video, I can’t imagine. However, I still have serious concerns about resolution since there is no optical system to focus the image on the object being printed. As someone else above pointed out, the light spreads out very quickly above an LCD; even the 1 mm spacing between the panel and the front surface of the glass will degrade the resolution greatly. I’d like to see a print that has some fine detail on it — unless this example is about as fine as it can do, which wouldn’t surprise me.
That’s an excellent point. That starting 80k fund is NOWHERE near what it costs to bring something like this to market, and another data point that at best this is incompetent and at worst a scam.
What the hell is oxygen peroxyde?
I guess that would be O2, but I’ve never seen it in brown bottles.
I have several brown bottles full of oxygen peroxyde. I keep it with my nitrogen nitride for convenience.
I keep my Iodine Iodide in brown bottles.
This. These type of resins are well studied and are easily cured with hundreds of watts of UV in a fairly short time period. Cell phone screens are not UV, they are polarized and output no UV spectrum if they are LED based.
The average output from a cell phone screen being enough to cure UV resin feels rather optimistic. Setting aside the concept that you could somehow selectively inhibit inks using a selectively oxygen inhibiting layer, there just isn’t much *energy* available even with a fully white screen. If cell phones gave off plenty of waste light, they would waste energy and have a shorter battery life.
Plus, you *can* use photoinitiators that are closer to the visible light spectrum but users need to be able to handle these resins, pour it in, expose it to 50 – 300 lumens of indoor light at minimum without it curing, etc. The bottles are not even in opaque containers!
Plus, does it need any post curing? How is that handled?
Several parts of this are extremely suspect. It’s *possible* but I am very skeptical of it being done with a cellphone display as a means of curing photopolymers.
Plus, the phone is going to never cease smelling like uncured photopolymer inks.
Color me extremely skeptical until more technical details arise. Also, the price tag is extremely optimistic. Yes, it has one axis but that’s still an extremely aggressive price point.
I have some really sensitive blue cured resin that I work with, and dental resins (composites) are blue cured, so it is conceivable that the blue wavelengths are being used from the white LED back lit LCD screen. White LED’s are just blue LED’s with a Ce:YAG phosphor over them, so there is a lot of blue available.
Most resins really only need blue light to cure, though the shorter wavelength you get the quicker the cure, usually. White light from a phone is ~1/3rd blue so it will cure.
if they spent half as much time, money and energy on the r&d of the proposed product as they do on their video production and viral marketing campaigns perhaps they could produce a better product sooner?
But then nobody knows about it and sales are much poorer. Seems kind of backwards, isn’t it?
Think about the distance between the LCD panel and the front glass. Even if the resin sat straight on the touchscreen, there would be too much difference, and the light would spread out before it hits the resin.
You are correct – this is the factor that tells me this is almost certainly vaporware/fraudware. It would need a lens that focuses the image on the plane where the resin is being cured. Otherwise the resolution would be really, really, REALLY low. Take a piece of wax paper or tracing paper and place it on your smartphone screen. That blurry mess is what the resin would be seeing.
I am guessing there is some sort of fresnel or microlens array to focus the image on the plane.
Blue LEDs emit UV, and WHITE leds are just blue LEDs with a phosphor (like in fluorescent lamps) coating. Also, my Note 4 has an OLED screen, which probably also emits UV. Not sure how much backlight UV gets blocked by the LCD panel though. To test fir UV, just expose glow-in-the-dark stuff to its white (or blue) light in a dark room, then tuen off the screen and check for after-glow.
Oops, actually blue LEDs do not emit UV, but if their photon frequency is high enough to charge ZnS phosphors, perhaps it is enough for this polymer. Not enough coffee…
LED lit LCD screens don’t emit UV, nor do OLEDs. Old CRTs used to emit low levels of UV, as did fluorescent lit LCDs (which still exist, but not in modern smartphones).Your mention of OLEDs has sparked a new question for me though.
On LCD screens, black pixels still emit some light. On OLED screens they don’t. So perhaps it’s possible the resin is tuned to a specific wavelength of light (light bright blue).
How do you tune the resin but insist the user can use basically any cell phone that fits?
You use blue curable resin.
Which would cure with normal “blue” room lighting. The watts per cubic centimeter of a cell phone display is extremely small compared to your average UV resin cure profile in a normal off the shelf printer. Further, those already use 1 to maybe 5% photoinitiator loading as it is. Setting aside oxygen inhibition issues with some resins, I still have a hard time pointing to “blue curing resins” being the solution that works how they describe it does.
I agree. The amount of light required makes it unlikely this technique would be useful.
For the ambient light problem, you’d keep it in black bottles, and have the developing tank kept in the dark. Not hard to keep room light out.
That said, it’s still almost certainly bollocks. Give me good odds and I’d bet my arm on it.
At least on their site they have something that looks plausibly like the device in action, though it does seem like it will be slow (30s/layer) since it looks like they want their polymer to tolerate brief exposure to room lighting. Unlike a lot of the more scammy/naive 3d printer kickstarters, they seem to be answering hard questions about the abilities of their printer.
Interesting idea, though most of their magic is in the photopolymer they are using.
ALL the magic is in their videos.
Who here wants to give up their phone for 4-5 hours while the print happens.
The cure time is much slower, as the resins are not intended to expose with visible light. So the print time is much longer.
Or risk burning an incoming call notification into a layer of your 3D print if you forget airplane mode? Anyway, it should be possible to pause printing in event of an incoming call, then replace your phone into the printer and resume later, if software permits.
And good luck with the alignment. That would cause enormous artifacts unless the resolution of the gizmo is so poor anyway that half a millimeter offset here or there doesn’t matter …
If this is NOT a 4/1 joke, I would expect people could use a SPARE phone for their printer, not their daily use one.
If this was real, that would not be an issue. At this price, most people would probably buy another smartphone to dedicate to this. IF this was real.
Watch this…
It is an objective review of the OLO from a 3d printer guy on YouTube. Makes you think about it.
Also some info in a video from an aussie channel called Maker’s Muse. He and 3d printer guy often cooperate i think too. Maker’s Muse got an email from the OLO people answering some of his questions and he made a follow up vid. Still not 100% sold but he said the fact they were responding was a positive.
All this guy is “reviewing” is the Kickstarter campaign. For him to review the product, it would first have to exist.
Looks like another of HaD’s April Fool’s Day gags.
Nope. This has been making the rounds for a week or two now.
Maybe they’re featuring it now because it might as well be. :)
Jonathan Buford anywhere near?
Oh please don’t mention that name. I was one of the few ‘lucky’ ones that actually GOT their Makibox and the hot end burned out within a couple of prints, and the construction was so wonky that it’ll never work properly.
By the way I have a Printrbot Play now and I got it in a week (unlike 2 years like the makibox) and it actually DOES deliver on its promises.
To be fair, the original Printrbot kickstarter units were pretty bad too, made out of laser cut wood, printed parts, used belts and rods not meant for linear motion, etc. The new ones from the company really can’t be compared to their original kickstarter. Kickstarting hardware of any kind is really risky, especially when they ask for so little and are an unknown company.
“Resin chemistry is tailored by manufacturers to meet specific customer needs. Both visible light and ultraviolet light have been used as curing mechanisms for this technology. Ultraviolet light presents some potential hazards and workers using ultraviolet curing resins generally wear protective equipment. … The new light curing unit (LCU) is based on blue light-emitting diodes (LED). The main potential benefits of LED LCU technology are: long lifetime of LED LCU (several thousand hours), no filters or cooling fan required, virtually no decrease of light output over lifetime with resulting consistent and high quality of material curing. Simple depth of cure experiments of dental composites cured with LED technology show promising results. … Recently, light-activated resins have found a place in floor refinishing applications, offering instant return to service not available with any other chemistry due to the need to cure at ambient temperatures. Because of application constraints, these coatings are exclusively UV cured with portable equipment containing high intensity discharge lamps. Such UV coatings are now commercially available for a variety of substrates, such as wood, vinyl composition tile and concrete, replacing traditional polyurethanes for wood refinishing and low durability acrylics for VCT. Also used in 3D SLA Printers.”
April fools jokes aside, I wonder if the light-activated floor finishing resin could be used for 3D printer, with a suitable 3D printer. It should keep materials costs down, I think.
And yes, there are resins that cure with blue light.
Light-activated floor finishing resin could most likely be used for some types of 3D printing, depending on the technology and how well the expected spectra aligned with the curing source and if whatever was added as filler doesn’t prove problematic and if cure inhibition wasn’t an issue. Probably a few other potential minor items as well?
If it uses the visible light from your phone, shouldn’t those translucent bottles be rock hard and ruined?
Deep in the kickstarter they mention using black (opaque) bottles out of necessity. Seems a bit misleading – handling resin that goes rock hard when exposed to sunlight is tricky!
For those who doubt this is possible, do some research. The quality of the print should be sufficient (at least under the 100 micron level for X/Y). “Daylight” resins are made by a few companies around the world, and though the layer cure time is way higher than a DLP SLA printer, it will absolutely work.
yes, one examle is they already sell printer like this using stock lcd panel and daylight curable resin, check their forum for people experiences
Our local 3D printer experts looked at it, and said “plausible”. The caveats: 1) It’ll likely be slow. The light output of the phone isn’t anywhere near a dedicated laser that most resins are designed for. 2) Expect to replace the tank and the print platform on a regular basis. The KS campaign says nothing about these being consumable pieces, but they are. They apparently degrade significantly with each print. The KS campaign says nothing about their replacement cost.
I read somewhere that the cure time is roughly 28 seconds per layer, which makes sense since you’ll still have light being emitted through black pixels on the screen. The cure has to be slow in order for it to work, which is not a requirement in DLP SLA due to the way it operates.
I did not know about the casing being consumable, though. That will add to the cost.
As someone mentioned, Exceptionally slick videos. Not one thing more. I saw their presentation at the NY Maker Faire in 2015. The showman asked for a phone from one of the 15 or so people standing at the booth. He placed it in one of the empty, slick OLO boxes. Closes up the box, and leans to his side to grab something from a box next to the table. He then opened the magical OLO box, and displayed the piece he just grabbed from the side of the table. “VOILA!” WHAT!? Are you kidding me? Am I the only one who felt like they were on candid camera? What the …? I had my kids with me, so I couldn’t properly express my feelings to the presenter. The second thing I couldn’t believe, is that nobody else laid into him. When I got home and web-searched OLO, it became clear that this is a dream, Unless you hand them your money, in which case it’s a nightmare. They claim they got a ribbon from MAKE mag. I emailed MAKE, but never got a response. I was looking for someone who actually saw this vaporware print something. Even confirmation that they actually did present the ribbon as OLO stated. So is the ribbon a lie? It’s also interesting how many printer and tech sites spewed out the same garbage they either stole from one another, or just posted whatever OLO claim on their website. Not one did I find that actually reviewed a working machine. Aren’t they supposed to weed out some of the scum? Sorry, for the length of this post, but I’m pissed. This actually is the abbreviated and family friendly version .. Slick, very slick, nothing more.
I think there is an extremely good chance kickstarter will cancel it like they did the Skarp.
This product only shows signs of being a scam, some of which you point out. Not only is the technology highly unlikely to be usable in any sort of consumer sense, a primary warning sign, but the comments on kickstarter are basically blanketed with people asking basic questions and lamenting the lack of creator feedback.
It appears to me they have a actual print and are calling it ‘an egg’, which it is almost certain it is supposed to be the sphere 3D model they have all over their marketing RENDERINGS. Backers have been asking to see the 3D CAD of the ‘egg’ and getting no response.
Scam. Scamarino, kidarinos. Really though – I kinda wish I was a scam artist type, my career is product development and 3D renderings, I could easily make a winning scam campaign. Sadly I am more of the spend time stopping scams type.
“I could easily make a winning scampaign.”
Fixed it for ya. :)
For those that bought into the Kickstarter campaign:
For $49 only I have a pdf file for download. Print it on your inkjet. Cut along the lines and fold at the crease marks. Glue the tabs as marked. Place on your smartphone. Fill with water to mark. Do not over-fill. If print does not start automatically, check the OLO tech support website. It’s based on the same technology.
It is irresponsible for hack a day to be promoting this in any credulous mode.
Seriously, this is at least as obviously bunk as Skarp, and hack a day was timidly promoting Skarp as well..
I think it’s funny that everyone is debating the viability, cost, consumables, technology used, etc. etc. etc.
The truth is, it’s like discussing the fabric, color, and texture of the garments of Emperor’s New Clothes tale. Except, in this case there isn’t even an Emperor. For those not getting the analogy: THERE IS NO PRINTER.
I DO want to thank Hackaday for showing us this obvious fake. Why? Beause it’s not that far off the mark. This is truly something that should be easier to DIY than FDM printers. You’ll want to use a really high-resolution LCD, such as an iPad with the Retina display, but add an imaging lens and a glass-bottomed tank on a Z-axis platform, and you could make one of these that could actually work. There is still some concern about the amount of light needed to cure even the “daylight” cure resins, which is why people have been playing with DLP projectors,
So if you want one of these, don’t waste your money on the OlO Kickstarter, but make one!
I am skeptical this idea can work in any practical sense using a consumer device as the LCD\light source.. They need a brighter backlight to have any hope – and LCDs have lots of bleed, so they are back to OLED or DLP….
It just isnt happening. I am sorry.
Agree there is a lot of DIY potential in resin machines though, with materials developing rapidly.
This particular kickstarter ticks off every scam-alert box.. Including the simple reasons their entire concept is likely to be flawed:
1) LCDs in phones have variable depth of glass\touchscreen. Even with the thinnest cover glass, this idea is still super suspicious – very unlikely to work.
2) LCDs in phones are highly variable in other ways as well – brightness, coatings, pixel density, and so on – simply noting ‘results depend on device’ is simply misleading in that it implies any device will work, when it is in fact likely this idea will not work with the majority of phones, even if it does work with 1 or 2..
Even with the perfect phone and so on, there is other problems with this product idea.
I am also glad Hack a day brought this to our attention, because I enjoy being a ‘skeptic on the internet’. I spend too many days trying to make peoples fanciful BS work as a product to pretend ‘ideas’ are infallible.
That got me at first as well. Even assuming as little as 1mm of glass between the actual light-emission layer and the resin layer, and a +/- 30 degree viewing angle, light from a point source would spread out to over 1.2mm by the time it reached the surface! Assuming there’s no imaging optics in between, which there certainly doesn’t look to be.
This implies I am wrong in a way, but still this machine in the link is far more likely to be workable than the Olo.
Olo also has all the other issues.
would it be that hard to hack a proof of concept for this? it sounds like we know (or have a good idea) of what kinda of resin they use.
just to see if they are completely full of crap about the phone as a curing light and so forth…
then again if it worked, why wouldnt they make a video with a clear case in a dark room…
Yes, you are totally correct. You would think, that if they can sell the printer for $99, they could make it for say, $33 ( I know, I know, they can’t, but just for argument’s sake.) Send 10 units to various independant reviewers (youtube, make, HAD, 3ders … ) This would alleviate much suspicion. A great investment for $330. I promise, this will never happen. Con-job.
I had an idea for a resin printer – I peeled apart an LCD monitor so I had only the LCD with no filters. It seemed transparent, and I could selectively make any part opaque. The idea was to have a tank with this as the bottom, and use UV from below. You would expose a sacrificial attachment to the device that incrementally raises and then proceed to make your item by lifting and exposing at whatever resolution was necessary or possible.
However, the damn LCD screen blocked the UV and the resin never hardened. Left it on overnight even. Maybe other resin, or some other LCD, or a better UV source was needed ( I used a water purifier bulb). But it was a FAIL. The only expense was the resin, and the LCD that I destroyed.
Anybody see a way to revive this idea?
Virtually all glass and plastic blocks or attenuates UV significantly, especially at the wavelength a purifier works, I believe around 254nm. You dont need anything nearly that short of a wavelength, 400nm is fine which is blue/purple.
Do a little Google Fu. Anybody who seriously looked at this project should have also found this: Sooo…. you don’t need UV. Also found instructional videos on print setup, removing prints from bed and post curing.
Also found this for a bit more info on OLO:
As for my opinion, I’m not seeing any spooky magic. All pretty much solid tech from what I can see. I don’t have any any inflated expectations about what kind of print quality I’m going to get for my $99, but I can see a couple of niche applications where my FDM printer would be at a disadvantage. Granted, at 28 seconds a layer with 4 seconds between for this size print area, yeah, good thing to have that spare phone.
Regarding interview: This is the problem. No in-depth reporting. Did she see the printer operate? I doubt it. My favorite line is “We had big offers from big international players which we refused so we can control the price.”
Still nothing but talk. Yeah, they talk like they know what they’re doing, but all we see are pictures of a hollow rectangular tube and a cover that fits on this. Not so much as a peek into that cover. No trace of optics in the tube. This is so fake, I can hardly believe anybody’s getting excited. Not even any pictures of a finished print being removed from the device. Yeah, there’s one moment in their video where they’re peeling a flexible print off of something in the rectangular tube, which we can’t see. Unbelievable fakery.
No pictures of their development prototypes, no demonstration of the user interface, nothing. Snake oil.
These Olo people are such total and complete carnival barking fakes, they were actually taking cellphones from people at maker faire NY, putting them in a non functional prototype, then handing them an object to ‘showthem what it will be like once Olo works’.
This of course is as absurd as it is pathetic.
The most pathetic thing: they got the editors ribbon on vaporware and a snake oil show..
Fool +1
these lens arrays veryone is imagining do not exist, and likely cannot xiat.
imagine what that actually calls for: a cuatom lens array per lcd display used. lcds have wide variance in pixel pitch.
The lens arrays used for Shack-Hartman wavefront sensors would work. But as Noirwhal said, the lens pitch would need to match the particular LCD.
Won’t work. Not enough power in a smartphone screen. Homemade SLA printers uses DLP projectors with a strong light that emits a ton of UV (when you peel off the UV filter on the lightbulb) or UV lasers. I found once a site that was selling resin sensitive to normal light but you still needed a lot of light (a pocket-size projector won’t work).
So it’s wether a scam or a team that have launched a kickstarter campaign without any research prior to that. In this case, they will soon realize that it’s not possible (at least, not for 99$)
Well it’s good to see I’m not the only one who suspects this as a scam. At the same time I’m glad that someone was able to verify that they were even at Maker Faire because I looked at last year’s Maker Faire on their website and was not able to find OLO as one of the winners. I won’t lie I’m still critical if this is for real or just a scam for money.
You are correct, they WEREN’T on the winners list after last years Maker Faire. I emailed the Faire about this, but got no reply. My question is first, did they actually get the ribbon award? And second, did the organizers actually see a printer print, or did they award based on the hype? The Kickstarter page displays the logos of some fifty tech and 3D printer websites. They all reported OLO as the next greatest thing in printing. OLO displays them as if they were endorsements of their product. I hope these sites will rise above the rest, and will care about their own credibility. Reveal this fraud. Those that don’t are are tacitly aiding scammers like this by being their advertisers. How about HAD follow the spirit of their skull-and-crossbones logo lead the way …
That’s interesting – their “iOS app” is something in a browser showing fake iOS screen elements. Screenshot from of of the videos on youtube: – in fact, that site is still online and definitely a pure mockup.
What an amazing crowd… So caught up in the technical “details” that you didn’t even notice the date of this post?
Yes it was April Fool’s Day. The OLO Kickstarter was started 18 days ago, and has been in the works for at least a year. So, what’s the connection?
Maybe HaD editors hate their readers as much as they imply sometimes – and they want to harm us by promoting this obvious scam to us?
While I dont think most HaD writers are incompetent, promoting these scams while saying “we dont see why it cannot work” is totally incompetent and irresponsible.
Thanks for turning this post into another advertisement for OLO. I hope you buy one for every member of your family for Christmas.
All the phone is providing is an LCD / OLED screen, and not an optimal one. You can buy LCDs without phones attached, and they’re not expensive. Why bother using a phone? Especially with the many interruptions to the display that are likely to happen.
Why not just get a few UV LEDs, or a UV tube, and a plain LCD panel? You’d have the full resolution, 3x the pixels, if you can get one without the RGB filters on. They must be available in medium quantities.
Resin printers have an advantage, in being mechanically much simpler, so there could be potential in this. But not using a phone as the light source.
Because the polarizing filters, liquid crystal composition, and ITO coatings in / on LCD panels do not work well (or at all) at UV wavelengths. Not to mention you still need a driver for the LCD.
ITO transmission is poor at UV wavelengths, and even the glass used needs to be (at least) UV grade fused silica.
Liquid crystal compositions designed for visible wavelengths have horrible transmission below 400nm.
Blue curable resins are available, having been used in dentistry for at least 15 years, and a color LCD would work at those wavelengths.
I think the point here is that it’s for people who aren’t technically inclined enough to hack up a printer on their own. And that it’s very economically priced because it’s nothing more than a Z axis and some software, and most people have the rest of the device tucked in their hip pocket..
There was no argument. I was commenting on Greenaum’s idea.
Sorry, not at you in particular. Guess I’m just tired of reading the same irrelevant “proof that it’s all a scam” over and over again.
What the heck? I couldn’t get my post in at all, and now it’s triple posted? How do you un-post?
That explains it. Still kind of a waste of a cellphone though. Just for a few quid’s worth of LCD screen..
Sorry, I don’t know how to unpost something. Perhaps contact the moderator – James Hobson.
I’m calling BS on this one..
Controversy is the journalists best friend. I can hardly wait for the “I told you so’s” and the lack of responses and which side of the fence they fall.
Sorry, I don’t know how to unpost something. Perhaps contact the moderator – James Hobson.
Well, this is the second time in a row I’ve called “BS”, and then had to eat my words (the previous time being the laser rust remover). And in this case I’m happy to be wrong, since it really WOULD be nice to get decent 3D prints with such a simple mechanism. But my wallet isn’t quite jumping out of my pocket yet, since I haven’t seen a demonstration of decent X-Y resolution. Mind you, I’m not talking about how fine a feature it can print, but how close together it can print fine features. With the lack of optical system for focusing the image, I can’t see how they can do a decent job, but I’d sure love to be wrong just one more time!
But will it work with and old Nokia???
Needs MOAR LAZERS in order to work.
Put this “invention” next to the fake “laser razer” featured a few months ago.
I wonder why they chose a Golden Egg as the subject matter for the fake demo print … (sarcasm)
Just to throw in something completely out of left field, I wonder if a system like this could be used to print a single layer of resin as a photoresist on a copper-clad board. I’m not a fan of any of the other DIY methods I’ve seen or used for applying etchant resist to PC boards. I guess the main question would be whether the polymer would stick well to copper, how small the geometry (line width, line spacing) could be printed, and how hard it would be to remove the polymer after etching. On one of the videos I’ve seen about the Photocentric printer (), it looks like it takes some real effort to break the support struts off of the build plate.
And if that’s viable, then it should be a no-brainer to do solder mask with it as well, though maybe not in the traditional colors.
It could probably simply expose a pre-sensitized board. With proper alignment scheme, it might work pretty well for 2 sided boards. Not a bad idea at all. Focus and cover glass would still be an issue, of course.
Having worked with a (real , $$$ ) kickstarted machine … i am not buying it (the concept, believing it) at all.
So, after a bunch of googling and reading it seems ‘LCD Contact’ exposure of new resins is totally a thing. It looks very promising!
These people have the same general idea but their approach looks very good! There is a bunch of machines working this way, though many seem to be crowd funding things without much consumer reviews.
I still think Olo is a scam.
Yep, I saw this too. Looks really excellent for a semi-pro level resin printer. I actually asked them why don’t need any focusing optic (that is the only real question I have with the OLO feasibility at this point), so we will see what they say.
Olo cannot use optics. Imagine what that will require… It isnt possible to just ‘put optics’ that ‘match’ ‘any’ cellphone screen.
No, I asked the Slash guys what their solution was. They replied it was not necessary given the distance between their panel and the resin.
I also asked Olo about it also and they said:
“this is part of our patent: the light runs just 150 microns before meeting the resin through a ‘special’ transparent layer.
In other words too less to diverge”
My follow up question was, what about the 750-1000 microns of digitizer and glass thickness. We’ll see what they say.
So … you’re using one Kickstarter project to validate another?
But seriously, this is a whole different thing. There are SLA printers that use built-in LCD screens (like the SLASH), and then there’s OlO. Here’s the difference: on a printer with a built-in screen, the vat film can be in contact with the front of the LCD’s very thin polarizer layer, which means that each pixel of the LCD illuminates an area of the polymer layer not much larger than the pixel itself. But if you use a cell phone for producing the image, you DON’T have access to the surface of the LCD. There’s a piece of glass over the LCD panel that protects the LCD itself from scratches and impacts. This layer of glass forms an optical gap between the LCD and the vat film, and since a typical cell phone LCD has at least a 120 degree viewing angle, the light from each pixel IMMEDIATELY spreads out, even before it passes through the glass.
Many people commenting here are concentrating on the wrong “impossible” part. It’s clearly not impossible to buy polymers that can cure with blue light; several successful printers have been doing this for years using DLP projectors and blue lasers. The impossible part is getting a decent resolution image projected onto the vat film (and thus the photopolymer) through the faceplate glass of a cell phone. The one video I’ve seen of something actually being printed this way is of a distinctly LOW-resolution object – an egg shape with big holes in it. No little holes, no fine features at all. I’m pretty sure that OlO will work, I just don’t believe that it will work well enough to print the sub-millimeter features people now expect from 3D prints.
I have now posted 2 links to ‘LCD contact’ printers. This one looks much more promising, like I said.
Actually, you really do NOT want the resin in direct contact with the display. As with most 3D printers, the finished print can require quite a bit of force to remove. The actual print surface is a thin, consumable layer that’s meant to be sacrificed from time to time. Just hopefully not after EVERY print, in this case.
While it’s true that the distance from the image element means that you could not have a one to one correspondence with print resolution, even with a monolithic plate of FFO replacing the display glass(due to the numerical aperture of the individual fibres, although it could get you very close!), think about this, my phone has a 557 ppi display. This means that each element is in the neighborhood of .004 inch. Adding the thickness of the glass, you still need a divergence of almost 10x to leave submillimeter territory. Even if you have that, look at your phone and tilt it from side to side and you’ll notice the brightness drop off sharply towards the low angles. That’s also going to trim the effective exposure area above each element. Now, obviously everyone’s phone is not going to have that high a pixel density, so YMMV applies directly here.
I’m actually working with some micro displays right now that have image elements measuring in the single digit microns. I had to go through a very cringeworthy process of grinding the cover plates down to get a coherent image through an even more densely packed FFO element. You’d be amazed what a difference there is between .32mm and .29mm at this scale.
Hmmm…..a Z axis made from a CD drive and I could print resin in the micron range!
Even with a 1×2″ build area that would let you do some pretty impressive stuff.
Actually much smaller area, only about .6 x .9″. And I’m not too sure how small an accurate step an optics drive carriage from a CD could do. And it would be slow going unless I could find a way to increase the luminous output of the OLEDs or find a more sensitive resin. Then there is the question of how to remove the print from the bed without damaging it or the print. A fixed slide obsidian blade, maybe?
Arrrrgh!! Now my brain hurts and I’m losing focus on the original project! Damn you HAD!
First thing I did when reading the article was doing some 5 minute research. The thing doesn’t seem to be a vaporware as similar printer already exists (and OLO is using their resin as they mention in the kickstarter). I can imagine that iphone with retina display could do some high resolution prints. They are just trying to get the price down by reusing piece of hardware everyone has (smartphone), which is the most expensive part.
As I understand. The Liquid crystal 3D printer is just LCD monitor with armature to move the 3D print.
It IS vaporware, though similar printers exist.. Logic is easy, i thought.
Seriously! Not a single person in this thread calls april fools? Do
People did, but were quickly informed this device has been around for at least a few months.
Some digging shows this device has been around since October 2015 at the latest.
Try reading the posts first next time …
So, they exceeded 2 million yesterday. I’m hopeful that means their engineering and testing will greatly improve and we’ll see something that is at the very least usable.
Geez! … Delusional! Why would more money be a greater incentive, he he he ? I can already hear “So long suckers! … ” fade into the night (or at least Italy.) Don’t worry, they’ll be back within the next couple years for their next big score. It’s just too easy.
Thank you for all your warnings, Frankie. But big boys know how to take on a calculated risk when they want something. If they didn’t the buggy whip business would still be going strong.
You just stay down there in the bunker where it’s safe. We’ll handle it if things go bad.
Frankie is correct though. Sorry.
He can be correct in September, or not. As for the present, it’s all conjecture. I’ve placed my bet already, that’s how you make things happen. If I get burned, It’s a risk I was willing to take. I will have lost an insignificant cost in order for the world to be enlightened to a new scam artist. Is that cause to call me “Fool” or “delusional” when no substantial evidence of wrong doing has been revealed? Really, I’m doing you a favor. “But there are signs” you may say. So far I’ve only seen the signs of someone inexperienced in the nuances of setting up a Kickstarter campaign. And apparently over 14,000 other delusional fools feel similarly enough to wager as well.
I’ve not lost money on a Kickstarter yet. Perhaps if I had, then everything would look to me like a smoking gun as well. But probably not. It’s really not in my nature. And still, I wouldn’t be vehemently broadcasting my suspicions without something concrete to base it on.
Actually, Big Boy, falling into the OLO trap sound to me more like the actions of a naive teenage girl. A slick guy in a sports car pulls up, gives her a nod and a smile, and she’s more than happy to jump in. Whether big boys like you behave similarly, is certainly up to you and none of my business. Personally, 9 months from now, I hope you don’t wake up with a mutant baby OLO in your arms. Then again, is a mutant OLO better than none? Anyway, IF you do get one, I’m sure it will LOOK very good — Congratulations!
Some people are fine with the risk of losing $99. I can see the thrill in buying-into part of the cutting edge of the already cutting edge 3D printer spectacle. I blow money on dumb thrills all the time. To each his own.
For those who are on teh fence and do give a hoot:
I have spent way too much time researching OLO, Solido3D, their founders, etc. I kinda think that’s part of what hackers do. Find out what makes things work. To my eyes, I see nothing to convince me that either the US or Italian “companies” have any engineering/manufacturing substance to them. “Fonderie Digitali” and similar lingo and flash pervades every one of their pages. It’s seams clever at first, but is totally ambiguous and dumb. There is no independent review of the OLO, or any precursor. Generally, people that build cool stuff, have a track record of other cool stuff. Of all the famous companies they have supposedly worked with, how many of them were helped directly by the two founders’ or their companies, not by a network of companies they have worked with? And, what did they do for them? Was it anything close to a printer? Anything cutting edge or technical? Or, did they do the marketing / video production for them (my guess?) The feeling I get, is that most of what they ever did or claim, is based on incubator affiliations.
I guess I’m trying to find ANYTHING that appears genuine and not somehow a gimmick/pitch/BS? Anything? Anybody? Anybody worked with them in developing/producing anything? No videos of Filippo as a kid spinning a stepper motor with a BASIC stamp? Stupid transformer tricks? Nothing? Am I being suspicious? Oh, yeah! You bet! To get my money, you will be required to convince me, that you are who you claim to be, and will deliver what you are selling. And yes, I am a hater of boisterousness, flash, slick, and hype (I’m looking at you cheerleaders, malls, big car dealership’s and Las Vegas.) I was going to take out cheerleaders, but instead, I’ll qualify, by saying I hate them only when doing their dumb cheers. Truly interesting sports don’t need them. Sorry, off topic.
Being hackers, we are all in love with the dream OLO puts forth … but wise Big Boys know when it’s time to snap out of it. Piecutter is right, I am a fraud. I have no proof, special technical insight, or divine enlightenment. All I’m hoping, is that if you are on the fence about buying OLO, just WAIT!
If you need me, I’ll be in my bunker. I’ll be be up in two weeks, when my CO2 laser tube comes in. I figure, it only cost me $70, since I didn’t waste $99 on the OLO. Wise Big Boy fun.
Don’t you have anything better to do?
Actually, I’m waiting for my print to complete. It uses my 60″ LED TV. Only 2 weeks and 3 days till completion, so I’ll be here a while, if you want to chat. This is great though! Looking very promising…I wonder if I could make any money with this? I don’t want to make any big money by selling to StrataSys or AutoDesk or any venture capitalists, who are more than eager to invest in sexy technology. I’m thinking instead, I’ll help the maker community. Danny, how does this Kickstarter thing work?
A 2 Million Scam!
Imagine yourself to be a founder of this Kickstarter campaign.One day you wake up with this brilliant idea of a phone based 3d printer that everyone can carry around.You meet your friend or partner or whoever and start about creating a mechanical prototype for raising the bed.Then you create a really basic software to split STL files into layers and project them on the screen of consumer phones at a certain wavelength.You tweak the software till you can sync the moving bed with the screen images.Then.You pour photocurable resin from a BLACK bottle onto the resin container and lower the bed into the resin and start the mechanism.And pray.The gap between your phone screen and the glass and the refraction from the glass effs up your print.But you know this can be done.
Then you go and create a KickStarter video and show the resin stored in WHITE bottles.You also show prototypes printed from YOUR invention which look deceptively similar in color to the orange resin from other DLP printers.
You are asked if the phone can be charged while printing.You say YES first.Then you say doing this could expose more light into the printer so you say NO.But.3 DAYS LATER. :)
And then you notice that 20,000 people have backed your project, and you’re thinking, “I can’t even make ONE of these work right, how am I going to produce 20,000 working units in the next year?”
So you keep delaying delivery saying you would rather deliver a world-class high quality product than a sub-standard product and keep paying yourself a decent 6-figure salary to ‘survive’ in San Fran.But then you have backers visiting your office to check progress.So you move offices to Italy and say you will give an extra bottle of resin to all good backers who are patiently waiting.You keep putting updates on how you are this close to a breakthrough while curing the resin with a special LCD screen.Then one day you check your bank balance and find that all those expenses and overheads can’t breakeven with the cost of manufacture.
BrightBlueJim & Vishal:
I think we agree on the overall outcome, but I believe you both are giving them too much credit. They didn’t accidentally get in over their head. I bet you they already have a 6 month calendar marked up with dates, for release of already-made “progress reports”, encouraging videos, and statements ready for release to backers. This has been, and will be, a carefully planned circus. You’re right, the quantity of backers will give them an added excuse not to be able to deliver.
On another note: I would like to know what their supposed patent covers. Utility or design? There’s a big difference.
The promised updates and answers to backer questions never came.And Frankie you are right.If the campaign is make-believe they would have carefully thought up future updates and timelines with delays.KS will never raise an iota of doubt since all they need is a visible attempt to fulfill backer pledges.KS never goes and checks inventories,workshops and prototypes.
So now 16,180 people have been duped of 108$ or more,SMH
ONO ! This Philipe guy is still peddling the non working prototype at Maker Faires.Here is him at the NY Maker Faire showing off the same vaporware stuff they had before the KS campaign. And its been 7 months almost since the KS. campaign ended.
About time KS backers went from ONO to OMG !
Interesting FAQ answers some questions:
So it’s a .15mm build film that’s good for 3 prints. Good for them, another consumable for continued business. And, interestingly, any screen protector under .2mm won’t affect the print.
Oddly, they’ve also chosen audio as the data link. but I suppose that keeps the cost down and no reason it shouldn’t work. Guess I won’t me jamming out to anything in the 18 to 20 khz range while I’m printing though!
Also in the FAQ:
“OLO 3D printer will let you know if its batteries need to be replaced before you start printing.”
How is it going to do that, when it uses non-rechargeable alkaline batteries? How does the printer know what the initial capacity of the cells is?
“What do the prints look like?”
In the pictures provided, while the layers are clearly discernible, all of the prints show a distinct lack of sharp-edged features. This is consistent with the fact that light from an LCD separated from the print by the phone’s faceplate glass can only deliver a blurred image.
Printing rate is about two hours per inch of height.
“OLO’s app is cloud-based, does it have its own servers?
No. OLO 3D is using Amazon and Google servers.”
Sigh. No reason in the world this should be cloud-based, but that pretty much guarantees that unless somebody hacks it, this will eventually become useless. I mean, even MORE useless.
“How does a file get from the PC to OLO Smartphone 3D printer?
PC > 3D file > stl file > cloud > slice > svg > olo > smartphone > OLO > final print.”
A simple forty-nine-step process, overall, from the looks of it.
For this price, I don’the care. I’ll hack what I don’t like. It’s so sh*t simple, there is really nothing to it. A Z axis with a controller board and a mic. Strip out the board, put in an Arduino (just to give it real HAD cred!) And run it via BT, WiFi, USB or whatever you like! With whatever software you like! Take the Z axis out and put it on a tablet, monitor, big screen TV or whatever! Extend the height!
Screw it, just build your own from scratch to your own specs. Then you get to be the expert and tell everyone what is or isn’t real. Doesn’t really matter. The Internet will always argue with God when he posts something too.
You seem to have fundamental misunderstandings about the product you discussing.
Why not make your own if you have these skills?
Personally reading about this product has inspired me to try something a bit funky and get a tiny low cost pocket projector and some of this daylight resin.
What you describe is just…. No. Also, there is no god, so of course the internet will argue with that idea!
Not much to understand. Your phone sends an audio signal carrying the Z axis instructions while simultaneously displaying the current slice of the model, the printer takes the audio data and changes the Z height accordingly. Repeat for a couple hours and you have an object. Am I missing something here? Do tell.
Yeah, I probably would have built one last week, but I’m a little tied up building a heated bed for my filament printer, building a microdisplay immersive headset, converting my fink trusses to attic trusses and installing an HVAC system. Then there’s the pile of new components that should’ve been a new PC a few months ago, the pile of vintage motorcycle parts that need to go back together, drywalling the pantry, and of course, working 9 to 5 all week. For $99 I think I’ll wait for them to do it right now.
But if I manage to get caught up before then……
Here’s what you’re missing: it’s a fundamentally flawed optical design, regardless of the price. Fixing that will cost more than the $99 that just gets you a Z stage and polymer reservoir.
Hey piecutter:
RE: “Thank you for all your warnings, Frankie. But big boys know how to take on a calculated risk when they want something.”
Ready to print a “I’m such a SUCKER!” plaque yet? Oh, yeah that’s right .. never mind … maybe it’s still in the mail, Big Boy. “Calculated Risk” or wishful delusion. You “wanted” it to be true. No calculation performed, Ciao! Italy loves you!
Frankies favorite italian boy showing off his toy at NY Maker faire
Hey Vishal,
OMG! That ass is still around?! So. with all those beautiful boxes there, he must have had tons of prints going on, right? There must have been at least one printing, with a window, so we can see what’s going on inside. No?… hmmm. I guess the ambient light would mess with the print. That must be the reason.
I’m actually pissed at myself for not seeking out this loser at Maker Faire! I wish I would have thought of it. I was there, but I never got around to seeing his booth, which would have jogged my memory. Next year I’ll have to go for two days. One just isn’t enough to see everything. I’m sure Bozo will be there again, too.
I like to print and wear unique T-shirts to the Faire. Had I remembered about the Ono, I would have printed something like “WHERE’S MY OLO PRINTER?” and strutted around his booth for a while. Or, as long as it takes for this con to actually prove to me with a print-while-I-wait, that I was wrong all along.
As disappointing as it is, to know that a dirt bag like this is allowed to operate, my real anger is toward:
1) Bloggers like James Hobson, who act like they are knowledgeable, cutting edge reporters. Seems to me, when you were suckered into being some con-guys bitch, the least you can do is compensate, by reporting on the problems with kickstarter. I’m not here to single out JH or HAD. It’s a sad sign of the times.
2) Maker Faire — another more-than-willing pawn of this sleaze.
3) All those who back this garbage, despite obvious indications of fraud. STOP making excuses for them ( “The whole thing could work, because, there is such and such… , and it’s possible that if …, “.) If they want your money, have THEM prove their abilities to YOU. Also, when you get ripped off, take these guys to task. You would be surprised, how long after a transaction, you can still cancel a payment. Confront this fraud wherever he shows up. With all the people who got screwed, you would think OLO’s booth would have been unable to operate. It should have been swamped with irate backers wanting to know what’s going on! Get some BACKBONE! STOP BEING PANSIES! | https://hackaday.com/2016/04/01/a-99-smartphone-powered-3d-printer/ | CC-MAIN-2019-35 | refinedweb | 11,528 | 73.27 |
Microsoft Roslyn is an API that exposes the C# compiler as a service or one can say now the entire compiler is exposed in a form of a library that can be included in your project or application.
Microsoft Roslyn is an API that exposes the C# compiler as a service or one can say now the entire compiler is exposed in a form of a library that can be included in your project or application, earlier you needed to write code in C# and build that code, if it is successful then you get the compiled code in the form of an assembly, but now you can actually build or compile the code dynamically from within your .Net applications. You can now have Build process information or compile process information that was not available earlier. So now you can pass in your code as a string to the API and it will provide you with the code in Intermediate Language (IL) with syntactic and semantic information regarding your code. So the major advantage we get is one can do the Code Analysis using Roslyn.Roslyn has nothing to do with the CLR, Roslyn can do the same for you as any other compiler can do, that is it can compile your code and return it in Intermediate Language that can then be passed to the CLR (as we know the CLR doesn't understand any specific language like C# or VB, so the role of every language compiler (.Net Compliant Language) is to produce a code in IL that is very well understood by the CLR).With the introduction of Roslyn (Right now Roslyn is available a Community Technology Preview) now the compilers are no more the blackbox (that earlier takes in the code writhen in a managed language and outputs it as an assembly), now one can get the entire Syntax Tree of the code in the form of objects (API(s) are exposed to get the Syntax Tree).One of the major advantages that I see now is that you can produce code from a User Interface, in other words suppose your application is in production and now you need to write some code, earlier you need to do the code changes and build the code again but now you can create a User Interface in your application (the UI can have a textarea and a button) and you can actually write the code on the UI and get it compiled at runtime without doing the deployment again. But yes you need to make your application intelligent enough.Roslyn API(s) are available as NuGet Packages; you can do something anytime, so one can install it very easily by the Package Manager.Here is a sample code showing some of the features of the Roslyn C# compiler.First of all you need the Roslyn Libraries available as a NuGet Package that can be installed using the Package Manager in Visual Studio. For installing the Roslyn libraries, just open the Package Manager console and type in the following command:PM> Install-Package Roslyn.Compilers.CommonOnce the installation is successful, create a sample console application or a Web Application as needed and add the reference to the two libraries, that you got from the preceding installation. The two libraries are:Roslyn.CompilersRoslyn.Compilers.CSharpAnd you are ready to go.First we will see how to output the Syntax Tree or the code as the DLL. You can find the details of what the code does as inline comments within the code.
using System;
using System.IO;
using Roslyn.Compilers;
using Roslyn.Compilers.CSharp;
namespace SampleApplication
{
class Program
{
static void Main(string[] args)
{
//Syntax tree is the code you want to compile at runtime
var syntaxTree = SyntaxTree.ParseText(@"using System;
class TestClass
{
static void Main()
{
Console.WriteLine(""Testing Rolyn"");
Console.ReadLine();
}
}");
//Creates the copimlation, Here we are setting that compile it to a dll for the syntax tree defined above, adding references at runtime, here we are adding metadata
//reference of System library at runtime
var compilation = Compilation.Create("RoslynSampleApplication.dll",
references: new[]
new MetadataFileReference(typeof(object).Assembly.Location)
},
syntaxTrees: new[] { syntaxTree });
//Here we are getting the Diagnostic results for a particular syntax tree on copilation, so if there are any errors we will get a list of that errors which can be
//used to show it to user, These errors are just the same as we see in the Error list of Visual Studio.
var diagnostics = compilation.GetDiagnostics();
//Here i am prinitng the errors if any
foreach (var diagnostic in diagnostics)
{
//You can also get the line number here on which the error has occurred. Code goes something like this: diagnostic.Location.GetLineSpan(usePreprocessorDirectives: true).StartLinePosition.Line
Console.WriteLine("Error: {0}", diagnostic.Info.GetMessage());
}
//If we want to generate a DLL for the above syntax tree we can emit the compilation to a DLL by the following code.
EmitResult result;
using (var file = new FileStream("RoslynSampleApplication.dll", FileMode.Create))
result = compilation.Emit(file);
}
}
}The sample code I provided above does not have any errors, if you want to see some errors that are caught by the compilation diagnostic then you can make some invalid changes in the Syntax Tree and you will see the errors in the console window.The DLL created above can now be consumed in the application. So this is how you can create DLL(s) at runtime. Now let's see how to write a piece of code at runtime, compile it and produce the output:
//Syntax tree is the code you want to compile at runtime
public static string GetWelcomeMessage()
return ""Welcome! Abhishek Jain"";
options: new CompilationOptions(outputKind: OutputKind.DynamicallyLinkedLibrary),
//Here i am printng the errors if any
//var lineSpan = diagnostic.Location.GetLineSpan(usePreprocessorDirectives: true);
//var startLine = lineSpan.StartLinePosition.Line;
//Here the compiled code is emitted into memory stream which is used to create a assembly at runtime, and we are using this assembly at runtime only to invoke a
//method present in one of the class of this assembly.
Assembly assembly;
using (var stream = new MemoryStream())
EmitResult emitResult = compilation.Emit(stream);
assembly = Assembly.Load(stream.GetBuffer());
//Type of class is retrieved and for that type, method is retrieved from it using reflection, Method is invoked also by using reflection
Type testClass = assembly.GetType("TestClass");
MethodInfo methodInfo = testClass.GetMethod("GetWelcomeMessage");
string welcomeMessage = methodInfo.Invoke(null, null).ToString();
Console.WriteLine(welcomeMessage);
Console.ReadLine();So these are the very basic samples, I am also attaching the source code, if needed you can also try at your end.
View All | https://www.c-sharpcorner.com/UploadFile/25c78a/using-microsoft-roslyn/ | CC-MAIN-2020-24 | refinedweb | 1,093 | 50.36 |
Edit: following @Shnatsel’s comment, I updated my original post removing all references to C runtime linkage, and leaving only the main point about saving debugging information in separate files.
Rust programs are known to have larger binary sizes than C programs. This was, and in part still is, due to several reasons as explained in the FAQ.
One of the reasons reported in the FAQ, Jemalloc, has already been removed on nightly. Another reason, debug symbols, is actually avoided for the
msvc toolchain on Windows by saving debugging information in separate files (rather than in the executable itself as the
gnu toolchain does).
I made a brief assessment of binary sizes of basic “Hello world” programs in C, C++, and Rust, on Windows and Linux, by using the following compilers:
Windows:
- Build Tools for Visual Studio 2017 (
cl)
- MinGW-W64
gcc/
g++8.1.0
rustc1.32 nightly
Linux:
gcc/
g++6.3.0
rustc1.32 nightly.
Note: the results reported below for Rust are obtained with default mode compilation, but I verified no significant difference with release mode compilation.
C
#include <stdio.h> int main() { printf("hello, world!\n"); }
Windows:
cl: 113.2 kb
cl -Zi: two files, executable 494.0 kb and PDB file 4894.7 kb
gcc: 54.0 kb
gcc -g: 54.7 kb
Linux:
gcc: 8.6 kb
gcc -g: 11.1 kb
C++
#include <iostream> int main() { std::cout << "Hello world!" << std::endl; }
Windows:
cl: 221.2 kb
cl -Zi: two files, executable 1041.4 kb and PDB file 8368.1 kb
g++: 56.9 kb
g++ -g: 76.6 kb
Linux:
g++: 9.3 kb
g++ -g: 28.8 kb
Rust
fn main () { println!("Hello, world!"); }
Windows:
rustc: two files, executable 141.8 kb and PDB file 1232.9 kb
Linux:
rustc: single executable file 2401.9 kb
The size of the two binary files differs so much because the
gnu toolchain on Linux (but the same applies to the
gnu toolchain on Windows) saves the debugging information in the binary itself, while the
msvc toolchain saves the debugging information in a separate PDB file.
Actually, also the
gnu building tools allow to save debugging information in separate files, by using the following commands:
objcopy --only-keep-debug foo foo.dbg objcopy --strip-debug foo objcopy --add-gnu-debuglink=foo.dbg foo
Otherwise the following commands can be used, with same results:
objcopy --only-keep-debug foo foo.dbg strip -g foo objcopy --add-gnu-debuglink=foo.dbg foo
Applying those commands to the Rust program compiled with
gnu toolchain on Linux I get the following results (note: they do not seem to work with the Rust program compiled with
gnu toolchain on Windows, but maybe this is a limitation of the MinGW-W64 implementation, and anyway IMHO this fact is not that relevant):
Linux:
rustc: two files, executable 256.2 kb and dbg file 2201.9 kb
Proposal
To vastly reduce the binary size of Rust programs on Linux, I propose to have the
gnu toolchain save debugging information in separate files (like the
msvc toolchain already does) by using the
objcopy tool. | https://internals.rust-lang.org/t/proposal-have-the-gnu-toolchain-save-debugging-information-in-separate-files-like-the-msvc-toolchain/9033 | CC-MAIN-2019-04 | refinedweb | 522 | 67.04 |
On Thu, Dec 04, 2008 at 03:24:16AM +0000, John Levon wrote: > On Wed, Dec 03, 2008 at 09:37:57AM +0000, Daniel P. Berrange wrote: > > > > +def blkdev_size(path): > > > + if platform.system() == 'SunOS': > > > + return os.stat(path)[stat.ST_SIZE] > > > + else: > > > + dummy, msg = commands.getstatusoutput('fdisk -s %s' % path) > > > + # check > > > + if msg.isdigit() == False: > > > + lines = msg.splitlines() > > > + # retry eg. for the GPT disk > > > + msg = lines[len(lines)-1] > > > + return (int(msg) * 1024) > > > > > > ACK, to the general idea of adding a common routine. The original Linux > > impl was kind of crazy. We could get a single portable impl for all > > OS by using seek(), which is how libvirt does it in its storage code. > > Quite honestly, I wasn't entirely sure why you're using fdisk. But if > you don't need to, why use lseek() when os.stat() does the job? Because stat() returns 0 for the size of block devices on many UNIX including Linux. # perl -e 'use File::stat; my $f = stat("/dev/sda1"); printf "%d\n", $f->size' 0 # perl -e 'use POSIX; my $f = POSIX::open("/dev/sda1", O_RDONLY); printf "%d\n", (POSIX::lseek $f, 0, 2)' 106896384 :| | http://www.redhat.com/archives/et-mgmt-tools/2008-December/msg00068.html | CC-MAIN-2014-10 | refinedweb | 192 | 77.53 |
Understanding API Pagination
. What this looks like will depend on the API format, as there are multiple ways to indicate pagination.
Page numbers are the simplest ways. Often, the returned JSON will not even mention what page you are on. Your returned results will be dependent on what page you request. Usually follows a scheme like.
Cumulatively counting items, also called offset pagination is similar to page numbers, but you request the next page depending on how many items you have already seen. This requires you to keep track of the count. These often follow a scheme like.
On a similar vein, you can request after a timestamp offset. This might look like. These can be difficult, as timezones are always annoying.
Sometimes you request the next page depending on the ID of last item in the current page JSON. This is more comprehensive, as you do not need to know the current page number to request the next. These often follow a scheme like, where
zbx43ks is the ID of the last item on the previous page.
Since bash handles loops, you can paginate with
curl, but you will usually want these items in a program. As such, let’s look at two examples.
Example with Page Numbers — Github Jobs & Ruby
The GitHub jobs API is wonderfully simple, and I highly recommend it to those just starting out with JSON APIs. It is quite simple: for any page, there is a corresponding json page. Just add
.json to the end of the URL.
The API takes a query string
page. Each page will start where the previous one ended. Pretty simple. Note I think the pages start at 1, contrary to what the API says.
There is no way of knowing how many pages there are, but that is no problem. Since the JSON returned is just an array, we can check to see if the array is empty. Here is an example in Ruby to scrape all of the positions:
require 'net/http'
require 'json'
url = ""
page = 1
positions = []
loop do
page_url = url + "?page=" + page.to_s
puts "on page" + page.to_s
uri = URI.parse(URI.escape(page_url))
response = Net::HTTP.get_response(uri)
data = JSON.parse(response.body)
if data.empty?
break
end
positions += data
page += 1
end
Example with ID of Last Item — Reddit & Python
According to the Reddit API:
Listings do not use page numbers because their content changes so frequently.
Instead, pagination is dependent on the IDs of the elements of the current page.
You can access the JSON version of a Reddit page like above — appending
.json to the site url. For example, typing reddit.com/r/popular.json returns json that looks like this:
First there is the page’s
kind:
Listing, which just means a list of posts. If we want to grab all of the posts, we should look at
data.
The contents of
children is an array of posts. Each post has a lot of information, so I collapsed it for brevity. There are 25 elements in the
children array, so we can assume that
dist is the number of children.
Finally, there is the
after field. In case you are unfamiliar with Reddit IDs, this field is the ID of a post. In this case, it has the ID of the last post in the array. You can double check this yourself, by going to the endpoint and comparing the
after field with the final array element’s
data.name.
In my opinion, the Reddit API documentation is not great, but we can infer what this means for ourselves. If I try hitting the same endpoint, but inserting the query string (
reddit.com/r/popular.json?after=t3_k0eop4), I get a new array of posts. If I go to
reddit.com/r/popular without the json, I can go between the first and second page and compare the posts to the two json endpoints we just looked at. In this case, the one without query strings matches page 1, and the posts of page 2 match the json with the query string.
We can infer that the
after field can be passed as a URL query string to facilitate pagination. Here is a simple Python script to get the first 10 pages worth of posts:
import requests
url = ""
after = ''
for page in range(0, 10):
page_url = url
if after:
page_url += '?after=' + after
# Reddit shuts down Python requests unless they have a custom user agent
# See:
listing = requests.get(page_url, headers={'User-Agent': 'Pagination Example'}).json()
posts += listing['data']['children']
after = listing['data']['after'] | https://eking-30347.medium.com/understanding-api-pagination-eea509f358d1 | CC-MAIN-2021-04 | refinedweb | 763 | 75.3 |
icetWallTime -- timer function
#include <GL/ice-t.h>
Retrieves the current time, in seconds. The returned values of icetWallTime are only valid in relation to each other. That is, the time may or may not have anything to do with the current date or time. However, the difference of values between two calls to icetWallTime is the elapsed time in seconds between the two calls. Thus, icetWallTime is handy for determining the running time of various subprocesses. icetWallTime is used internally for determining the values for the state variables ICET_BUFFER_READ_TIME, ICET_BUFFER_WRITE_TIME, ICET_COMPARE_TIME, ICET_COMPOSITE_TIME, ICET_COMPRESS_TIME, ICET_RENDER_TIME, and ICET_TOTAL_DRAW_TIME.
The current time, in seconds.
None.
None known.
This man page should never be installed. It should just be used to help make other man pages.(3) | http://www.makelinux.net/man/3/I/icetWallTime | CC-MAIN-2016-40 | refinedweb | 124 | 59.3 |
If you need simple Role based access control without the long RBAC process then this article is just for you. Lets jump to the point.
On your user table make a column named 'roles'. Create the model accordingly. It will be named "User" here.
When you add users you can assign them a role among 'admin', 'user', 'staff' etc etc.
In the file "protected/components/UserIdentity.php" write something like:
class UserIdentity extends CUserIdentity { private $id; public function authenticate() { $record=User::model()->findByAttributes(array('email'=>$this->username)); if($record===null) $this->errorCode=self::ERROR_USERNAME_INVALID; else if($record->password!==md5($this->password)) $this->errorCode=self::ERROR_PASSWORD_INVALID; else { $this->id=$record->id; $this->setState('roles', $record->roles); $this->errorCode=self::ERROR_NONE; } return !$this->errorCode; } public function getId(){ return $this->id; } }
The important line is
$this->setState('roles', $record->roles);
It adds user roles to their session.
You can fetch the role of the current user with
Yii::app()->user->getState('roles') or simply
Yii::app()->user->roles.
Modify or create the "WebUser.php" file under the "protected/components" directory so that it overloads the
checkAccess() method.
class WebUser extends CWebUser { /** * Overrides a Yii method that is used for roles in controllers (accessRules). * * @param string $operation Name of the operation required (here, a role). * @param mixed $params (opt) Parameters for this operation, usually the object to access. * @return bool Permission granted? */ public function checkAccess($operation, $params=array()) { if (empty($this->id)) { // Not identified => no rights return false; } $role = $this->getState("roles"); if ($role === 'admin') { return true; // admin role has access to everything } // allow access if the operation request is the current user's role return ($operation === $role); } }
You can define your own logic in this
checkAccess() methods.
Make sure this class is used by Yii. The config file "protected/config/main.php" must contain:
'components' => array( // ... 'user' => array( 'class' => 'WebUser', ),
Sidenote:
CWebUser::checkAccess() usually connects to the authorization system loaded in Yii. Here we are replacing it with a simple system that just deals with roles instead of the hierarchical system defined by the derivatives of CAuthManager. See the official tutorial, Role-Based Access Control for details.
Yii::app()->user->checkAccess('admin')to check if the current user has the 'admin' role. The call
Yii::app()->user->checkAccess('staff')will return true if the user has the role "staff" or "admin".
accessRules()using the "roles" attribute of the rule.
See examples below.
The controller must contain:
public function filters() { return array( 'accessControl', // perform access control for CRUD operations ); } public function accessRules() { return array( array('allow', 'actions'=>array('admin'), 'roles'=>array('staff', 'devel'), ), array('deny', // deny all users 'users'=>array('*'), ), ); }
Here the "admin" action of the controller has restricted access: only those with roles "staff" or "devel" can access it.
As described in the API doc of CAccessRule, the "roles" attribute will in fact call
Yii::app()->user->checkAccess().
You can also use just one menu for all users based upon different roles. for example
$user = Yii::app()->user; // just a convenience to shorten expressions $this->widget('zii.widgets.CMenu',array( 'items'=>array( array('label'=>'Users', 'url'=>array('/manageUser/admin'), 'visible'=>$user->checkAccess('staff')), array('label'=>'Your Ideas', 'url'=>array('/userarea/ideaList'), 'visible'=>$user->checkAccess('normal')), array('label'=>'Login', 'url'=>array('/site/login'), 'visible'=>$user->isGuest), array('label'=>'Logout ('.Yii::app()->user->name.')', 'url'=>array('/site/logout'), 'visible'=>!$user->isGuest) ), ));
A very usual need is to allow a user to update its own data but not other's. In this case, the user's role is meaningless without the context: the data that will be modified.
This is why CWebUser::checkAccess() has an optional "$param" parameter. Now suppose we want to check is a user has the right to update a Post record. We can write:
if (Yii::app()->user->checkAccess('normal', $post)) {
Of course
WebUser::checkAccess() must be extended to use this "$params" parameter.
This will depend on your application's logic.
For instance, it could be as simple as granting access iff
$post->userId == $this->id.
Total 17 comments
You shouldn't use strstr() for the role check. If there are two roles named user and superuser then a check for user will always match superuser as well. Better to use array search or have an explicit delimiter...
Here is the updated version...
Thank you very much for this document.Very useful for me. Thank!
Hi,
On your user table make a column named 'roles'.
Details described here.
Hi,
On your User model did you create a column called role or roles. In the example they have created a column called roles, which is not clear.
The key is this line:
It says assign the column "roles" from the record to a state variable called "roles".
Hope this helps.
Neil
Hi, I just a newbie in Yii. I have read this article and followed all instructions here, but I had error User.roles is not defined when I tried to login. Here is my UserIdentity.php
And then EWebUser.php
At last accessRules method in UserController.php
I hope anyone can help solve this problem, thank you very much.
Work great for small projects, thanks for the wiki!
Hi guys
I try to all type of set access role and set role , I got role in controller but this can't be access a action page
thnaks
hari maliya
Hi guys
How to create access role in yii and where in yii application part ?
I want to create access role in yii application but i have a problem and dont know about where to assign role in yii like i have three department role 1.admin -: admin have a all access role in our application 2.staff -: staff same of page and access role like to edit or update 3.user -: user have a all access page only viewing in our application
These type of role can set in controller but i can justify where to write all access in yii and how to set access role ,
thank hari maliya
If you want to assign multiple roles to a user (separated by a comma) you can replace
with
Sorry guys, but this point it's not really clear for me
"The call Yii::app()->user->checkAccess('staff') will return true if the user has the role "staff" or "admin"."
What do i've to specify inside checkAccess? In my app, I've 3 user types (admin, operator, account) and i'd like to filter the access inside controllers and filter displayed content.
Inside the controller, i use
where User::ROLE_ADMIN and User::ROLE_OPERATOR are int 1 and 2, and it's the value assigned inside userIdentity
where $record->role_id can be 1 or 2
But it's not working, if i chanche the accessRules with
users with User::ROLE_OPERATOR can access anyway. :(
Any suggestion? Thank you
ps:
this is the code inside checkAccess
You can also use YiiSmartMenu extension.
Update: Please see Derek++ comment My usage of strtstr() is incorrect.
Hello,
I needed to be able to check for multiple roles. With a minor change I can now do this:
*Note: you can do any combination | ; , . I just choose commas. The command will find any match.
Place the following below $role === 'admin' in protected/components/WebUser.php
Full protected/components/WebUser.php file:
I had the idea, thanks.
Thank you very much for the text.
If set autoLogin=>true in config all data will saved in cookie and i can change my role. WebUser it's better place for method getRole().
Hi, Thank you for a great text! I've been looking for "as simpliest as possible" solution like that, to incorporate it into smaller projects, that do not need a complex, "heavy" RBAC module. Thank you again.
I have one doubt, since the methods isAdmin, isUser etc of Utils class are not static (public Methods) How can we refer them as Utils::isAdmin in access rules or i Zii widgest?
Please login to leave your comment. | http://www.yiiframework.com/wiki/328/simple-rbac/ | CC-MAIN-2018-13 | refinedweb | 1,325 | 57.67 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.