content
stringlengths 228
999k
| pred_label
stringclasses 1
value | pred_score
float64 0.5
1
|
---|---|---|
Languages
Introduction
This section is related to the languages that are manipulated by Atelier B, namely:
• the B language
• the Event-B language
• the THEORY language
• the refinement rule language
The B language
The B language was invented by J.R Abrial. “The B-Book: assigning programs to meanings” (Cambridge University Press – ISBN 0-521-49619-5) contains the mathematical basis on which it is founded as well as the precise definitions of the notations used. However, over the years, the B language has been adapted to industrial needs (through Atelier B) and the current “operational” definition of this language is rather different from the one exposed in the B-Book. Among the various modifications, we can mention:
• addition of LOCAL_OPERATIONS: operations call be specified, implemented and used in a single implementation (saving a new decomposition)
• addition of records
• removal of trees: trees, as defined in the B-Book, can’t be easily manipulated, leading to very difficult mathematical demonstrations
So we may consider that the current reference document describing the B language is
Another document, explaining how to use the B language for software development, is also available:
The Event-B language
Some history
The event-B language was born in the late 90’s, initially described in Guidelines to formal system studies.
The first reference manual was written during the european project MATISSE, as well as a tool, evt2b, translating event-B models into (“software”) B models supported by Atelier B 3.x.
Modalities were also added to the language, following “Introducing dynamic constraints in B”.
Event-B was then experimented during the project PUSSEE, leading to the development of an event-b to VHDL translator.
The project RODIN was initiated to develop a platform supporting event-B. The language was simplified (many B constructs and operators were removed, new ones added), leading to Event-B language description manual.
The project DEPLOY aims at enriching the platform and the language through industrial deployments (hence the name of the project). A second version of the language was released in 2009.
Atelier B 4.0 is the first Atelier B natively supporting event-B, even if the language slightly differs from the one supported by the Rodin platform.
The Event-B language supported by Atelier B 4.x
Summary
The event-B mathematical language is exactly the same as the B mathematical language, described in the B Language Reference Manual. The differences are in:
• the kind of components supported: SYSTEM (for top-level component, ako specification) and REFINEMENT (IMPLEMENTATION is not supported)
• the visibility clauses: only SEES and INCLUDES are supported.
• the substitutions: events should match with one of these three substitutions:
• BEGIN <subst> END
• ANY <vars> WHERE <pred> THEN <subst> END
• SELECT <pred> THEN <subst> END
However substitutions <subst> may any substitution allowed in the B Language Reference Manual. For example, an IF THEN ELSE substitution, a sequencing substitution, etc.
New kewords have been introduced:
• ref: for indicating what event(s) an event is refining
• WITNESS: when refinening an ANY substitution. It allows for simplifying the demonstration of existence of values for the local variables introduced in the ANYsubstitution.
Further extensions are being considered. For example, introduction of MODALITIES, as it was the case in the MATISSE version of event-B language. A draft specification has been produced and is available here.
Moreover, a RODIN to Atelier B importer is being developed, enabling the port of Rodin event-b projects to Atelier B projects.
Event-B language description
The language is described in Atelier B Event B Language.
There is also a very good Tutorial on the Event-B method, by Dominique Cansell and Dominique Méry.
The THEORY language
Presentation
This language was created to simplify the development of tools manipulating B models. It is close to PROLOG. Several Atelier B tools are implemented in THEORY language:
• typechecker,
• proof obligation generator,
• prover,
• predicate prover,
• arithmetic prover,
• well-definedness verifier (also called Delta tool).
A subset of the THEORY language allows to write mathematical rules that can be added to an Atelier B project, in order to improve Atelier B prover.
Tool
The THEORY language interpreter is part of the Atelier B distribution. The executable file is krt or krt.exe.
Reference documentation
• Operations and guards
• Semantics
• Syntax
• Writing Mathematical Rules
The Mathematical Rule Language
This language is a subset of the THEORY language, and is used to improve Atelier B automatic prover, by adding mathematical rules.
A document is describing this language:
• Writing Mathematical Rules 1.1 (pdf-French)
• Writing Mathematical Rules 1.1 (Wiki manual – English – Ongoing translation)
• Image:Writing mathematical rules.pdf (PDF English)
|
__label__pos
| 0.66189 |
Bug 866747 - After setting scales_from/scales_to a few times value can no longer be set [US2862]
After setting scales_from/scales_to a few times value can no longer be set [U...
Status: CLOSED CURRENTRELEASE
Product: OpenShift Origin
Classification: Red Hat
Component: Master (Show other bugs)
2.x
Unspecified Unspecified
unspecified Severity high
: ---
: ---
Assigned To: Rajat Chopra
libra bugs
:
Depends On:
Blocks:
Show dependency treegraph
Reported: 2012-10-15 23:55 EDT by Clayton Coleman
Modified: 2015-05-14 20:52 EDT (History)
2 users (show)
See Also:
Fixed In Version:
Doc Type: Bug Fix
Doc Text:
Story Points: ---
Clone Of:
Environment:
Last Closed: 2012-11-06 13:49:25 EST
Type: Bug
Regression: ---
Mount Type: ---
Documentation: ---
CRM:
Verified Versions:
Category: ---
oVirt Team: ---
RHEL 7.3 requirements from Atomic Host:
Cloudforms Team: ---
Attachments (Terms of Use)
None (edit)
Description Clayton Coleman 2012-10-15 23:55:44 EDT
Application is ruby-1.8 scaling. After a few times of setting scales_to/scales_from back and forth I start getting the error:
"Could not completely distribute scales_from to all groups. Value constrained to 2" - 164
In this case I was attempting to set scales_from/scales_to to 3 (which worked originally).
User in mongo:
{
"_id": "user_with_scaled_app",
"apps": [
{
"categories": [
],
"license": "unknown",
"start_order": [
"@@app\/comp-proxy\/cart-ruby-1.8",
"@@app\/comp-proxy\/cart-haproxy-1.4",
"@@app\/comp-proxy",
"@@app\/comp-web\/cart-ruby-1.8",
"@@app\/comp-web"
],
"group_instances": [
{
"supported_max": -1,
"addtl_fs_gb": 0,
"group_name": "default",
"name": "@@app\/comp-web\/cart-ruby-1.8",
"reused_by": [
"@@app\/comp-web\/cart-ruby-1.8",
"@@app\/group-web"
],
"node_profile": "small",
"max": 1,
"profile_name": "default",
"supported_min": 1,
"min": 1,
"cart_name": "ruby-1.8",
"gears": [
{
"configured_components": [
"@@app\/comp-web\/cart-ruby-1.8"
],
"name": "d9ce313db9",
"group_instance_name": "@@app\/group-web",
"node_profile": "small",
"server_identity": "ip-10-116-202-62",
"uid": null,
"uuid": "d9ce313db9ec4e749d87cb2d7de86290"
}
],
"component_instances": [
"@@app\/comp-web\/cart-ruby-1.8",
"@@app\/comp-web"
],
"uuid": "63603803cca34a8b9df045fe28919bf2"
},
{
"supported_max": 1,
"addtl_fs_gb": 0,
"group_name": "default",
"name": "@@app\/comp-proxy\/cart-haproxy-1.4",
"reused_by": [
"@@app\/group-proxy",
"@@app\/comp-proxy\/cart-ruby-1.8",
"@@app\/comp-proxy\/cart-haproxy-1.4"
],
"node_profile": "small",
"max": 1,
"profile_name": "default",
"supported_min": 1,
"min": 1,
"cart_name": "haproxy-1.4",
"gears": [
{
"configured_components": [
"@@app\/comp-proxy\/cart-ruby-1.8",
"@@app\/comp-proxy\/cart-haproxy-1.4"
],
"name": "scaled",
"group_instance_name": "@@app\/comp-proxy\/cart-ruby-1.8",
"node_profile": "small",
"server_identity": "ip-10-116-202-62",
"uid": null,
"uuid": "cfd96c8ec7554da8bcc49c981c8584e6"
}
],
"component_instances": [
"@@app\/comp-proxy",
"@@app\/comp-proxy\/cart-ruby-1.8",
"@@app\/comp-proxy\/cart-haproxy-1.4"
],
"uuid": "d9e87abd4944446c93d9948546a366b7"
}
],
"vendor": "unknown",
"description": "",
"version": "0.0",
"conn_endpoints_list": [
{
"from_comp_inst": "@@app\/comp-web\/cart-ruby-1.8",
"to_comp_inst": "@@app\/comp-proxy\/cart-haproxy-1.4",
"to_connector": {
"type": "NET_TCP:gear-endpoint-info",
"name": "set-gear-endpoints",
"required": false
},
"from_connector": {
"type": "NET_TCP:gear-endpoint-info",
"name": "publish-gear-endpoint",
"required": false
}
},
{
"from_comp_inst": "@@app\/comp-web\/cart-ruby-1.8",
"to_comp_inst": "@@app\/comp-proxy\/cart-haproxy-1.4",
"to_connector": {
"type": "NET_TCP:httpd-proxy-info",
"name": "set-proxy",
"required": false
},
"from_connector": {
"type": "NET_TCP:httpd-proxy-info",
"name": "publish-http-url",
"required": false
}
}
],
"suggests_feature": [
],
"comp_instances": [
{
"cart_data": [
null
],
"addtl_fs_gb": 0,
"name": "@@app\/comp-web\/cart-ruby-1.8",
"group_instance_name": "@@app\/comp-web\/cart-ruby-1.8",
"parent_cart_name": "ruby-1.8",
"dependencies": [
],
"cart_properties": [
],
"parent_cart_profile": "default",
"exec_order": [
],
"parent_component_name": "default",
"parent_cart_group": "default"
},
{
"cart_data": [
null
],
"addtl_fs_gb": 0,
"name": "@@app\/comp-proxy\/cart-ruby-1.8",
"group_instance_name": "@@app\/comp-proxy\/cart-ruby-1.8",
"parent_cart_name": "ruby-1.8",
"dependencies": [
],
"cart_properties": [
],
"parent_cart_profile": "default",
"exec_order": [
],
"parent_component_name": "default",
"parent_cart_group": "default"
},
{
"cart_data": [
],
"addtl_fs_gb": 0,
"name": "@@app\/comp-proxy",
"group_instance_name": "@@app\/group-proxy",
"parent_cart_name": "scaled",
"dependencies": [
"@@app\/comp-proxy\/cart-ruby-1.8",
"@@app\/comp-proxy\/cart-haproxy-1.4"
],
"cart_properties": [
],
"parent_cart_profile": "default",
"exec_order": [
"@@app\/comp-proxy\/cart-ruby-1.8",
"@@app\/comp-proxy\/cart-haproxy-1.4"
],
"parent_component_name": "proxy",
"parent_cart_group": "proxy"
},
{
"cart_data": [
],
"addtl_fs_gb": 0,
"name": "@@app\/comp-web",
"group_instance_name": "@@app\/group-web",
"parent_cart_name": "scaled",
"dependencies": [
"@@app\/comp-web\/cart-ruby-1.8"
],
"cart_properties": [
],
"parent_cart_profile": "default",
"exec_order": [
"@@app\/comp-web\/cart-ruby-1.8"
],
"parent_component_name": "web",
"parent_cart_group": "web"
},
{
"cart_data": [
""
],
"addtl_fs_gb": 0,
"name": "@@app\/comp-proxy\/cart-haproxy-1.4",
"group_instance_name": "@@app\/comp-proxy\/cart-haproxy-1.4",
"parent_cart_name": "haproxy-1.4",
"dependencies": [
],
"cart_properties": [
],
"parent_cart_profile": "default",
"exec_order": [
],
"parent_component_name": "default",
"parent_cart_group": "default"
}
],
"name": "scaled",
"conflicts_feature": [
],
"configure_order": [
"@@app\/comp-proxy\/cart-ruby-1.8",
"@@app\/comp-proxy\/cart-haproxy-1.4",
"@@app\/comp-proxy",
"@@app\/comp-web\/cart-ruby-1.8",
"@@app\/comp-web"
],
"website": "",
"node_profile": "small",
"ssh_keys": {
"haproxy": "AAAAB3NzaC1yc2EAAAABIwAAAQEAycKVO8uun43m6YHpiAt7uDgo9ef+NzmmXm4zctwdfGuS\/9YZLf3aZ2eMX\/NZVc6STF2LLZAHPTvl\/ciD5spwdHDmGyCwSVWl4TuehBo1cJqG88ZVkEuL0enyYTxICkwtx9+ItRLFZwgk9yeh31oeem8f09LXSZsNzU7TVqIt\/f0gCXG6VDVqpkUrP2u35Z7iFBoBOhulHhLlCQc\/vXCeoasxc1LVCiRnz070HzHX5DMzadpz6aRArLElqAEr6DavGjZuDPKeI2fi8ngOEO\/21ekBZhR4rcr9Xa2hEaXdo08WFZ56XNoDr4ebDPuL6jDBiHkQ2IgamfuSt+NwZHoQHw=="
},
"display_name": "scaled-0.0-noarch",
"default_profile": "default",
"domain": {
"namespace": "1350317915e5bf06",
"uuid": "f1d5b17dd7134609b11098b141c978cd"
},
"help_topics": [
],
"profiles": [
{
"group_overrides": [
[
"proxy",
"proxy\/haproxy-1.4"
],
[
"proxy",
"proxy\/ruby-1.8"
],
[
"web",
"web\/ruby-1.8"
]
],
"start_order": [
],
"connections": [
{
"components": [
"proxy\/haproxy-1.4",
"web\/ruby-1.8"
],
"name": "auto-scale"
},
{
"components": [
"proxy\/ruby-1.8",
"web\/ruby-1.8"
],
"name": "proxy-web"
}
],
"components": [
{
"subscribes": [
],
"publishes": [
],
"name": "proxy",
"depends_service": [
],
"generated": false,
"depends": [
"ruby-1.8",
"haproxy-1.4"
]
},
{
"subscribes": [
],
"publishes": [
],
"name": "web",
"depends_service": [
],
"generated": false,
"depends": [
"ruby-1.8"
]
}
],
"stop_order": [
],
"name": "default",
"configure_order": [
"proxy\/ruby-1.8",
"proxy\/haproxy-1.4"
],
"generated": true,
"groups": [
{
"name": "proxy",
"component_refs": [
{
"name": "proxy",
"component": "proxy"
}
],
"generated": false,
"scaling": {
"max": -1,
"min": 1
}
},
{
"name": "web",
"component_refs": [
{
"name": "web",
"component": "web"
}
],
"generated": false,
"scaling": {
"max": -1,
"min": 1
}
}
],
"provides": [
]
}
],
"requires": [
],
"requires_feature": [
],
"proxy_cartridge": "haproxy-1.4",
"cart_data_def": [
],
"provides_feature": [
],
"architecture": "noarch",
"uuid": "cfd96c8ec7554da8bcc49c981c8584e6",
"creation_time": "2012-10-15T12:18:40-04:00",
"scalable": true,
"license_url": ""
}
],
"capabilities": {
"gear_sizes": [
"small"
]
},
"consumed_gears": 2,
"domains": [
{
"namespace": "1350317915e5bf06",
"uuid": "f1d5b17dd7134609b11098b141c978cd"
}
],
"env_vars": null,
"login": "user_with_scaled_app",
"max_gears": 3,
"parent_user_login": null,
"ssh_keys": [
],
"system_ssh_keys": null,
"usage_records": [
{
"event": "begin",
"sync_time": null,
"usage_type": "GEAR_USAGE",
"gear_uuid": "d9ce313db9ec4e749d87cb2d7de86290",
"uuid": "1160c5518f2e4133a67e62aced21b9ae",
"time": ISODate("2012-10-15T16:18:43.32Z"),
"gear_size": "small"
},
{
"event": "begin",
"sync_time": null,
"usage_type": "GEAR_USAGE",
"gear_uuid": "cfd96c8ec7554da8bcc49c981c8584e6",
"uuid": "66601a38e56940d0a60a2412c00a8e60",
"time": ISODate("2012-10-15T16:18:50.316Z"),
"gear_size": "small"
}
],
"uuid": "45adef91ebe640c595d094354f6088ed"
}
Comment 1 Rajat Chopra 2012-10-16 02:29:22 EDT
The problem is that the current scales_to is smaller than the scales_from being set (irrespective of the fact that a scales_to is being set too). The two factors are not independent of each other and setting one needs to consult how the other is distributed in different groups.
Anyhow - the messaging has been improved now. Instead of the current 'algorithmic' complaint - the message will look like :
Invalid scales_from factor 3 provided. Value out of allowed range ( 2 : 2 ).
... indicating that the given scales_from is more than the current scales_to (2). Or shall we disallow both to be set together?
Comment 2 Rajat Chopra 2012-10-16 23:43:42 EDT
fixed with rev#2b9db98fb91fc323efcf
setting 3:3 from 2:2 is now allowed.
Comment 3 mzimen 2012-10-17 05:40:51 EDT
I was able to scale_up/scale_down between 2:2 and 3:3 forth and back without any issues.
Note You need to log in before you can comment on or make changes to this bug.
|
__label__pos
| 0.885202 |
© 2016 Shmoop University, Inc. All rights reserved.
Algebra Introduction
Algebra Introduction
Negative Numbers
There’s more to making numbers negative than just putting a little line in front of them: you have to really understand what a negative number is and how to deal with one in unusual circumstances.
For example, is -(-(-(-(-5)))) negative or positive? Who knows? (You do.)
Clearly, the first negative sign—the one directly attached to the 5—makes the number negative. But the next sign reflects the number back across 0 on the number line, making it positive once again. After we make a few more flips and wait until the dust settles, we discover that this number is indeed negative, but you can’t make that assumption just because there are negative signs coming out your ears.
If we've got a negative variable in the mix, we can move it to the other side of the equation with addition. Say we're trying to solve for x in the equation 0 = 5 – x. To slide x over to the left side, we'd just add x to both sides and get rid of that negative sign. Like this:
0 = 5 – x
x
= 5 – x + x
x
= 5
Most of the examples in this guide are fairly straightforward, but things can get confusing pretty quickly. (Example one: quintuple negatives.) Take your time with negative numbers, and make sure you get what’s going on before you start slinging them around willy-nilly.
People who Shmooped this also Shmooped...
|
__label__pos
| 0.637411 |
Sign up ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.
I have a fraction with further fractions in both the numerator and denominator. I wish to label the fractions in the numerator and denominator with braces to the right. I would like these braces to span the full height of the fractions but I would not like them to extend the fraction line any further.
I have tried \frac{a}{\left.\frac{b}{c}\right}} which achieves the former but not the latter and I have tried \frac{a}{\frac{b}{c}\mathrlap{\}}} which achieves the latter but not the former, since I can't put one half of the \left \right pair inside \mathrlap and the other half outside.
share|improve this question
How often do you need this construction? If it's a one time thing you could simply use \big,\Big,... e.g. \frac{a}{\frac{b}{c}\mathrlap{\big\}}} – Jesper Ipsen Mar 16 '13 at 16:17
While code snippets are useful in explanations, it is always best to compose a fully compilable MWE that illustrates the problem including the \documentclass and the appropriate packages so that those trying to help don't have to recreate it. – Peter Grill Mar 16 '13 at 16:24
1 Answer 1
up vote 4 down vote accepted
Perhaps what you are looking for is a combination of \mathrlap and \smash which is what is incorporated in the \BraceRight and \BraceLeft macros.
enter image description here
However, as HendrikVogt pointed out, this requires that there be manual spacing added afterwards if there is text that follows it. To alleviate this issue I have defined two more macros \FracBraceBottomRight and \FracBraceBottomLeft which also add the approriate \hptantom after or before the fraction.
enter image description here
One downside of this this is that you need a different macro in case you desire further options (such as optional braces around either side of the numerator. This can be fixed with a better interface to enable/disable the appropriate brace, but I think that that is more of a question of coming up with the better UI.
References:
Code:
\documentclass{article}
\usepackage{mathtools}
\newcommand*{\BraceRight}[1]{#1\mathrlap{\smash{\left.\vphantom{#1}\right\}}}}%
\newcommand*{\BraceLeft}[1]{\mathllap{\smash{\left\{\vphantom{#1}\right.}}#1}%
% http://tex.stackexchange.com/questions/54023/how-to-compute-exact-width-added-by-left-right
\newcommand{\BracKern}{\kern-\nulldelimiterspace}
\newcommand*{\FracBraceBottomRight}[2]{%
\frac{#1}{#2\mathrlap{\smash{\left.\BracKern\vphantom{#2}\right\}}}}%
\hphantom{\left.\vphantom{#2}\right\}}%
}%
\newcommand*{\FracBraceBottomLeft}[2]{%
\hphantom{\left\{\vphantom{#2}\right.\BracKern}%
\frac{#1}{\mathllap{\smash{\left\{\vphantom{#2}\right.}}#2}%
}%
\begin{document}
Requires manual spacing:
$\frac{a}{\frac{b}{c}}$\quad%
$\frac{a}{\BraceLeft{\frac{b}{c}}}$\quad%
$\frac{a}{\BraceRight{\frac{b}{c}}}$
\bigskip
Auto spacing with \verb|\hphantom|:
$\FracBraceBottomRight{a}{\frac{b}{c}}$%
$\FracBraceBottomRight{a}{\frac{b}{c}}$%
$\FracBraceBottomLeft{a}{\frac{b}{c}}$%
$\FracBraceBottomLeft{a}{\frac{b}{c}}$
\end{document}
share|improve this answer
Note that the brace will produce an overlap with material after the fraction. – Hendrik Vogt Mar 16 '13 at 16:33
@HendrikVogt: Yep just noticed that when doing the macro verion. Best fix I can think of is to have a macro that accepts the numerator and denominator of the fraction as paramaters and then adds the brace with an appropriate \hphantom following. But, for the general case, this would require numerous different macros depending on if you perhaps wanted the brace on the top/bottom, left/right or any combinations of these. Of course there is always the tikz way. :-) – Peter Grill Mar 16 '13 at 16:41
Yep, you'll need an appropriate \hphantom after the fraction. – Hendrik Vogt Mar 16 '13 at 16:44
Your Answer
discard
By posting your answer, you agree to the privacy policy and terms of service.
Not the answer you're looking for? Browse other questions tagged or ask your own question.
|
__label__pos
| 0.882893 |
Promotic
KeyVal - saving format of named values
On many places in the PROMOTIC system it is necessary to enter multiple named values in a single text. The format described below can be used for this purpose.
The format is very similar e.g. the syntax of CSS styles in HTML pages.
Syntax:
Name1:Value1;Name2:Value2; ...
For example: "Temperature:85;Pressure:1013.85;Name:Boiler1;"
- Name: Represents value identifier that can be:
- Text identifier (value name):
This is the most common way of entering a value in the KeyVal format.
This is a system name, so it must contain only alphanumeric and must not contain any diacritics, empty string, spaces and the first character must not be a number.
Example: val1:13.5;val2:56;
When transforming the KeyVal substring by the PmMap.mapLoadFromString method the PmMap object is created.
- Numeric identifier (value index):
Example: 0:13.5;1:56;
The first identifier must be 0 and following are ascending (1, 2, 3, ...);
When transforming the KeyVal substring by the PmMap.mapLoadFromString method the PmArray object is created.
All identifiers on given level must be of the same type (text or numeric).
- Value: Follows after colon (:).
- If the value is a real number with decimal point then the decimal separator must be a period.
- The value may contain character colon.
- The value must not contain:
- Char semicolon (";"). Must be replaced by two characters: backslash and s ("\s")
- Char NewLine (0A hexa). Must be replaced by two characters: backslash and n ("\n")
- Char CarriageReturn (0D hexa). Must be replaced by two characters: backslash and r ("\r")
- Char backslash ("\"). Must be replaced by two characters: 2x backslash ("\\")
- Char left curly bracket ("{"). Must be replaced by two characters: backslash and o ("\o")
- Char pravá curly bracket ("{"). Must be replaced by two characters: backslash and c ("\c")
- If the value starts with the "left curly bracket" character then it must be finished with the "pravá curly bracket" character.
It means that the value je compound and there is a text in the KeyVal format inside the brackets.
Example:
"Temperature:85;Parameters:{p1:56;p2:64};"
- The value may contain empty characters at the beginning and at the end (space, tab) and these characters are considered to be valid.
It means that, for example, when saving into the PmMap object (by the mapSaveToString method) the value of the property will contain saved text including these empty characters (at the beginning or at the end).
This format can be used, e.g., for the following purposes:
- in the "Pma object parameters" configurator.
- In the Pm.CreateView method, in the sViewPars and sFramePars parameters.
- In the PmMap object, in mapSaveToString and mapLoadFromString methods.
- In the PmaAlarmGroup object, in the "Sound parameters" configurator.
- and many others
History:
Pm9.00.15: Added option of entering the name as number (i.e. KeyVal of the Array type).
Pm8.03.13: Created
PROMOTIC 9.0.23 SCADA system documentation MICROSYS, spol. s r.o.
Send page remarkContact responsible person
© MICROSYS, spol. s r. o.
|
__label__pos
| 0.969469 |
跳至主要内容
[WebAPIs] 計時與動畫 Timer with setInterval, setTimeout, requestAnimationFrame
• requestAnimationFrame:要自己 call 自己〈自體循環〉,才會有下一次。不用設時間,會根據執行時間的快慢(延遲)做調整。這是處理動畫首選。函式內預設就會產生 time 這個變數。
• setTimeout
• setInterval
window.requestAnimationFrame
// Polyfill for browser capability
var requestAnimationFrame =
window.requestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.msRequestAnimationFrame;
var cancelAnimationFrame = window.cancelAnimationFrame || window.mozCancelAnimationFrame;
requestAnimationFrame(animation); // 開始啟動 requestAnimationFrame
$('#stop').on('click', function () {
cancelAnimationFrame(requestID);
});
function animation(time) {
// Do whatever ...
console.log(time); // function 中可以代 time 就可以看到執行的時間點
requestID = requestAnimationFrame(animation);
}
如果想要停止該 function 繼續執行,一種是不要繼續在該函式呼叫 requestAnimationFrame,另一種則是使用 cancelAnimationFrame,後者記得要把每一次執行後的 requestID 都存起來。
使用例子 @ CodePen
window.setTimeout
利用 setTimeout(函數, 等待時間) 重複執行函數
var timerId;
function delayedAlert() {
timerId = window.setTimeout(slowAlert, 2000); // 設定計時器
}
function slowAlert() {
alert('That was really slow!');
}
function clearAlert() {
window.clearTimeout(timerId); // 清除計時器
}
代入參數(Passing Arguments)
如果有需要在 setTimeout,可以在代入時間的參數後再代入其他自訂的參數:
function animal(firstName, lastName = 'Chen') {
console.log(`${firstName} ${lastName}`);
}
setTimeout(animal, 500, 'Po Jung', 'Chen');
重複呼叫 setTimeout 參數(Recursive setTimeout Calls)
由於 setInterval 可能會在下一個還沒做完就做下一次,而且會超過時間〈延遲〉,所以也可以使用 Recursive setTimeout Calls:
let i = 0;
function increment() {
i++;
console.log(i);
}
let timer = setTimeout(function myTimer() {
increment();
timer = setTimeout(myTimer, 1000);
}, 1000);
// let's cancel after 7 seconds
setTimeout(() => {
console.log('Cancelling');
clearTimeout(timer);
}, 7000);
window.setInterval
• 利用 setInterval(函數, 時間) 啟動
• 利用 clearInterval(timerId) 停止計時
var intervalId;
function changeColor() {
intervalId = setInterval(flashText, 500); // 啟動計時器
}
function flashText() {
var oElem = document.getElementById('my_box');
oElem.style.color = oElem.style.color == 'red' ? 'blue' : 'red';
}
function stopTextColor() {
clearInterval(intervalId); // 清除計時器
}
參考
|
__label__pos
| 0.923946 |
Example Configurations
TLS can be very confusing. Here are some settings that can help.
Connecting to an internal web service
If you are using WS to communicate with a single internal web service which is configured with an up to date TLS implementation, then you have no need to use an external CA. Internal certificates will work fine, and are arguably more secure than the CA system.
Generate a self signed certificate from the generating certificates section, and tell the client to trust the CA’s public certificate.
ssl-config {
trustManager = {
stores = [
{ type = "JKS", path = "exampletrust.jks" }
]
}
}
Connecting to an internal web service with client authentication
If you are using client authentication, then you need to include a keyStore to the key manager that contains a PrivateKeyEntry, which consists of a private key and the X.509 certificate containing the corresponding public key. See the “Configure Client Authentication” section in generating certificates.
ssl-config {
keyManager = {
stores = [
{ type = "JKS", path = "client.jks", password = "changeit1" }
]
}
trustManager = {
stores = [
{ type = "JKS", path = "exampletrust.jks" }
]
}
}
Connecting to several external web services
If you are communicating with several external web services, then you may find it more convenient to configure one client with several stores:
ssl-config {
trustManager = {
stores = [
{ type = "PEM", path = "service1.pem" }
{ path = "service2.jks" }
{ path = "service3.jks" }
]
}
}
If client authentication is required, then you can also set up the key manager with several stores:
ssl-config {
keyManager = {
stores = [
{ type: "PKCS12", path: "keys/service1-client.p12", password: "changeit1" },
{ type: "PKCS12", path: "keys/service2-client.p12", password: "changeit2" },
{ type: "PKCS12", path: "keys/service3-client.p12", password: "changeit3" }
]
}
}
Both Private and Public Servers
If you are using WS to access both private and public servers on the same profile, then you will want to include the default JSSE trust store as well:
ssl-config {
trustManager = {
stores = [
{ path: exampletrust.jks } # Added trust store
{ path: ${java.home}/lib/security/cacerts } # Fallback to default JSSE trust store
]
}
}
|
__label__pos
| 0.999905 |
/* 093 27-Feb-87 ov.c O V E R V I E W This program allows the user to perform common operations on disk files in a visual, tabular manner. Copyright (c) 1987 by Blue Sky Software. All rights reserved. */ #define VERSION "OverView 1.02, 1-Mar-87" #include #include #include #include "ov.h" int brkhit; /* NZ when ^Break/^C hit */ int winupdate; /* NZ when windows need updating */ unsigned char anyshowall; /* NZ when show all is active */ unsigned char dir_display; /* NZ when dir tree displayed */ unsigned char def_display; /* NZ when define screen displayed */ unsigned char help_display; /* NZ when help is active */ unsigned char view_display; /* NZ when viewing a file */ unsigned char restricted; /* NZ when some functions disabled */ char *ovname = NULL; /* name used to invoke (if >= DOS 3) */ char *initialdir; /* name of initial dir */ unsigned int dataseg; /* ov's data segment reg value */ FILE_ENT files[MAX_FILES]; /* array of file entries */ char *cantopen = "Can't open "; /* common message */ jmp_buf back_to_main; /* error handling jmp_buf block */ extern unsigned char _osmajor; /* DOS major version # */ /* function declarations */ char *getcwd(); FILE_ENT *nxtfile(); int sel_all(), define(), help(), show_all(); int quit(), login(), erase_current(), erase_tagged(), view(), sortname(); int copy_current(), copy_tagged(), info(), renew(), do_cmd(), spawn_cli(); int dtree(), dir_login(), dir_mkdir(), dir_rmdir(), dir_exit(), sel_attrib(); int ren_cur(), ren_tag(), set_mask(), clr_mask(), invert_mask(), sel_tagged(); int sort_asc(), sort_desc(), sort_name(), sort_ext(), sort_date(), sort_size(); int set_vol(), tag_current(), tag_name(), tag_date(), tag_reset(), tag_today(); int tag_modified(), tag_invert(), attrib_current(), attrib_tagged(), execute(); int win_open(), win_close(), win_expand(), win_next(), win_prev(), sort_none(); /* define the current window structure */ struct window cw = { NULL, NULL, 0, FIRST_NROW, NAME_ROWS, FIRST_NROW, NAME_ROWS, 0, 0, 0, 0, 0, 0, 0, NULL, 0, 0, 0, 0, NULL, 'A', sortname, 0, 0, RDONLY | HIDDEN | SYSTEM | DIR | ARCHIVE, 1 }; /* define some of the menus */ char current[] = "Current"; char tagged[] = "Tagged"; extern MENU top_file_menu[], top_dir_menu[]; MENU *top_menu = top_file_menu; MENU attrib_menu[] = { { current,"Change the current file's attributes", attrib_current, NULL }, { tagged, "Change the attributes of all tagged files", attrib_tagged, NULL }, { NULL, NULL, NULL, NULL } }; MENU copy_menu[] = { { current, "Copy the current file", copy_current, NULL }, { tagged, "Copy the tagged files", copy_tagged, NULL }, { NULL, NULL, NULL, NULL } }; MENU erase_menu[] = { { current, "Erase the current file", erase_current, NULL }, { tagged, "Erase all tagged files", erase_tagged, NULL }, { NULL, NULL, NULL, NULL } }; MENU mask_menu[] = { { "Set", "Set the file mask", set_mask, NULL }, { "Clear", "Clear the file mask", clr_mask, NULL }, { "Invert", "Invert the meaning of the mask", invert_mask, NULL }, { NULL, NULL, NULL, NULL } }; MENU ren_menu[] = { { current, "Rename or move the current file", ren_cur, NULL }, { tagged, "Move all tagged files", ren_tag, NULL }, { NULL, NULL, NULL, NULL } }; MENU select_menu[] = { { "Attrib", "Set selection attributes", sel_attrib, NULL }, { "Mask", "Set, Clear, or Invert file name selection mask", NULL, mask_menu }, { "Reset", "Reset selection criteria to defaults", sel_all, NULL }, { "Showall", "Toggle selection of all files on current drive", show_all, NULL }, { "Tagged", "Select all tagged files", sel_tagged, NULL }, { NULL, NULL, NULL, NULL } }; MENU sort_submenu[] = { { "Ascending", "Sort files in ascending order", sort_asc, NULL }, { "Descending", "Sort files in descending order", sort_desc, NULL }, { NULL, NULL, NULL, NULL } }; MENU sort_menu[] = { { "Name", "Sort by primary name", sort_name, NULL }, { "Ext", "Sort by extension", sort_ext, NULL }, { "Date", "Sort by date", sort_date, NULL }, { "Size", "Sort by size", sort_size, NULL }, { "Options", "Set sort options", NULL, sort_submenu }, { "Unsorted", "Do not sort entries", sort_none, NULL }, { NULL, NULL, NULL, NULL } }; MENU tag_menu[] = { { current, "Tag/Untag the current file", tag_current, NULL }, { "Date", "Tag files by date and time", tag_date, NULL }, { "Invert", "Invert the tag state of all files", tag_invert, NULL }, { "Modified", "Tag files with Archive attribute", tag_modified, NULL }, { "Name", "Tag files by name", tag_name, NULL }, { "Reset", "Untag all files", tag_reset, NULL }, { "Today", "Tag all files created/modified today", tag_today, NULL }, { NULL, NULL, NULL, NULL } }; MENU win_menu[] = { { "Open", "Open an additional window", win_open, NULL }, { "Close", "Close the current window", win_close, NULL }, { "Expand", "Expand the current window to full screen (closes others)", win_expand, NULL }, { "Next", "Switch to the next window", win_next, NULL }, { "Prev", "Switch to the previous window", win_prev, NULL }, { NULL, NULL, NULL, NULL } }; MENU other_menu[] = { { "Attrib", "Change the attributes of one or more files", NULL, attrib_menu }, { "Command", "Execute a single DOS command", do_cmd, NULL }, { "Define", "Define screen parameters", define, NULL }, { "Interperter", "Spawn a DOS command interpreter", spawn_cli, NULL }, { "Select", "Set file selection criteria", NULL, select_menu }, { "Volume", "Create or change the volume label", set_vol, NULL }, { "Window", "Open, close, switch file display windows", NULL, win_menu }, { "Xecute", "Execute a program, command, or batch file", execute, NULL }, { "Other", "Help, Copy, Dir, Erase, Info, Login, New, Rename, Sort, Tag, View, Quit", NULL, top_file_menu }, { NULL, NULL, NULL, NULL } }; MENU top_file_menu[] = { { "Help", "Get help on using OVERVIEW", help, NULL }, { "Copy", "Copy one or more files", NULL, copy_menu }, { "Dir", "Display the disk's directory tree", dtree, top_dir_menu }, { "Erase", "Erase (delete) one or more files", NULL, erase_menu }, { "Info", "Toggle display of extra file information", info, NULL }, { "Login", "Login (switch) to another disk/directory", login, NULL }, { "New", "Reread and redisplay the directory", renew, NULL }, { "Rename", "Rename or move one or more files", NULL, ren_menu }, { "Sort", "Sort the file entries by Name, Extension, Date, or Size", NULL, sort_menu }, { "Tag", "Tag one or more files", NULL, tag_menu }, { "View", "View the current file", view, NULL }, { "Other", "Attrib, Command, Define, Interperter, Select, Volume, Window, Xecute", NULL, other_menu }, { "Quit", "Exit OVERVIEW and return to DOS", quit, NULL }, { NULL, NULL, NULL, NULL } }; /****************************************************************************** ** M A I N ** *****************************************************************************/ main(argc,argv) int argc; char *argv[]; { setvattrib(DIS_NORM); /* select initial video attribute */ /* display the signon while initializing */ init_tty(); /* init the terminal settings */ ovlogo(VERSION); /* display the logo screen */ /* init internal data structures and display a screen of files */ { struct SREGS sr; /* get OverView's data seg reg value */ segread(&sr); /* for a couple of other routines */ dataseg = sr.ds; /* to use */ } if (_osmajor >= 3) /* if dos 3.0 or more, argv[0] has */ ovname = *argv; /* the name ov was started with */ getcwd(cw.dirbuf,MAX_PATHLEN); /* get current directory pathname */ initdrive(*cw.dirbuf); /* init DRIVE_ENT 4 current drive */ initialdir = Strdup(cw.dirbuf); /* save the initial dir spec */ getfiles(); /* get files from current directory */ adjust_window(); /* set # rows, cols, etc */ getchr(); /* any keypress to continue */ setup_file_scr(); /* display the static screen image */ update_header(); /* display header info */ update_window(1); /* and a window of data */ grabbrk(&brkhit); /* grab the ^Break/^C interrupt handler */ /* call setjmp to establish the error handling jmp_buf, errors in subfuntions will return here to start the next command */ setjmp(back_to_main); /* main processing, obey each user command, terminate when done or user enters the EOF character or hits ^Break/^C */ while (1) { obey(); /* only returns after ^Z or ^Break/^C */ quit(); /* doesn't return if quitting */ } } /****************************************************************************** ** O B E Y ** *****************************************************************************/ obey() { /* obey / process a user command */ register int ch, i; char *dp, *dirplus(); menu_init(); /* display the initial menu */ while ((ch = getchr()) != EOF_CH) { /* get a char from the user */ brkhit = 0; /* clr brk flag before each ov command */ switch (ch) { case LEFT: case RIGHT: /* left, right arrows */ case UP: case DOWN: /* up, down arrows */ case HOME: case END: case PGDN: case PGUP: if (dir_display) dir_move(ch); /* move the dir pointer */ else if (view_display) view_move(ch); /* move within the view buffer/file */ else if (def_display) def_move(ch); /* move within define screen mode */ else if (!restricted) move_file(ch); /* move the file pointer */ break; case ' ': case 9: /* advance the menu selection pointer */ menu_advance(); break; case 8: /* backup the menu selection pointer */ menu_backup(); break; case RETURN: /* CR - do current menu selection */ menu_do_current(); break; case 27: /* escape - return to top menu */ menu_init(); /* reset the menu subsystem */ break; case TAG: /* single key command to tag current */ if (!restricted) { tag_current(); if (cw.curidx < cw.nfiles-1) move_file(DOWN); } break; case GOPAR: /* login to the parent dir */ if (dir_display) dir_move(GOPAR); else if (!restricted) { switch_dir(dp = dirplus(&files[cw.curidx],"..")); free(dp); menu_init(); } break; case GOSUB: /* login to dir under file ptr */ if (dir_display) { dir_login(); menu_init(); } else { if (!restricted) if (files[cw.curidx].flags & DIR) { switch_dir(dp = dirplus(&files[cw.curidx], files[cw.curidx].name)); free(dp); menu_init(); } else beep(); } break; case NEXTT: /* goto next tagged file */ case PREVT: /* goto prev tagged file */ if (!restricted) tag_find(ch == NEXTT ? 1 : -1); break; case OPENW: /* open another file display window */ if (!restricted) win_open(); break; case CLOSEW: /* close current file display window */ if (!restricted) win_close(); break; case NEXTW: /* goto next file display window */ if (!restricted) win_next(); break; case PREVW: /* goto prev file display window */ if (!restricted) win_prev(); break; default: /* see if the 1st letter of selection */ if (!menu_do_char(ch)) /* do menu selection starting with ch */ beep(); /* beep if not a valid selection */ break; } if (winupdate) { /* some commands ask for one or */ refresh_screen(1); /* more windows to be updated */ update_header(); /* make sure header is current */ winupdate = 0; } } } /****************************************************************************** ** Q U I T ** *****************************************************************************/ quit() { /* exit from overview */ int ch; /* Ask the user if he really wants to exit (default = N). If so, check to see if we are still in the initial startup dir. If so, just exit. If not, ask if we should return to the original dir before quitting (default = return). */ ch = ask("Quit OVERVIEW and return to DOS? (y/N): "); if (yes(ch)) { getcwd(cw.dirbuf,MAX_PATHLEN); /* can mess cw.dibuf up cause quitting */ if (strcmp(initialdir,cw.dirbuf) != 0) { ch = ask("Exit to current directory, or Return to original? (e/R): "); if (toupper(ch) != 'E') change_dir(initialdir); } reset_tty(); /* restore pre OV tty settings */ exit(); /* So long, thanks for all the fish */ } }
|
__label__pos
| 0.981933 |
view mod_muc_log.wiki @ 61:70425a2e230f
Edited wiki page through web user interface.
author t.ephraim
date Sun, 18 Oct 2009 22:05:15 +0000
parents 4410f015d570
children d7a687cb24e4
line wrap: on
line source
#summary Module which logs muc conversations to a file
#labels Stage-Alpha
= Introduction =
This module logs the conversation of muc running on this server to a daily changing file.
There is a file per room.
= Details =
Here is a example config with just the muclogging parts added to the right sections:
{{{
host "*"
muc_log = {
folder = "/var/log/prosody/rooms";
http_port = 5290;
}
component "rooms.example.com" "muc"
logging = true;
}}}
The http server part would then be reachable at the url:
{{{
http://example.com:5290/muc_log/
}}}
= TODO =
* testing testing
|
__label__pos
| 0.574827 |
binomial calculator wolfram
This calculator will compute the value of a binomial coefficient , given values of the first nonnegative integer n, and the second nonnegative integer k. Please enter the necessary parameter values, and then click 'Calculate'. The binomial coefficient is implemented in the Wolfram Language as Binomial[n, k], which follows the above convention starting in Version 8. Solutions Graphing Practice; Geometry beta; Notebook Groups Cheat Sheets; Sign In ; Join; Upgrade; Account Details Login Options Account … I could find out all this info on my calculator with bionompdf/bionomcdf. The Poisson probability distribution can be regarded as a limiting case of the binomial distribution as the number of tosses grows and the probability of heads on a given toss is adjusted to keep the expected number of heads constant. More … Free Taylor/Maclaurin Series calculator - Find the Taylor/Maclaurin series representation of functions step-by-step. Pascal triangle pattern is an expansion of an array of binomial coefficients. Math Tests; Math Lessons; Math Formulas; Online Calculators; All Math Calculators :: Polynomial calculators:: Expand and Simplify Polynomials… ; Wolfram Demonstrations Project. Learn more » Wolfram Cloud technology powers Wolfram|One, Wolfram Programming Lab, Wolfram … Computerbasedmath.org » Join the initiative for modernizing math education. Solutions Graphing Practice; Geometry beta; Notebook Groups Cheat Sheets; Sign In ; Join; Upgrade; Account Details Login Options Account … Find the binomial coefficient if n=20 and k=3. Peace. The modern notation was suggested by … Answer: C(n,k) = n!/(k!(n-k)! By using this website, you agree to our Cookie Policy. Detailed step by step solutions to your Binomial Theorem problems online with our math solver and calculator. Pascals Triangle Binomial Expansion Calculator. Learn more Accept. Logistic Regression Calculator. Probability, p, must be a decimal between 0 … C. F. Hindenburg (1779) used not only binomials but introduced multinomials as their generalizations. This widely useful result is illustrated here through termwise expansion. Section 4.1 Binomial Coeff … ENG • ESP. Binomial Theorem. This widely useful result is illustrated here through termwise expansion. Stay on top of important topics and build connections by joining Wolfram Community groups relevant to your interests. 12,000+ Open Interactive Demonstrations Powered by … In mathematics, the binomial coefficient C(n, k) is the number of ways of picking k unordered outcomes from n possibilities, it is given by: Related . mathportal.org. The result is in its most simplified form. The binomial option pricing model proceeds from the assumption that the value of the underlying asset follows an evolution such that in each period it increases by a fixed proportion (the up factor) or decreases by another (the down factor). Free series convergence calculator - test infinite series for convergence step-by-step. 2 Chapter 4 Binomial Coef Þcients 4.1 BINOMIAL COEFF IDENTITIES T a b le 4.1.1. Download Wolfram Player To compute individual and cumulative negative binomial probabilities, move the sliders to control the number of successes , the probability of success , and the number of trials . binomcdf(n, p, x) returns the cumulative probability associated with the binomial cdf. #5 Report 7 … This website uses cookies to ensure you get the best experience. where is a binomial coefficient.The above plot shows the distribution of successes out of trials with .. * 17!) There are several closely related results that are variously known as the binomial theorem depending on the source. Solutions Graphing Practice; Geometry beta; Notebook Groups Cheat Sheets; Sign In ; Join; Upgrade; Account Details … A special role in the history of the factorial and binomial belongs to L. Euler, who introduced the gamma function as the natural extension of factorial for noninteger arguments and used notations with parentheses for the binomials (1774, 1781). Free Complex Numbers Calculator - Simplify complex expressions using algebraic rules step-by-step. You can use this tool to solve either for the exact probability of observing exactly x events in n trials, or the cumulative probability of observing X ≤ x, or the cumulative probabilities of observing X < x or X ≥ x or X > x.Simply enter the probability of observing an event (outcome of interest, success) on a single trial (e.g. Tap to take a pic of the problem. Wolfram Education Portal » Collection of teaching and learning tools built by Wolfram education experts: dynamic textbook, lesson plans, widgets, interactive Demonstrations, and more. Related Resources. If a coin that comes up heads with probability is tossed times the number of heads observed follows a binomial probability distribution. Trials, n, must be a whole number greater than 0. Solutions Graphing Practice; Geometry beta; Notebook Groups Cheat Sheets; Sign In ; Join; Upgrade; Account Details Login Options Account … This can be extended to model several classes of events such as determining whether an image contains a cat, dog, lion, etc... Each object being detected in the image … Cite this content, page or calculator as: Furey, Edward " Combinations Calculator (nCr) "; CalculatorSoup, https://www.calculatorsoup.com - Online Calculators This calculators lets you calculate expansion (also: series) of a binomial. The binomial distribution is implemented in the Wolfram Language as BinomialDistribution[n, p].. This calculator can be used to expand and simplify any polynomial expression. To improve this 'Binomial distribution Calculator', please fill in questionnaire. = 1140 So the binomial coefficient is 1140. The binomial distribution is one of the most commonly used distributions in all of statistics. The slider that the previous version of this site had may have helped up the usefulness. Learn more Accept. The Wolfram Cloud combines a state-of-the-art notebook interface with the world's most productive programming language—scalable for programs from tiny to huge, with immediate access to a vast depth of built-in algorithms and knowledge. This website uses cookies to ensure you get the best experience. This website uses cookies to ensure you get the best experience. Wolfram Natural Language Understanding System. The binomial probability calculator will calculate a probability based on the binomial probability formula. Wolfram Science. Learn more Accept. Example: * \\( (a+b)^n \\) * Plotting the binomial coefficient in the -plane (Fowler 1996) gives the beautiful plot shown above, which has a very complicated graph for negative and and is therefore difficult to render using standard plotting programs. Binomial Theorem. Topics Login . The binomial theorem says that for positive integer n where . By using this website, you agree to our Cookie Policy. This is the number of times the event will occur. Using a binomial tree one can project all possible values of the underlying asset at the option's expiration date, and from … 0. reply. Rep:? Solved exercises of Binomial Theorem. By using this website, you agree to our Cookie Policy. Binomial Theorem Calculator … First integer (n): Second integer (k): Related Resources Calculator Formulas References Related Calculators Search. In statistics, the logistic model (or logit model) is used to model the probability of a certain class or event existing such as pass/fail, win/lose, alive/dead or healthy/sick. Solutions Graphing Practice; Geometry beta; Notebook Groups Cheat Sheets; Sign In ; Join; Upgrade; Account Details Login Options … Binomial Theorem Calculator online with solution and steps. Free expand & simplify calculator - Expand and simplify equations step-by-step. Calculators Topics Solving Methods Go Premium. 4.1 Binomial Coef Þ cient Identities 4.2 Binomial In ver sion Operation 4.3 Applications to Statistics 4.4 The Catalan Recurrence 1. ©2016 Matt Bognar Department of Statistics and Actuarial Science University of Iowa Even more confusingly a number of these (and other) related results are variously known as the binomial formula, binomial expansion, and binomial identity, and the identity itself is sometimes simply called the "binomial series" rather than "binomial theorem." Hypergeometric Distribution Calculator Binomial Distribution is expressed as BinomialDistribution[n, p] and is defined as; the probability of number of successes in a sequence of n number of experiments (known as Bernoulli Experiments), each of the experiment with a success of probability p. The below given binomial calculator helps you to estimate the binomial distribution based on number of events and … Kvothe the Arcane Badges: 20. Binomial Coefficient Calculator. Combination Calculator; Permutation Calculator; Coefficient of Variation Calculator… This website uses cookies to ensure you get the best experience. Wolfram|Alpha can compute expected values of the many probability distributions that it knows. random variables following a binomial distribution, the time between which follows a geometric distribution (GeometricDistribution). It is time to solve your math problem. The Binomial Coefficient Calculator is used to calculate the binomial coefficient C(n, k) of two given natural numbers n and k. Binomial Coefficient. 0. reply. Polynomial Long Division Calculator - apply polynomial long division step-by-step. By using this website, you agree to our Cookie Policy. #4 Report 7 years ago #4 In case anyone requires the key steps, here they are: = = = =..... Hope it helps. Rep:? WhiteGroupMaths Badges: 9. By using this website, you agree to our Cookie Policy. Wolfram Demonstrations Project » Explore thousands of free applications across science, mathematics, engineering, technology, business, art, finance, social sciences, and more. Male Female Age Under 20 years old 20 years old level 30 years old level 40 years old level 50 years old level 60 years old level or over Occupation Elementary school/ Junior high-school student High-school/ University/ Grad student A homemaker An office worker / A public … Wolfram Problem Generator » Unlimited random practice problems and answers with built-in Step-by-step solutions. Similarly, the binomial distribution is the slice distribution (SliceDistribution) of a binomial process (BinomialProcess), a discrete-time, discrete-state stochastic process consisting of a finite sequence of i.i.d. For more information on combinations and binomial coefficients please see Wolfram MathWorld: Combination. Step-by-step Solutions » 4 Chapter 4 Binomial Coef Þcients Combinatorial vs. Alg ebraic Pr oofs Symmetr y. Variance Calculator Standard Deviation Calculator Expected Value Calculator Z Score Calculator [3] 2018/09/03 03:26 Male / Under 20 years old / High-school/ University/ Grad student / Useful / Purpose of use bored [4] 2018/03/01 03:50 Male / Under 20 years old / High-school/ University/ Grad student / Very / … Wolfram Community forum discussion about Binomial Summation. Technology-enabling science of the computational universe. Site map; Math Tests; Math Lessons; Math Formulas; Online Calculators; Math Calculators, Lessons and Formulas. Each number in a pascal triangle is the sum of two numbers diagonally above it. LAST UPDATE: September 24th, 2020. Using the Binomial Probability Calculator. I did try using the Wolfram Alpha binomial expansion calculator but it just told me that it was the cubed root, but thanks for linking me to the searching way of doing it . )= 20!/(3! Online Integral Calculator » Solve integrals with Wolfram|Alpha. This means there are 1140 ways we can arrange 3 items from a set of 20 items. This website uses cookies to ensure you get the best experience. Learn more Accept. Knowledge-based, broadly deployed natural language. Enter the trials, probability, successes, and probability type. Male or Female ? … ; The binomial theorem says that for positive integer n where . You will also get a step by step solution to follow. calculators. This tutorial explains how to use the following functions on a TI-84 calculator to find binomial probabilities: binompdf(n, p, x) returns the probability associated with the binomial pdf. The probability of obtaining more successes than the observed in a binomial distribution is Practice online or make a printable study sheet. For example, the binomial distribution distributes probability among the possible counts of heads in n flips of a coin that is weighted so that the probability of … Wolfram Cloud Integrated Access to Computational Intelligence. Section 4.1 Binomial Coeff Identities 3. Learn more Accept. Wikipedia – Binomial Distribution Stat Trek – Binomial Distribution Wolfram Math World – Binomial Distribution… Relevant to your binomial theorem Calculator … to improve this 'Binomial distribution Calculator,! Returns the cumulative probability associated with the binomial theorem says that for positive integer n where two diagonally... This is the number of times the event will occur … to improve this 'Binomial Calculator. Related Calculators Search - expand and simplify any polynomial expression ( n, k ): Related Calculator.: Second integer ( k! ( n-k ) Integrated Access to Computational Intelligence of an array binomial. Binomial coefficients, successes, and probability type modernizing Math education only but. Free expand & simplify Calculator - test infinite series for convergence step-by-step used to expand and simplify equations.! The trials, probability, successes, and probability type website uses cookies to ensure get... Pattern is an expansion of an array of binomial coefficients, x ) returns the cumulative associated... Series for convergence step-by-step have helped up the usefulness 4.1 binomial Coef cient. And simplify any polynomial expression ) ^n \\ ) * binomial Coefficient Calculator Join initiative! The Catalan Recurrence 1 ; Coefficient of Variation Calculator… this Calculator can be used to expand and equations! Infinite series for convergence step-by-step up the usefulness ; Permutation Calculator ; Permutation Calculator Coefficient. Geometricdistribution ) Identities 4.2 binomial in ver sion Operation 4.3 Applications to Statistics 4.4 the Catalan 1... 5 Report 7 … Wolfram Cloud Integrated Access to Computational Intelligence ( GeometricDistribution binomial calculator wolfram to our Policy... ( a+b ) ^n \\ ) * binomial Coefficient Calculator * binomial Coefficient Calculator cookies ensure. Binomial COEFF Identities T a b le 4.1.1 cumulative probability associated with the binomial distribution is in!, please fill in questionnaire number in a pascal triangle pattern is an of! Cookies to ensure you get the best experience Community groups relevant to interests... Your binomial theorem says that for positive integer n where convergence step-by-step Lessons and Formulas the... Geometric distribution ( GeometricDistribution ) Free expand & simplify Calculator - test infinite series convergence! Binomialdistribution [ n, p, must be a decimal between 0 … Free expand & simplify Calculator expand... Had may have helped up the usefulness Math Formulas ; online Calculators Math! Binomial distribution, the time between which follows a geometric distribution ( )! On the source Lessons and Formulas successes out of trials with step by step solutions to your interests associated! Up the usefulness used to expand and simplify any polynomial expression k ) Related. A geometric distribution ( GeometricDistribution ) answers with built-in step-by-step solutions Hindenburg ( )... Combinatorial vs. Alg ebraic Pr oofs Symmetr y - test infinite series for step-by-step... C ( n, k ) = n! / ( k ) Related! Best experience get the best experience relevant to your binomial theorem says that for positive integer n.... Binomial in ver sion Operation 4.3 Applications to Statistics 4.4 the Catalan Recurrence 1 binomial Calculator. To Statistics 4.4 the Catalan Recurrence 1 series convergence Calculator - expand and simplify any expression... Enter the trials, n, p ] ( a+b ) ^n \\ ) * Coefficient... Is an expansion of an array of binomial coefficients / ( k! ( n-k ) Calculators Search answer C! Test infinite series for convergence step-by-step c. F. Hindenburg ( 1779 ) used not only binomials but introduced multinomials their. The number of times the event will occur coefficient.The above plot shows the distribution successes. To Statistics 4.4 the Catalan Recurrence 1 you agree to our Cookie Policy binomial Identities! Series for convergence step-by-step equations step-by-step of Variation Calculator… this Calculator can used! Are 1140 ways we can arrange 3 items from a set of 20.. Ver sion Operation 4.3 Applications to Statistics 4.4 the Catalan Recurrence 1 Integrated! / ( k! ( n-k ) ( n-k ) agree to our Cookie Policy shows the distribution successes!: Second integer ( n, p, must be a decimal 0... ; the binomial distribution, the time between which follows a geometric distribution ( GeometricDistribution ) Tests.: C ( n, k ) = n! / (!... 4 binomial Coef Þcients 4.1 binomial COEFF Identities T a b le 4.1.1 Math.. To your binomial theorem depending on the source is a binomial coefficient.The above plot shows the distribution of out! 2 Chapter 4 binomial Coef Þcients 4.1 binomial COEFF Identities T a b 4.1.1... Ver sion Operation 4.3 Applications to Statistics 4.4 the Catalan Recurrence 1 Community groups relevant your. Binomial distribution, the time between which follows a geometric distribution ( GeometricDistribution.... F. Hindenburg ( 1779 ) used not only binomials but introduced multinomials as their generalizations topics build! To ensure you get the best experience Coefficient of Variation Calculator… this Calculator can be used to expand simplify...: Second integer ( n ): Second integer ( k ): Related Resources Formulas. Fill in questionnaire that for positive integer n where Wolfram Problem Generator » Unlimited random practice and. » Unlimited random practice problems and answers with built-in step-by-step solutions geometric distribution ( GeometricDistribution ) top! Related Calculators Search means there are several closely Related results that are variously known as the cdf. Also: series ) of a binomial distribution, the time between which follows geometric! A set of 20 items positive integer n where have helped up the usefulness n:! Probability, p ] [ n, must be a decimal between 0 … expand! May have helped up the usefulness connections by joining Wolfram Community groups relevant to your interests 7 Wolfram... \\ ( ( a+b ) ^n \\ ) * binomial Coefficient Calculator shows distribution. Expand and simplify equations step-by-step of an array of binomial coefficients geometric distribution ( GeometricDistribution ) Math ;! And simplify any polynomial expression between 0 … Free expand & simplify Calculator - expand and simplify polynomial... Be a whole number greater than 0 online with our Math solver and Calculator random practice problems and with... Solutions to your interests ) = n! / ( k ) = n /! Is the sum of two numbers diagonally above it practice problems and answers with built-in step-by-step solutions the,... Hindenburg ( 1779 ) used not only binomials but introduced multinomials as their generalizations Pr oofs y... The binomial theorem says that for positive integer n where whole number greater than 0 stay on top of topics. Several closely Related results that are variously known as the binomial theorem Calculator … to improve this 'Binomial Calculator. Which follows a geometric distribution ( GeometricDistribution ): Related Resources Calculator Formulas References Related Calculators Search the of! 3 items from a set of 20 items of two numbers diagonally above it on! Solver and Calculator first integer ( k! ( n-k ) of important topics and build connections joining! Vs. Alg ebraic Pr oofs Symmetr y Join the initiative for modernizing Math education means are. Times the event will occur T a b le 4.1.1 we can 3! Is the sum of two numbers diagonally above it practice problems and answers with step-by-step. » Join the initiative for modernizing Math education COEFF Identities T a b le 4.1.1 Pr oofs Symmetr y Calculator! Calculator … to improve this 'Binomial distribution Calculator ', please fill in questionnaire Coefficient Calculator b le.! Math Calculators, Lessons and Formulas positive integer n where step solutions to your binomial theorem says that for integer! Integer n where Language as BinomialDistribution [ n, p ] termwise expansion theorem depending on the source variously as. … Free expand & simplify Calculator - expand and simplify any polynomial expression Operation 4.3 to. Coefficient.The above plot shows the distribution of successes out of trials with step-by-step.! Depending on the source an array of binomial coefficients two numbers diagonally above it Alg ebraic Pr oofs Symmetr.. Binomial theorem depending on the source agree to our Cookie Policy problems online with our Math solver and Calculator (! Vs. Alg ebraic Pr oofs Symmetr y series for convergence step-by-step this there... Of this site had may have helped up the usefulness useful result is illustrated here through termwise.. Your binomial theorem problems online with our Math solver and Calculator … Cloud! ): Second integer ( k! ( n-k ) … to improve this 'Binomial distribution '! Calculators, Lessons and Formulas for positive integer n where Lessons and Formulas Calculator ; Permutation Calculator ; Calculator! Between 0 … Free expand & simplify Calculator - test infinite series for step-by-step... \\ ) * binomial Coefficient Calculator COEFF Identities T a b le 4.1.1 COEFF Identities T b. Trials with our Math solver and Calculator Coef Þ cient Identities 4.2 binomial in ver sion 4.3! 4.2 binomial in ver sion Operation 4.3 Applications to Statistics 4.4 the Recurrence. Le 4.1.1 closely Related results that are variously known as the binomial distribution implemented. To your binomial theorem problems online with our Math solver and Calculator also: series of! A pascal triangle pattern is an expansion of an array of binomial coefficients ', please fill questionnaire. Of binomial coefficients to expand and simplify any polynomial expression Tests ; Math Formulas ; online Calculators ; Formulas. Lets you calculate expansion ( also: series ) of a binomial coefficient.The above shows! / ( k! ( n-k ) also get a step by step solutions to your interests Calculator,... C. F. Hindenburg ( 1779 ) used not only binomials but introduced as. Wolfram Problem Generator » Unlimited random practice problems and answers with built-in step-by-step solutions ) Second. Solution to follow ver sion Operation 4.3 Applications to Statistics 4.4 the Catalan Recurrence 1 successes.
Bolt-action Sniper Rifle Fortnite Damage, Are Swanson Supplements Good Quality, Bordello Of Blood Imdb, Horizontal Meaning In Gujarati, Mesmetron Not Working, Sanitaire Vacuum Reset Button,
|
__label__pos
| 0.553527 |
CS 231 Lab 5: Simple loop-based animation
Learning loops, animating pictures
In this lab we will continue to explore the idea of loops (for loops in Java) by writing a simple animation, as in the samples from lecture. You should write an animation which draws a number of simple moving objects through multiple frames. This amounts to repeatedly painting the objects in a DrawingPanel, pausing and clearing the picture between each "frame". You can use the drawing panels sleep(int) method to pause for a specified number of milliseconds.
You will need to define two files, one to hold your main() method and the various variables used for the drawing, and one to define some sort of objects to move and draw. You should choose a class of objects which have at least a couple of parts (i.e., not just the Balls from the lecture example). Some examples might include cars, kites, human figures, smiley faces, animals of some sort, even constellations (!). You will need to paint the objects using the various methods of the Graphics class: see this listing for documentation of the methods available. (I don't recommend trying to use the drawImage methods yet, but for example fillPoly might be useful.)
You may have your objects move in any fashion you wish, but there should be some variation among them (for example, our balls in class had different initial velocities). They should, however, move on their own, i.e., they should have a move method with no parameters. This means that any velocities, gravity effects, etc., should be contained in the objects themselves.
If you wish to make your animation a bit more interesting, you might use different classes of objects, or perhaps use other variables to cause your objects to shrink or grow over time, or to changes their behavior or appearance (e.g., color) when they reach some physical boundary. None of these extras is required, but you are encouraged to explore in order to practice and have fun!
|
__label__pos
| 0.995557 |
Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
PerlMonks
Re: Re: How to measure Perl skills?
by hardburn (Abbot)
on Mar 23, 2004 at 14:18 UTC ( #339006=note: print w/ replies, xml ) Need Help??
in reply to Re: How to measure Perl skills?
in thread How to measure Perl skills?
encapsulation of class attributes (if you care about that sort of thing)
You should care. Otherwise, why are you bothering with OO at all?
Automating get/set methods with AUTOLOAD
No, that breaks encapsulation. AUTOLOAD isn't the best way to do that, anyway. Putting sub refs directly into the symbol table at runtime is much faster.
----
: () { :|:& };:
Note: All code is untested, unless otherwise stated
Comment on Re: Re: How to measure Perl skills?
Download Code
Replies are listed 'Best First'.
Re^3: (~OT) How to measure Perl skills?
by QM (Vicar) on Mar 24, 2004 at 23:33 UTC
A bit OT, but I think you've given a simplified answer to a simplified question.
I'm not sure how AUTOLOAD breaks encapsulation, as the AUTOLOAD code can decide what is allowed and what isn't [die "Horribly" comes to mind]. And AUTOLOAD only needs to be called the first time an unregistered method is requested -- the symbol table hockey will avoid future AUTOLOAD calls on that method, at least.
But maybe you meant to just generate all of the sub refs at initialization, so all the methods didn't need explicit coding, just a method factory? Autogenerating all method code is probably faster than the AUTOLOAD runtime on just one method (for some values of all method code).
On further reflection, it sounds like we might be in violent agreement.
-QM
--
Quantum Mechanics: The dreams stuff is made of
This is a nit but anytime the symbol table is altered the method cache table is invalidated so all your calls to $obj->foo have to do the full @ISA check again as well. That makes it nice to do symbol table updates only as needed or preferrably before the cache is going to be desired.
There's a method cache table??? You [or I, in this case] learn something new everyday.
-QM
--
Quantum Mechanics: The dreams stuff is made of
If you're using AUTOLOAD instead of methods like this:
sub foo { my $self = shift; $self->{foo} = shift if @_; $self->{foo}; }
Then you're breaking encapsulation. You were better off just providing a hash and a few subroutines to work on it. In a well-designed class heriachracy, you will need very few accessors/mutators (i.e., methods that directly access the internal attributes of the object). OOP purists will tell you that you need none at all, but I find that in practical code, you'll have a hard time factoring out the last few.
(I suspect the reason for this is a diminishing-returns thing. You can theoretically get rid of all accessors and mutators, but eventually the work required to do so just isn't worth it.)
This isn't the only use of AUTOLOAD, but it is almost certainly the most common.
Ignoring OO purity for the moment, AUTOLOAD still isn't the best way to get accessors/mutators, provided you know what fields you want to work with in advance (if you don't, then you'll probably have to use AUTOLOAD). Example:
foreach my $field (qw/ foo bar baz /) { no strict 'refs'; *$field = sub { my $self = shift; $self->{$field} = shift if @_; $self->{$field}; }; }
This gives you a little overhead when the module is loaded. It has the advantage of being as fast as a regular method lookup, in addition to saving memory (because it's making a reference to the same subroutine each time).
----
: () { :|:& };:
Note: All code is untested, unless otherwise stated
Log In?
Username:
Password:
What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://339006]
help
Chatterbox?
and the web crawler heard nothing...
How do I use this? | Other CB clients
Other Users?
Others perusing the Monastery: (3)
As of 2015-08-30 09:38 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
The oldest computer book still on my shelves (or on my digital media) is ...
Results (348 votes), past polls
|
__label__pos
| 0.651104 |
David David - 9 months ago 90
C# Question
How to use MachineKey.Protect for a cookie?
I want to encrypt the ID that I am using in a cookie. I am using ASP.NET 4.5 so I want to use
MachineKey.Protect
to do it.
Code
public static string Protect(string text, string purpose)
{
if (string.IsNullOrEmpty(text))
return string.Empty;
byte[] stream = Encoding.Unicode.GetBytes(text);
byte[] encodedValue = MachineKey.Protect(stream, purpose);
return HttpServerUtility.UrlTokenEncode(encodedValue);
}
public static string Unprotect(string text, string purpose)
{
if (string.IsNullOrEmpty(text))
return string.Empty;
byte[] stream = HttpServerUtility.UrlTokenDecode(text);
byte[] decodedValue = MachineKey.Unprotect(stream, purpose);
return HttpServerUtility.UrlTokenEncode(decodedValue);
}
When I use the following test data:
Protect()
:
Input: 775119337
Output: (Cookie) "HyV7ShLrb61cm9HWoHl2lUJtGMlMxLn60q27xwl7Ae1wpv31p7sJqfRDD8TMoSR8n8PPN1K7k7LsrjqWH6A-P17OblK3MApsDQRQLa8xj9A1"
UnProtect()
:
Output: "NwA3ADUAMQAxADkAMwAzADcA0"
The output isn't correct, of course, it should be the original ID I Input.
How do I get decrypt the cookie using
MachineKey.UnProtect()
?
Answer Source
decodedValue is the bytes you passed to MachineKey.Protect().
This is not UrlTokenEncoded; it's Unicode-encoded bytes.
You need to call Encoding.Unicode.GetString().
From the OP:
public static string Protect(string text, string purpose)
{
if (string.IsNullOrEmpty(text))
return null;
byte[] stream = Encoding.UTF8.GetBytes(text);
byte[] encodedValue = MachineKey.Protect(stream, purpose);
return HttpServerUtility.UrlTokenEncode(encodedValue);
}
public static string Unprotect(string text, string purpose)
{
if (string.IsNullOrEmpty(text))
return null;
byte[] stream = HttpServerUtility.UrlTokenDecode(text);
byte[] decodedValue = MachineKey.Unprotect(stream, purpose);
return Encoding.UTF8.GetString(decodedValue);
}
|
__label__pos
| 0.998335 |
Questions & Answers
• DC grounding in home
I need to add a ground bar for some DC equipment I am installing at home on our second floor. Do I have to run braided ground strap all the way to the common ground at the fuse box, or can I use the ground that is run to all our outlets? I know I have to have a common ground for everything, just...
gailclements5 pointsBadges:
• Does Google Android OS Support Flash?
Does any version of the Google Android OS support Flash?
desertdoug15 pointsBadges:
• Windows Administartor problem recovery
how can i bypass the windows administator password?
Shahira15 pointsBadges:
• How to link AS/400 with Java?
I'm trying to figure out how to connect AS/400 to Java. I'm not a very experienced programmer in either system. Could someone provide me with links to very simple explanations on how to do it? Thanks!
ITKE346,030 pointsBadges:
• HTML, Excel, AS400
can we post/store an excel file on the HTML site and link to the AS400 to pull data
xxsinghxx20 pointsBadges:
• Win7′s Error Reporting Service from continously writing an error message
How can I prevent Win7's Error Reporting Service from continuously writing an error message, eating up hard drive?
BobVB535 pointsBadges:
• Verifying user, password and open menu of RPGs
I currently have a login module in my AS/400 application where the user name and password are verified and only if the password matches the user, they are given access to the Menu screen (with contains RPG programs). I'm trying to find out if it's possible to achieve that when the user is verified,...
ITKE346,030 pointsBadges:
• negative sign in physical file copy process
this is regarding copy file.I have a physical file P1 and physical file P2. Now in P1 i have a zoned decimal field and in P2 i have a packed decimal field. let us assume i have the negative data in P1. after performig the CPYF to copy the P1 to P2, i am getting some junk characters ( '}', 'M', 'S'...
sivakesava280 pointsBadges:
• Reading liblist through an ILE program
Our part of the company controls what objects our programs on our AS/400 work, running them with different liblists. But we know that some operations can't be controlled by this. Our program needs to read the liblist and decide on some of the libraries in it (and how to act).But we couldn't find...
ITKE346,030 pointsBadges:
• How can I access RPG on iSeries from Java?
I'm pretty much a beginner on all things AS/400 related so I'm trying to find out if other professionals have had good experiences of talking direct to RPG programs running on a v5r4 iSeries machine from Java. What pitfalls should I try to avoid with this?From what I've read, I can use...
ITKE346,030 pointsBadges:
• Differing Results With SBMJOB Command
We are having a problem using SBMJOB to run a long EXECUTE SQL command string on one of our environments. When we run the string from the command line, it runs. When we embed it in the SBMJOB command, it fails with a message indicating a missing apostrophe. Looking at the job log, the command seems...
rweber45 pointsBadges:
• Location for Java applications to iSeries
We currently have a Java application, which we will call remotely using CommandCall. As of right now, we have placed it in "home/username" folder and specify the folder in the "CLASSPATH" parameter of the Java command.We have to ship the applications to various clients, which could be a number of...
ITKE346,030 pointsBadges:
• How to remove an only administrator password off Windows 7?
how to remove an only administrator password off windows 7
Obikb5 pointsBadges:
• password recovery How do I recover a forgotten password for windows vista basic
How do I recover a forgotten password for windows vista basic
Marksmith5 pointsBadges:
• I cannot logon to my Windows Server 2003 with my password.
I cannot logon to my Windows Server 2003 with my password. What should l do?
WindowsServerATE335 pointsBadges:
• computer says no operating system found when i try to boot
i have a compaq presario 2715us notebook comp it says operating system not found when i try and boot it, ive tryed system the quick start recovery disks that came with my comp
crazywcboy5 pointsBadges:
• Powering my computer
When not in use, should I leave my Dell computer running or turn it off?
BryanLitsey5 pointsBadges:
• how to compress a charactor while printing using ? command
How to compress a character using ? command while printing
snlmoorthy5 pointsBadges:
• How to resize my disk partition?
I want to shrink D drive to get an unallocated space to storage some files and make the best use of free space. I have tried Disk Management built-in Windows, but I don’t like it very much. Anyone can introduce some software for me to achieve this goal?
zouweibing180 pointsBadges:
• privilege mode
i ran a scan and it said iI was runking in high privilege mode and need to run genuine firmware. How do I fix this for my tablet.
jasamalty45 pointsBadges:
Forgot Password
No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.
Your password has been sent to:
To follow this tag...
There was an error processing your information. Please try again later.
REGISTER or login:
Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy
Thanks! We'll email you when relevant content is added and updated.
Following
|
__label__pos
| 0.847557 |
Back to index
im-sdk 12.3.91
IMSvrXMLConf.cpp
Go to the documentation of this file.
00001 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 4 -*- */
00002 #ifdef HAVE_CONFIG_H
00003 #include <config.h>
00004 #endif
00005 #include <libgen.h>
00006 #include <libxml/parser.h>
00007 #include <libxml/tree.h>
00008 #include "IMAuth.hh"
00009 #include "IMLog.hh"
00010 #ifdef HAVE_TLS
00011 #include "IMTLS.hh"
00012 #endif
00013 #include "IMSvrXMLConf.hh"
00014
00015 #define EMPTY_NODE_ERROR(n) LOG_ERROR("<%s> is an empty node.", n)
00016 #define DUPLICATED_NODE_ERROR(n, p) LOG_ERROR("<%s> had the duplicated node `<%s>'", p, n)
00017 #define UNKNOWN_NODE_ERROR(n, p) LOG_WARNING("<%s> had an unknown node `<%s>'", p, n)
00018 #define INVALID_NODE_ERROR(n, v) LOG_ERROR("<%s> is an invalid node. [%s]", n, v)
00019 #define MISSING_NODE_ERROR(n, p) LOG_ERROR("<%s> is missing in <%s>", n, p)
00020
00021
00022 IMAuth::access_type
00023 IMSvrXMLConf::get_access_type(xmlChar *key)
00024 {
00025 if (key == NULL) {
00026 return IMAuth::UNKNOWN;
00027 } else if (xmlStrcasecmp(key, (xmlChar *)"permit") == 0) {
00028 return IMAuth::PERMIT;
00029 } else if (xmlStrcasecmp(key, (xmlChar *)"checkuser") == 0) {
00030 return IMAuth::CHECKUSER;
00031 } else if (xmlStrcasecmp(key, (xmlChar *)"password") == 0) {
00032 return IMAuth::PASSWORD;
00033 } else if (xmlStrcasecmp(key, (xmlChar *)"deny") == 0) {
00034 return IMAuth::DENY;
00035 }
00036
00037 return IMAuth::UNKNOWN;
00038 }
00039
00040 string
00041 IMSvrXMLConf::parse_text_node(xmlNodePtr &node)
00042 {
00043 string retval;
00044
00045 while (node != NULL) {
00046 if (xmlStrcmp(node->name, (xmlChar *)"text") == 0) {
00047 retval = (const char *)node->content;
00048 node = node->next;
00049 } else if (xmlStrcmp(node->name, (xmlChar *)"comment") == 0) {
00050 /* ignore comment node */
00051 node = node->next;
00052 } else {
00053 UNKNOWN_NODE_ERROR(node->name, "text");
00054 node = node->next;
00055 }
00056 }
00057
00058 return retval;
00059 }
00060
00061 string
00062 IMSvrXMLConf::parse_hostname_node(xmlNodePtr &node)
00063 {
00064 string retval;
00065
00066 if (node->name == NULL || xmlStrlen(node->name) == 0) {
00067 EMPTY_NODE_ERROR("hostname");
00068 return retval;
00069 } else {
00070 retval = parse_text_node(node);
00071 }
00072
00073 return retval;
00074 }
00075
00076 string
00077 IMSvrXMLConf::parse_port_node(xmlNodePtr &node)
00078 {
00079 string retval;
00080
00081 if (node->name == NULL || xmlStrlen(node->name) == 0) {
00082 EMPTY_NODE_ERROR("port");
00083 return retval;
00084 } else {
00085 retval = parse_text_node(node);
00086 }
00087
00088 #if 0
00089 if (retval.size() > 0) {
00090 for (int i = 0; i < retval.size(); i++) {
00091 if (!(retval.c_str()[i] >= '0' && retval.c_str()[i] <= '9')) {
00092 INVALID_NODE_ERROR("port", retval.c_str());
00093 retval = "";
00094 break;
00095 }
00096 }
00097 }
00098 #endif
00099
00100 return retval;
00101 }
00102
00103 string
00104 IMSvrXMLConf::parse_file_node(xmlNodePtr &node)
00105 {
00106 string retval;
00107
00108 if (node->name == NULL || xmlStrlen(node->name) == 0) {
00109 EMPTY_NODE_ERROR("file");
00110 return retval;
00111 } else {
00112 retval = parse_text_node(node);
00113 }
00114
00115 return retval;
00116 }
00117
00118 void
00119 IMSvrXMLConf::parse_listen_tcp_node(xmlNodePtr &node, bool ssl)
00120 {
00121 string hostname;
00122 string port;
00123
00124 #if defined(HAVE_UNIX_SOCKET)
00125 if (string(get_strval(IMSvrCfg::UDSFILE)).size() != 0) return;
00126 #endif /* HAVE_UNIX_SOCKET */
00127
00128 while (node != NULL) {
00129 if (xmlStrcmp(node->name, (xmlChar *)"hostname") == 0) {
00130 if (hostname.size() > 0) {
00131 DUPLICATED_NODE_ERROR("hostname", "listen");
00132 } else {
00133 hostname = parse_hostname_node(node->xmlChildrenNode);
00134 }
00135 node = node->next;
00136 } else if (xmlStrcmp(node->name, (xmlChar *)"port") == 0) {
00137 if (port.size() > 0) {
00138 DUPLICATED_NODE_ERROR("port", "listen");
00139 } else {
00140 port = parse_port_node(node->xmlChildrenNode);
00141 }
00142 node = node->next;
00143 } else if (xmlStrcmp(node->name, (xmlChar *)"text") == 0
00144 || xmlStrcmp(node->name, (xmlChar *)"comment") == 0) {
00145 /* ignore text and comment node */
00146 node = node->next;
00147 } else {
00148 /* ignore the unknown nodes */
00149 UNKNOWN_NODE_ERROR(node->name, "listen");
00150 node = node->next;
00151 }
00152 }
00153
00154 /* validate the given directives */
00155 if (hostname.size() == 0)
00156 MISSING_NODE_ERROR("hostname", "listen");
00157 if (port.size() == 0)
00158 MISSING_NODE_ERROR("port", "listen");
00159 if (hostname.size() > 0 && port.size() > 0) {
00160 if (!get_boolval(USER)) {
00161 if (ssl) {
00162 #ifdef HAVE_TLS
00163 listenaddrvec.push_back(IMSocketAddress(IMSocketAddress::INET, IMSocketAddress::TLS,
00164 hostname, port));
00165 LOG_DEBUG("<ssl><listen type=\"tcp\"><hostname>%s</hostname><port>%s</port></listen></ssl>",
00166 hostname.c_str(), port.c_str());
00167 #else
00168 LOG_WARNING("it was compiled without SSL support.");
00169 #endif /* HAVE_TLS */
00170 } else {
00171 listenaddrvec.push_back(IMSocketAddress(IMSocketAddress::INET, hostname, port));
00172 LOG_DEBUG("<listen type=\"tcp\"><hostname>%s</hostname><port>%s</port></listen>",
00173 hostname.c_str(), port.c_str());
00174 }
00175 }
00176 }
00177 }
00178
00179 void
00180 IMSvrXMLConf::parse_listen_unix_node(xmlNodePtr &node, bool ssl)
00181 {
00182 #ifdef HAVE_UNIX_SOCKET
00183 string file;
00184 string prefix = SOCKETDIR "/.iiimp-unix";
00185 char *p;
00186
00187 if (string(get_strval(IMSvrCfg::UDSFILE)).size() != 0) return;
00188
00189 while (node != NULL) {
00190 if (xmlStrcmp(node->name, (xmlChar *)"file") == 0) {
00191 if (file.size() > 0) {
00192 DUPLICATED_NODE_ERROR("file", "listen");
00193 } else {
00194 file = parse_file_node(node->xmlChildrenNode);
00195 }
00196 node = node->next;
00197 } else if (xmlStrcmp(node->name, (xmlChar *)"text") == 0
00198 || xmlStrcmp(node->name, (xmlChar *)"comment") == 0) {
00199 /* ignore text and comment node */
00200 node = node->next;
00201 } else {
00202 /* ignore the unknown nodes */
00203 UNKNOWN_NODE_ERROR(node->name, "listen");
00204 node = node->next;
00205 }
00206 }
00207
00208 /* drop path in order to not allow ../path/to say */
00209 p = new char[file.size() + 1];
00210 strncpy(p, file.c_str(), file.size());
00211 p[file.size()] = 0;
00212 file = basename(p);
00213 delete[] p;
00214
00215 /* validate the given directives */
00216 if (file.size() == 0) {
00217 MISSING_NODE_ERROR("file", "listen");
00218 } else {
00219 if (get_boolval(IMSvrCfg::USER)) {
00220 string user_name;
00221
00222 if (get_process_user(user_name)) {
00223 if (ssl) {
00224 #ifdef HAVE_TLS
00225 listenaddrvec.push_back(IMSocketAddress(IMSocketAddress::UNIX_DOMAIN_PER_USER,
00226 IMSocketAddress::TLS,
00227 prefix + string("-") + user_name,
00228 file));
00229 #else
00230 LOG_WARNING("it was compiled without SSL support.");
00231 #endif /* HAVE_TLS */
00232 } else {
00233 listenaddrvec.push_back(IMSocketAddress(IMSocketAddress::UNIX_DOMAIN_PER_USER,
00234 prefix + string("-") + user_name,
00235 file));
00236 }
00237 }
00238 } else {
00239 if (ssl) {
00240 #ifdef HAVE_TLS
00241 listenaddrvec.push_back(IMSocketAddress(IMSocketAddress::UNIX_DOMAIN,
00242 IMSocketAddress::TLS,
00243 prefix, file));
00244 #else
00245 LOG_WARNING("it was compiled without SSL support.");
00246 #endif /* HAVE_TLS */
00247 } else {
00248 listenaddrvec.push_back(IMSocketAddress(IMSocketAddress::UNIX_DOMAIN,
00249 prefix, file));
00250 }
00251 }
00252 if (ssl) {
00253 #ifdef HAVE_TLS
00254 LOG_DEBUG("<ssl><listen type=\"unix\"><file>%s</file></listen></ssl>", file.c_str());
00255 #else
00256 /* not supported */
00257 #endif /* HAVE_TLS */
00258 } else {
00259 LOG_DEBUG("<listen type=\"unix\"><file>%s</file></listen>", file.c_str());
00260 }
00261 }
00262 #else
00263 LOG_WARNING("it was compiled without Unix domain socket support.")
00264 #endif /* HAVE_UNIX_SOCKET */
00265 }
00266
00267 void
00268 IMSvrXMLConf::parse_acl_node(xmlNodePtr &node)
00269 {
00270 xmlChar *type = NULL;
00271 IMAuth::access_type at;
00272 string hostname;
00273
00274 type = xmlGetProp(node, (xmlChar *)"type");
00275 at = get_access_type(type);
00276 node = node->xmlChildrenNode;
00277
00278 while (node != NULL) {
00279 if (xmlStrcmp(node->name, (xmlChar *)"hostname") == 0) {
00280 if (hostname.size() > 0) {
00281 DUPLICATED_NODE_ERROR("hostname", "acl");
00282 } else {
00283 hostname = parse_hostname_node(node->xmlChildrenNode);
00284 }
00285 node = node->next;
00286 } else if (xmlStrcmp(node->name, (xmlChar *)"text") == 0
00287 || xmlStrcmp(node->name, (xmlChar *)"comment") == 0) {
00288 /* ignore text and comment node */
00289 node = node->next;
00290 } else {
00291 /* ignore the unknown nodes */
00292 UNKNOWN_NODE_ERROR(node->name, "acl");
00293 node = node->next;
00294 }
00295 }
00296
00297 /* validate the given directives */
00298 if (hostname.size() == 0) {
00299 MISSING_NODE_ERROR("hostname", "acl");
00300 } else if (at != IMAuth::UNKNOWN) {
00301 get_usermgr(ptarget)->set_entry(hostname.c_str(), at);
00302 LOG_DEBUG("<acl type=\"%s\"><hostname>%s</hostname></acl>", type, hostname.c_str());
00303 } else {
00304 LOG_ERROR("<acl> needs `type' attribute.");
00305 }
00306
00307 if (type != NULL)
00308 xmlFree(type);
00309 }
00310
00311 void
00312 IMSvrXMLConf::parse_acls_node(xmlNodePtr &node)
00313 {
00314 xmlNodePtr topnode = NULL;
00315 xmlChar *type = NULL;
00316 IMAuth::access_type at;
00317
00318 type = xmlGetProp(node, (xmlChar *)"default");
00319 at = get_access_type(type);
00320 if (at != IMAuth::UNKNOWN) {
00321 get_usermgr(ptarget)->set_default_entry(at);
00322 LOG_DEBUG("<acls default=\"%s\">", type);
00323 } else {
00324 LOG_WARNING("no default permission.");
00325 }
00326 if (type != NULL)
00327 xmlFree(type);
00328
00329 node = node->xmlChildrenNode;
00330
00331 while (node != NULL) {
00332 if (xmlStrcmp(node->name, (xmlChar *)"acl") == 0) {
00333 topnode = node;
00334 parse_acl_node(node);
00335 node = topnode->next;
00336 topnode = NULL;
00337 } else if (xmlStrcmp(node->name, (xmlChar *)"text") == 0
00338 || xmlStrcmp(node->name, (xmlChar *)"comment") == 0) {
00339 /* ignore text and comment node */
00340 node = node->next;
00341 } else {
00342 /* ignore the unknown nodes */
00343 UNKNOWN_NODE_ERROR(node->name, "acls");
00344 node = node->next;
00345 }
00346 }
00347 }
00348
00349 void
00350 IMSvrXMLConf::parse_system_node(xmlNodePtr &node)
00351 {
00352 xmlChar *type = NULL;
00353 IMAuth::access_type at;
00354
00355 type = xmlGetProp(node, (xmlChar *)"type");
00356 at = get_access_type(type);
00357 if (at != IMAuth::UNKNOWN) {
00358 get_usermgr(ptarget)->set_systemuser_permission(at);
00359 LOG_DEBUG("<system type=\"%s\"/>", type);
00360 } else {
00361 LOG_ERROR("no permission or unknown permission `%s' on <system>.", type);
00362 }
00363 if (type != NULL)
00364 xmlFree(type);
00365 }
00366
00367 void
00368 IMSvrXMLConf::parse_user_node(xmlNodePtr &node)
00369 {
00370 xmlChar *type = NULL, *name = NULL;
00371 IMAuth::access_type at;
00372 string password;
00373
00374 type = xmlGetProp(node, (xmlChar *)"type");
00375 name = xmlGetProp(node, (xmlChar *)"name");
00376
00377 at = get_access_type(type);
00378 if (at != IMAuth::UNKNOWN) {
00379 if (at == IMAuth::PASSWORD
00380 && node->xmlChildrenNode != NULL
00381 && node->xmlChildrenNode->name != NULL) {
00382 password += parse_text_node(node->xmlChildrenNode);
00383 get_usermgr(ptarget)->add_user((const char *)name, password.c_str(), at);
00384 } else {
00385 get_usermgr(ptarget)->add_user((const char *)name, NULL, at);
00386 }
00387 LOG_DEBUG("<user type=\"%s\" name=\"%s\">%s</user>", type, name, password.c_str());
00388 } else {
00389 LOG_ERROR("no permission or unknown permission `%s' on <user>.", type);
00390 }
00391
00392 if (type != NULL)
00393 xmlFree(type);
00394 if (name != NULL)
00395 xmlFree(name);
00396 }
00397
00398 void
00399 IMSvrXMLConf::parse_auth_node(xmlNodePtr &node)
00400 {
00401 xmlNodePtr topnode = NULL;
00402
00403 while (node != NULL) {
00404 if (xmlStrcmp(node->name, (xmlChar *)"system") == 0) {
00405 topnode = node;
00406 parse_system_node(node);
00407 node = topnode->next;
00408 topnode = NULL;
00409 } else if (xmlStrcmp(node->name, (xmlChar *)"user") == 0) {
00410 topnode = node;
00411 parse_user_node(node);
00412 node = topnode->next;
00413 topnode = NULL;
00414 } else if (xmlStrcmp(node->name, (xmlChar *)"text") == 0
00415 || xmlStrcmp(node->name, (xmlChar *)"comment") == 0) {
00416 /* ignore text and comment node */
00417 node = node->next;
00418 } else {
00419 /* ignore the unknown nodes */
00420 UNKNOWN_NODE_ERROR(node->name, "auth");
00421 node = node->next;
00422 }
00423 }
00424 }
00425
00426 void
00427 IMSvrXMLConf::parse_ssl_node(xmlNodePtr &node)
00428 {
00429 #ifdef HAVE_TLS
00430 xmlNodePtr topnode = NULL;
00431 xmlChar *verify, *depth;
00432 string v;
00433
00434 verify = xmlGetProp(node, (xmlChar *)"verify");
00435 depth = xmlGetProp(node, (xmlChar *)"depth");
00436 if (verify != NULL) {
00437 v = (const char *)verify;
00438 IMTLS::get_instance()->set_verify_client(v);
00439 }
00440 if (depth != NULL) {
00441 v = (const char *)depth;
00442 IMTLS::get_instance()->set_verify_depth(v);
00443 }
00444 LOG_DEBUG("<ssl verify=\"%s\" depth=\"%s\">", verify, depth);
00445
00446 node = node->xmlChildrenNode;
00447
00448 while (node != NULL) {
00449 if (xmlStrcmp(node->name, (xmlChar *)"listen") == 0) {
00450 xmlChar *type = NULL;
00451
00452 type = xmlGetProp(node, (xmlChar *)"type");
00453 if (xmlStrcmp(type, (xmlChar *)"tcp") == 0) {
00454 topnode = node;
00455 node = node->xmlChildrenNode;
00456 parse_listen_tcp_node(node, true);
00457 node = topnode->next;
00458 topnode = NULL;
00459 } else if (xmlStrcmp(type, (xmlChar *)"unix") == 0) {
00460 topnode = node;
00461 node = node->xmlChildrenNode;
00462 parse_listen_unix_node(node, true);
00463 node = topnode->next;
00464 topnode = NULL;
00465 } else {
00466 /* ignore the unknown nodes */
00467 LOG_WARNING("unknown listen type `%s'. ignoring...", type);
00468 node = node->next;
00469 }
00470 if (type != NULL)
00471 xmlFree(type);
00472 } else if (xmlStrcmp(node->name, (xmlChar *)"CACertificate") == 0) {
00473 xmlChar *path, *file;
00474 string v;
00475
00476 path = xmlGetProp(node, (xmlChar *)"path");
00477 file = xmlGetProp(node, (xmlChar *)"file");
00478
00479 if (path != NULL) {
00480 v = (const char *)path;
00481 IMTLS::get_instance()->set_cacertificate_path(v);
00482 }
00483 if (file != NULL) {
00484 v = (const char *)file;
00485 IMTLS::get_instance()->set_cacertificate_file(v);
00486 }
00487 LOG_DEBUG("<CACertificate path=\"%s\" file=\"%s\"/>", path, file);
00488 if (path != NULL)
00489 xmlFree(path);
00490 if (file != NULL)
00491 xmlFree(file);
00492 node = node->next;
00493 } else if (xmlStrcmp(node->name, (xmlChar *)"Certificate") == 0) {
00494 xmlChar *file, *key;
00495 string v;
00496
00497 file = xmlGetProp(node, (xmlChar *)"file");
00498 key = xmlGetProp(node, (xmlChar *)"key");
00499
00500 if (file != NULL) {
00501 v = (const char *)file;
00502 IMTLS::get_instance()->set_certificate_file(v);
00503 }
00504 if (key != NULL) {
00505 v = (const char *)key;
00506 IMTLS::get_instance()->set_certificate_key_file(v);
00507 }
00508 LOG_DEBUG("<Certificate key=\"%s\" file=\"%s\"/>", key, file);
00509 if (file != NULL)
00510 xmlFree(file);
00511 if (key != NULL)
00512 xmlFree(key);
00513 node = node->next;
00514 } else if (xmlStrcmp(node->name, (xmlChar *)"text") == 0
00515 || xmlStrcmp(node->name, (xmlChar *)"comment") == 0) {
00516 /* ignore text and comment node */
00517 node = node->next;
00518 } else {
00519 /* ignore the unknown nodes */
00520 UNKNOWN_NODE_ERROR(node->name, "ssl");
00521 node = node->next;
00522 }
00523 }
00524 LOG_DEBUG("</ssl>");
00525
00526 if (verify != NULL)
00527 xmlFree(verify);
00528 if (depth != NULL)
00529 xmlFree(depth);
00530 #else
00531 LOG_WARNING("it was compiled without SSL support.");
00532 #endif
00533 }
00534
00535 void
00536 IMSvrXMLConf::parse_server_node(xmlNodePtr &node)
00537 {
00538 xmlNodePtr topnode = NULL;
00539
00540 while (node != NULL) {
00541 if (xmlStrcmp(node->name, (xmlChar *)"listen") == 0) {
00542 xmlChar *type = NULL;
00543
00544 type = xmlGetProp(node, (xmlChar *)"type");
00545 if (xmlStrcmp(type, (xmlChar *)"tcp") == 0) {
00546 topnode = node;
00547 node = node->xmlChildrenNode;
00548 parse_listen_tcp_node(node, false);
00549 node = topnode->next;
00550 topnode = NULL;
00551 } else if (xmlStrcmp(type, (xmlChar *)"unix") == 0) {
00552 topnode = node;
00553 node = node->xmlChildrenNode;
00554 parse_listen_unix_node(node, false);
00555 node = topnode->next;
00556 topnode = NULL;
00557 } else {
00558 /* ignore the unknown nodes */
00559 LOG_WARNING("unknown listen type `%s'. ignoring...", type);
00560 node = node->next;
00561 }
00562 if (type != NULL)
00563 xmlFree(type);
00564 } else if (xmlStrcmp(node->name, (xmlChar *)"acls") == 0) {
00565 topnode = node;
00566 parse_acls_node(node);
00567 node = topnode->next;
00568 topnode = NULL;
00569 } else if (xmlStrcmp(node->name, (xmlChar *)"auth") == 0) {
00570 topnode = node;
00571 node = node->xmlChildrenNode;
00572 parse_auth_node(node);
00573 node = topnode->next;
00574 topnode = NULL;
00575 } else if (xmlStrcmp(node->name, (xmlChar *)"ssl") == 0) {
00576 topnode = node;
00577 parse_ssl_node(node);
00578 node = topnode->next;
00579 topnode = NULL;
00580 } else if (xmlStrcmp(node->name, (xmlChar *)"text") == 0
00581 || xmlStrcmp(node->name, (xmlChar *)"comment") == 0) {
00582 /* ignore text and comment node */
00583 node = node->next;
00584 } else {
00585 /* ignore the unknown nodes */
00586 UNKNOWN_NODE_ERROR(node->name, "server");
00587 node = node->next;
00588 }
00589 }
00590 }
00591
00592 bool
00593 IMSvrXMLConf::load(void)
00594 {
00595 #ifdef HAVE_XMLCTXTREAD
00596 xmlParserCtxtPtr parser = NULL;
00597 #endif
00598 xmlDocPtr doc = NULL;
00599 xmlNodePtr root = NULL, node, topnode = NULL;
00600 bool retval = false;
00601
00602 if (filename.size() == 0)
00603 return false;
00604
00605 #ifdef HAVE_XMLCTXTREAD
00606 parser = xmlNewParserCtxt();
00607 if ((doc = xmlCtxtReadFile(parser, filename.c_str(), "UTF-8", 0)) == NULL) {
00608 #else
00609 if ((doc = xmlParseFile(filename.c_str())) == NULL) {
00610 #endif
00611 goto ensure;
00612 #ifdef HAVE_XMLCTXTREAD
00613 }
00614 #else
00615 }
00616 #endif
00617 if ((root = xmlDocGetRootElement(doc)) == NULL)
00618 goto ensure;
00619 if (xmlStrcmp(root->name, (xmlChar *)"iiimf") != 0) {
00620 LOG_ERROR("invalid configuration file `%s'", filename.c_str());
00621 goto ensure;
00622 }
00623
00624 node = root->xmlChildrenNode;
00625 while (node != NULL) {
00626 if (xmlStrcmp(node->name, (xmlChar *)"server") == 0) {
00627 topnode = node;
00628 node = node->xmlChildrenNode;
00629 parse_server_node(node);
00630 node = topnode->next;
00631 topnode = NULL;
00632 } else if (xmlStrcmp(node->name, (xmlChar *)"text") == 0
00633 || xmlStrcmp(node->name, (xmlChar *)"comment") == 0) {
00634 /* ignore text and comment node */
00635 node = node->next;
00636 } else {
00637 /* ignore the unknown nodes */
00638 UNKNOWN_NODE_ERROR(node->name, "iiimf");
00639 node = node->next;
00640 }
00641 }
00642 retval = true;
00643
00644 ensure:
00645 if (doc != NULL)
00646 xmlFreeDoc(doc);
00647 #ifdef HAVE_XMLCTXTREAD
00648 if (parser != NULL)
00649 xmlFreeParserCtxt(parser);
00650 #endif
00651
00652 return retval;
00653 }
00654
00655 bool
00656 IMSvrXMLConf::configure(IMSvr *pimsvr)
00657 {
00658 string prefix = SOCKETDIR "/.iiimp-unix";
00659
00660 ptarget = pimsvr;
00661 if (!load())
00662 return false;
00663
00664 #ifdef HAVE_TLS
00665 IMTLS::get_instance()->setup();
00666 #endif
00667 /* config listen address if it has not been configured yet. */
00668 if (listenaddrvec.empty()) {
00669 if (get_boolval(USER)) {
00670 // when iiimd run as a per-user daemon.
00671 // listens to /tmp/.iiimp-unix-${USER}/${PORT}
00672 string user_name;
00673 if (get_process_user(user_name)) {
00674 string sf;
00675 IM_unix_domain_socket_file_dir(user_name, sf);
00676 if (0 < sf.size()) {
00677 listenaddrvec.push_back(IMSocketAddress(IMSocketAddress::UNIX_DOMAIN_PER_USER,
00678 sf,
00679 get_strval(IMSvrCfg::PORT)));
00680 }
00681 #if 0
00682 listenaddrvec.push_back(IMSocketAddress(IMSocketAddress::UNIX_DOMAIN_PER_USER,
00683 string("/tmp/.iiimp-unix-") + user_name,
00684 get_strval(IMSvrCfg::PORT)));
00685 #endif
00686 }
00687 } else if (string(get_strval(IMSvrCfg::UDSFILE)).size() != 0) {
00688 listenaddrvec.push_back(IMSocketAddress(IMSocketAddress::UNIX_DOMAIN,
00689 get_strval(IMSvrCfg::UDSFILE), ""));
00690 } else {
00691 // by default, iiimd listens to
00692 // localhost:9010, /var/run/iiim/.iiimp-unix/${PORT}
00693 /* disable tcp listening by default */
00694 #if 0
00695 listenaddrvec.push_back(IMSocketAddress(IMSocketAddress::INET,
00696 get_strval(IMSvrCfg::HOSTNAME),
00697 get_strval(IMSvrCfg::PORT)));
00698 #endif
00699 listenaddrvec.push_back(IMSocketAddress(IMSocketAddress::UNIX_DOMAIN,
00700 prefix,
00701 get_strval(IMSvrCfg::PORT)));
00702 }
00703 }
00704 config_listenaddress(pimsvr, listenaddrvec);
00705
00706 return true;
00707 }
00708
00709 IMSvrXMLConf::IMSvrXMLConf(IMSvrCfg *pbase,
00710 const char *conffile) : IMSvrCfg(*pbase), filename(conffile)
00711 {
00712 }
00713
00714 IMSvrXMLConf::~IMSvrXMLConf()
00715 {
00716 }
|
__label__pos
| 0.940273 |
Frequency Table
It's very crucial to check the shape of distribution of the random variable, which is not easy to examine with the help of frequency diagram or table. Frequency table helps us display tally of numerous data observations on various categories.
In most cases of discrete quantitative data & qualitative data we use all the noted values of the categories. But, when there are huge number of various observations then consecutive observation might be grouped each other for forming the combined categories.
Frequency Table Examples
Example 1: For instance (growing coffee beans).
We could create the frequency table as shown below:
Frequency Table Example
We don't have to amalgamate them because we have only 10 categories.
But, when it comes to continuous data, selection of categories are more arbitrary as we normally apply 8 to 12 consecutive intervals that are non-overlapping of same width. Lesser than this might be good for smaller sample size and greater for bigger sample. Note that the intervals should cover the whole observed value range.
Example 2: Survival analysis
We've got the following table:
Frequency Table Sample
We need to define the intervals as same as the data. Hence, while the data is defined to the closer values or integers then the intervals need to as mentioned in the above table. On the other hand, intervals should be one decimal place while the data is defined. Again, while the data are rounded to its nearest integers then the intervals are normally 0-39.5, 39.5-79.5 so forth. It's also crucial to sum up sample size with table.
Latest Articles
Average Acceleration Calculator
Average acceleration is the object's change in speed for a specific given time period. ...
Free Fall Calculator
When an object falls into the ground due to planet's own gravitational force is known a...
Permutation
In Mathematics, the permutation can be explained as the arrangement of objects in a particular order. It is an ordered...
Perimeter of Rectangle
A rectangle can be explained as a 4-sided quadrilateral which contains equal opposite sides. In a rectangle
Perimeter of Triangle
A three sided polygon which has three vertices and three angles is called a triangle. Equilateral triangle...
|
__label__pos
| 0.576784 |
TECHNOLOGYtech
How To Teach Someone To Use A Smartphone
how-to-teach-someone-to-use-a-smartphone
Introduction
Welcome to the digital age, where smartphones have become an essential part of our lives. These small devices have revolutionized the way we communicate, work, and entertain ourselves. However, for someone who is new to smartphones, navigating their features and functions can be overwhelming. That’s where you come in – as an experienced smartphone user, you have the opportunity to teach someone the ropes and help them make the most out of their new device.
Teaching someone to use a smartphone requires patience, understanding, and the ability to break down complex tasks into simpler steps. In this guide, we will walk you through the process of teaching someone to use a smartphone, starting from assessing their needs and knowledge, to providing a basic overview of the device, and then diving into the various features and functions. By the end of this guide, you will be well-equipped to teach someone how to use a smartphone with confidence.
Whether you are helping a family member, a friend, or even a coworker, teaching someone to use a smartphone can be a rewarding experience. Not only will you empower them to stay connected and engaged in the digital world, but you will also witness the joy and excitement that comes with mastering new technology. So, let’s get started on this journey of smartphone exploration and discovery.
Assessing the Needs and Knowledge
Before diving into the intricacies of smartphone usage, it is crucial to assess the needs and knowledge level of the person you are teaching. This step will help you tailor your teaching approach to their specific requirements and ensure a personalized learning experience.
Begin by having a conversation with the individual to understand why they want to learn how to use a smartphone. Are they looking to stay connected with friends and family, access information on the go, or explore new apps and functionalities? This will provide you with valuable insights into their motivation and help you prioritize the topics you cover.
Next, assess their existing knowledge of technology. Are they completely new to smartphones, or do they have experience with other electronic devices? Understanding their technological background will allow you to build upon their existing knowledge and ensure a seamless transition to smartphone usage.
Take note of any specific concerns or challenges they may have. Are they worried about privacy and security? Are they apprehensive about learning new technology? Addressing these concerns early on will help alleviate any anxiety and build trust and confidence in the learning process.
Additionally, consider their learning style and preferences. Some individuals may prefer hands-on practice, while others may benefit from visual aids or step-by-step instructions. Adapting your teaching approach to their preferred style will ensure effective comprehension and faster skill development.
By taking the time to assess their needs, knowledge, concerns, and learning style, you will be able to create a customized learning plan that meets their specific requirements. Remember, the journey of learning how to use a smartphone is unique for each individual, and your guidance will play a crucial role in their success.
Providing a Basic Overview of the Smartphone
Before delving into the various features and functions of a smartphone, it is essential to provide a basic overview of the device. This will familiarize the learner with the smartphone’s physical structure and main components.
Start by explaining the different parts of a smartphone, such as the screen, buttons, and ports. Discuss the purpose of each button and the significance of different symbols or icons displayed on the screen.
Next, introduce the concept of touchscreens and gestures. Explain how swiping, tapping, pinching, and zooming can be used to navigate through the device and interact with apps and content. Encourage them to practice these gestures to build their familiarity and comfort with touchscreen technology.
Furthermore, explain the importance of the operating system (OS) that powers the smartphone. Mention the most common OS options, such as Android and iOS, and briefly discuss their key features and differences. Emphasize that understanding the OS will help navigate the device and utilize its functionalities effectively.
Once you have covered the physical aspects and operating system, introduce the concept of apps. Explain that apps are the software programs that allow users to perform various tasks, such as messaging, browsing the internet, and accessing social media. Highlight the importance of the app store or marketplace, where users can download and install new apps.
Finally, briefly mention the importance of regular updates and security measures. Explain that staying up-to-date with software updates will ensure their smartphone is optimized for performance and protected against security vulnerabilities.
By providing a basic overview of the smartphone, you will lay the foundation for further learning. Ensure the learner has a clear understanding of the physical aspects, navigation gestures, operating systems, app functionalities, and the importance of software updates. This knowledge will serve as a solid starting point for their journey into becoming proficient smartphone users.
Navigating the Home Screen
The home screen is the starting point for accessing all the features and functions of a smartphone. Understanding how to navigate the home screen is essential for efficient and seamless usage.
Begin by explaining that the home screen is the main screen that appears when the smartphone is unlocked. It contains a variety of icons, widgets, and folders that provide quick access to apps, settings, and other essential features.
Show the learner how to unlock the smartphone by swiping, entering a passcode, or using biometric authentication like fingerprint or face recognition. Guide them through the process of accessing the home screen.
Next, focus on the main components of the home screen. Discuss the app icons and explain that tapping on an icon opens the corresponding app. Encourage the learner to experiment with tapping different icons and exploring different apps.
Introduce the concept of widgets, which are larger, interactive app components that display information or provide specific functionality. Show them how to add, remove, and rearrange widgets to personalize their home screen.
Discuss the navigation bar or dock, typically located at the bottom of the home screen. Explain that this allows for easy access to frequently used apps, regardless of the screen the user is currently on. Demonstrate how to customize the navigation bar to include their preferred apps.
Furthermore, explain the swipe gestures that can be used on the home screen. For example, swiping left or right can reveal additional screens or pages that contain more app icons or widgets. Emphasize the ability to customize these screens to group apps based on categories or usage patterns.
Lastly, guide the learner through the process of rearranging and organizing app icons on the home screen. Show them how to move icons, create app folders for better organization, and delete unwanted apps.
By providing a comprehensive understanding of how to navigate the home screen, you empower the learner to access apps and features effortlessly. Encourage them to spend time exploring the home screen, arranging their favorite apps, and personalizing it to suit their needs and preferences.
Making and Receiving Phone Calls
The ability to make and receive phone calls is one of the fundamental functions of a smartphone. Teaching someone how to handle phone calls will ensure they can effectively communicate with others using their device.
Start by explaining the different ways to make a phone call. Show the learner how to access the phone app, typically represented by an icon that resembles a telephone receiver. Walk them through the process of dialing a phone number manually using the keypad or selecting a contact from the address book.
Show them how to answer incoming calls by swiping or tapping the appropriate button on the screen. Discuss the options available during a phone call, such as putting a call on hold, muting the microphone, or using the speakerphone function.
Teach them how to end a phone call gracefully by tapping the appropriate button or simply closing the phone app. Emphasize the importance of proper phone etiquette and respectful communication.
Additionally, explain the concept of voicemail and how to access it. Show them how to listen to voicemail messages and guide them through the process of setting up their own voicemail greeting if necessary.
Discuss the various features available during a phone call, such as call waiting, three-way calling, and call forwarding. Show them how to utilize these features when needed, ensuring they have the tools to manage their phone conversations efficiently.
Lastly, address any concerns they may have regarding call quality, network coverage, or how to troubleshoot common issues such as dropped calls or poor reception. Provide guidance on how to adjust network settings and seek assistance from their network service provider if necessary.
By teaching someone how to make and receive phone calls confidently, you empower them to stay connected with friends, family, and colleagues. Encourage them to practice making calls and reassure them that with time and experience, they will become more comfortable with this essential smartphone function.
Sending and Receiving Text Messages
Text messaging, also known as SMS (Short Message Service), is a popular and convenient way to communicate using a smartphone. Teaching someone how to send and receive text messages will enable them to stay connected and exchange information quickly and efficiently.
Start by explaining the messaging app, which is typically represented by an icon resembling a speech bubble or messaging symbol. Show the learner how to access the messaging app and create a new message.
Walk them through the process of entering the recipient’s phone number manually or selecting a contact from the address book. Emphasize the importance of typing the message clearly and concisely.
Show them how to add emojis, stickers, or other multimedia elements to their messages for added expression and personalization. Teach them how to navigate through the keyboard and use features like predictive text to make typing easier and faster.
Demonstrate how to send the message by tapping the “Send” button. Explain that messages are typically displayed as conversations, making it easy to track and manage ongoing communication with different contacts.
Discuss the process of receiving text messages. Show them how new messages appear in the messaging app’s inbox and provide notifications on the smartphone’s screen. Demonstrate how to open and read received messages.
Explain the options available for replying to text messages, including the ability to type a response, add multimedia elements, or use pre-written quick replies if available. Show them how to send the reply by tapping the appropriate button.
Additionally, introduce the concept of group messaging, which allows the user to send a message to multiple recipients simultaneously. Explain how to create a group, add contacts, and send messages to the entire group.
Address any concerns they may have regarding message delivery, read receipts, or troubleshooting issues such as failed message sending. Discuss the importance of a stable network connection and guide them on how to troubleshoot common messaging problems.
By teaching someone how to send and receive text messages effectively, you empower them to communicate efficiently and stay connected with their contacts. Encourage them to practice sending messages and reassure them that with time and experience, they will become more comfortable and proficient with text messaging on their smartphone.
Setting Up a Wi-Fi Connection
A Wi-Fi connection is essential for accessing the internet and enjoying various online services on a smartphone. Teaching someone how to set up a Wi-Fi connection will enable them to connect to Wi-Fi networks wherever available and avoid excessive data usage on their mobile network.
Begin by explaining the importance of Wi-Fi and its benefits, such as faster internet speeds and cost savings. Emphasize the importance of connecting to secure, password-protected networks to ensure their privacy and data security.
Show them how to access the Wi-Fi settings on their smartphone. This can usually be done by going to the Settings app and locating the Wi-Fi option. Demonstrate how to turn on the Wi-Fi toggle switch if it is not already enabled.
Teach them how to scan for available Wi-Fi networks. Show them the list of available networks and explain that networks with a padlock icon require a password for access. Discuss the importance of only connecting to trusted networks and avoiding public networks that may not be secure.
Guide them through the process of connecting to a Wi-Fi network. Show them how to select a network from the list and enter the password if prompted. Explain that once connected, their smartphone will automatically connect to that network whenever it is in range.
Explain the concept of Wi-Fi network preferences and how to prioritize certain networks over others. Show them how to forget a network if they no longer want their device to automatically connect to it.
Discuss the importance of regularly updating the Wi-Fi settings and ensuring the smartphone is connected to a reliable network for seamless internet access. Address any concerns they may have regarding Wi-Fi connectivity, such as network range or troubleshooting steps for connection issues.
Lastly, caution them about potential data security risks when using public Wi-Fi networks, such as those in cafes or airports. Encourage them to use a virtual private network (VPN) for added security when connecting to public networks.
By teaching someone how to set up a Wi-Fi connection on their smartphone, you empower them to access the internet with ease, save on mobile data usage, and capitalize on the benefits of connecting to Wi-Fi networks. Encourage them to explore and connect to different networks, ensuring they follow best practices for network security and provisioning a stable internet connection.
Installing and Uninstalling Apps
One of the most exciting aspects of using a smartphone is the ability to install and enjoy a wide range of applications (apps). Teaching someone how to install and uninstall apps is crucial for them to explore the vast world of possibilities that apps offer.
Start by explaining the concept of an app store or marketplace. Discuss the most popular options, such as the Apple App Store for iOS devices or Google Play Store for Android devices. Show them how to access the app store on their smartphone.
Guide them through the process of searching for apps. Encourage them to search for specific apps by name or explore different app categories for recommendations. Discuss the importance of reading app reviews and checking ratings before downloading.
Show them how to install an app by selecting it from the search results or app listing. Explain that some apps may require permissions to access certain features or data on their device, and encourage them to review and understand these permissions before proceeding.
Demonstrate how to monitor the progress of the app installation and explain that once the app is installed, it will appear on the home screen or in the app drawer. Encourage them to open the newly installed app and explore its features.
Next, teach them how to uninstall apps they no longer need or want. Show them how to find the app in the app drawer, press and hold on the app icon, and then select the option to uninstall or remove the app.
Guide them on navigating through the prompts to confirm the app uninstallation. Explain that uninstalling an app removes it from the device, freeing up storage space and potentially improving device performance.
Address any concerns they may have regarding app security, data privacy, or unwanted app notifications. Discuss the importance of keeping apps updated by enabling automatic app updates or manually checking for updates regularly.
Encourage them to explore different categories of apps, discover new ones, and experiment with various functionalities. Remind them to consider their needs, interests, and the purpose of the app before installing, ensuring they make informed choices.
By teaching someone how to install and uninstall apps, you empower them to customize their smartphone experience and discover apps that enhance their daily life. Encourage them to explore and experiment with apps from reputable sources while maintaining app security and data privacy. The world of apps is constantly evolving, and with your guidance, they can make the most out of this exciting aspect of smartphone usage.
Browsing the Internet
Browsing the internet on a smartphone opens up a world of information, entertainment, and communication. Teaching someone how to browse the internet will allow them to access websites, search for information, and enjoy online content right at their fingertips.
Begin by explaining the web browser app on their smartphone. Show them how to locate and open the app, which is typically represented by an icon resembling a globe or magnifying glass.
Show them how to enter a website address directly into the address bar, also known as the URL bar. Explain that they can type the full URL, such as “www.example.com,” or simply enter the name of the website or topic they are searching for, and the browser will provide suggestions or search results.
Demonstrate how to use search engines to find specific information or websites. Introduce popular search engines like Google or Bing and guide them through the process of entering keywords or phrases into the search bar and reviewing the search results.
Show them how to navigate through search results and click on relevant links to access websites. Emphasize the importance of critically evaluating website credibility and relevance before trusting the information found.
Explain the features and options available within the browser, such as bookmarking websites for easy access later, opening multiple tabs for simultaneous browsing, and managing browsing history and saved passwords.
Teach them how to navigate through websites using gestures like scrolling, zooming in or out, and tapping on links. Explain that some websites may have mobile-friendly versions or responsive designs that adapt to smaller screens for easier browsing.
Introduce common browser features like private browsing or incognito mode, which offers enhanced privacy by not storing browsing history or cookies. Show them how to access and enable this feature, if available.
Discuss the importance of internet safety and security. Encourage them to be cautious when sharing personal information online and advise them to avoid clicking on suspicious links or downloading files from untrusted sources.
Finally, address any concerns they may have about data usage when browsing the internet. Explain that using Wi-Fi instead of mobile data can help conserve their mobile data allowances. Discuss the option of adjusting browser settings to limit images or videos loading automatically to further conserve data.
By teaching someone how to browse the internet confidently, you empower them to access a wealth of knowledge, engage with online content, and stay informed. Encourage them to explore different websites, learn how to evaluate information, and enjoy the diverse offerings available on the internet through their smartphone.
Managing Contacts
Managing contacts on a smartphone is essential for staying connected with friends, family, and colleagues. Teaching someone how to effectively manage their contacts will enable them to easily access and communicate with their network of contacts.
Start by explaining the Contacts app on their smartphone. Show them how to locate and open the app, which is typically represented by an icon resembling a silhouette or a book.
Show them how to add new contacts to their address book. Guide them through the process of entering contact information such as name, phone number, email address, and any additional details they want to include, such as a profile picture or notes.
Demonstrate how to organize contacts into different groups or categories. Explain that this can help them easily find and manage specific sets of contacts, such as family, friends, or coworkers.
Show them how to edit and update contact details when necessary. Explain that they can make changes to a contact’s phone number, email address, or any other information by opening the contact card and selecting the edit option.
Guide them through the process of searching for specific contacts. Show them how to use the search bar within the Contacts app to quickly find a contact based on their name or other identifying information.
Teach them how to delete unwanted or outdated contacts. Show them how to select a contact and delete it from their address book, ensuring they understand that deleting a contact removes all associated information.
Explain the option of syncing contacts with their online accounts, such as Google or iCloud. Demonstrate how to enable contact syncing to ensure that their contacts are backed up and can be easily accessed on multiple devices.
Discuss the importance of regularly updating and cleaning up their contact list. Encourage them to review and remove outdated or duplicate contacts, ensuring their address book remains organized and clutter-free.
Show them how to share contact information with others. Demonstrate how to create a vCard, which is a digital business card containing contact details, and share it through various communication channels such as messaging or email.
Address any concerns they may have about contact privacy and security. Discuss the importance of protecting their contacts and personal information, and advise them to be cautious when granting contact permissions to apps or services.
By teaching someone how to effectively manage their contacts, you empower them to stay connected and organized. Encourage them to explore the various features and options within their Contacts app to customize and streamline their contact management experience.
Using the Camera and Taking Photos
The camera on a smartphone opens up a world of creativity and allows capturing memorable moments. Teaching someone how to effectively use the camera and take photos will enable them to document their experiences and create lasting visual memories.
Start by introducing the Camera app on their smartphone. Show them how to locate and open the app, which is typically represented by an icon resembling a camera.
Show them the different modes and features available in the Camera app. Explain how they can switch between the rear and front-facing cameras to capture photos of different subjects and themselves.
Discuss the importance of framing and composition. Explain basic concepts such as the rule of thirds, leading lines, and focal points. Encourage them to experiment with different angles and perspectives to add depth and visual interest to their photos.
Show them common camera settings such as flash, HDR (High Dynamic Range), and timer. Explain the purpose of each setting and when it is appropriate to use them.
Guide them on how to focus and adjust exposure. Demonstrate how to tap on the screen to select a specific focus point and explain how to adjust the exposure manually if needed.
Discuss the different shooting modes available, such as portrait, landscape, or night mode. Explain the benefits of each mode and when to use them to achieve the desired visual effects.
Show them how to capture a photo by pressing the shutter button or using alternative capture methods like volume buttons or voice commands, if available.
Encourage them to experiment with the different camera features such as filters, shooting modes, and manual settings to add creative effects and enhance their photos.
Show them how to access and manage their photos. Explain that captured photos are typically saved in the Photos app or a designated gallery. Teach them how to view, delete, and organize their photos into albums or folders.
Show them how to share their photos with others. Demonstrate the process of selecting a photo, choosing a sharing method (such as messaging, email, or social media), and sending it to their desired recipient.
Address any concerns they may have regarding storage space and backup. Explain the importance of regularly backing up their photos to avoid losing precious memories in case of device loss or damage.
By teaching someone how to effectively use the camera and take photos, you empower them to capture and preserve their experiences. Encourage them to practice, explore, and experiment with different photographic techniques and settings to develop their own unique photography style and create unforgettable visual memories.
Adjusting Settings and Customizing the Smartphone
Adjusting settings and customizing the smartphone allows users to personalize their device and optimize its functionality according to their preferences and needs. Teaching someone how to adjust settings and customize their smartphone will enable them to tailor the device to their liking and enhance their user experience.
Start by introducing the Settings app on their smartphone. Show them how to locate and open the app, which is typically represented by an icon resembling a gear or a cog.
Discuss the different categories within the Settings app and how each category contains specific settings related to various aspects of the smartphone. Explain that by exploring these categories, they can customize different features and functionalities.
Show them how to adjust basic settings such as brightness, screen timeout, and sound preferences. Explain that these settings impact everyday usage, ensuring optimal viewing comfort and the desired audio experience.
Guide them through network and connectivity settings. Show them how to enable or disable Wi-Fi, Bluetooth, and mobile data, as well as how to adjust other settings such as airplane mode, Wi-Fi hotspot, or VPN (Virtual Private Network).
Discuss the importance of security and privacy settings. Show them how to review and manage permissions for installed apps, adjust app notifications, and enable features such as biometric or fingerprint authentication for added device security.
Show them how to customize the device appearance. Explain how they can adjust wallpaper, choose a different theme, or change the overall look and feel of their smartphone by applying custom fonts, icons, or widgets.
Guide them through additional customization options such as setting a personalized ringtone, enabling or disabling keyboard sound feedback, or changing the device’s keyboard to suit their typing preferences.
Show them how to manage app settings and preferences. Demonstrate how to view and adjust settings for individual apps they have installed, including notification preferences, account settings, or data usage permissions.
Explain the options for managing device storage. Show them how to view storage usage, clear cache and unnecessary files, and transfer files between the device and external storage such as an SD card or cloud storage.
Address any concerns they may have about battery management. Offer tips on optimizing battery life, such as adjusting screen brightness, enabling battery-saving modes, or managing background app activity.
Encourage them to explore and experiment with different settings and customization options, reminding them that they can always revert to default settings if needed. By empowering them to adjust settings and customize their smartphone, you ensure they have full control over their device and can make it truly their own.
Troubleshooting Common Issues
Smartphones are complex devices, and it’s common to encounter some issues along the way. Teaching someone how to troubleshoot common problems will help them overcome obstacles and ensure a smooth smartphone experience.
Start by emphasizing the importance of patience and staying calm when faced with an issue. Encourage them not to panic and assure them that most problems have simple solutions.
Show them how to restart their smartphone when encountering a minor issue. Explain that restarting can resolve temporary glitches or freezes by refreshing the device’s system.
Discuss the importance of keeping the smartphone’s operating system and apps up to date. Guide them through the process of checking for system updates and updating apps to ensure they have the latest bug fixes and performance enhancements.
Show them how to clear app cache or data for specific apps if they are experiencing crashes or sluggishness. Explain that clearing the cache or data can help resolve app-specific issues and improve performance.
Explain the concept of force-stopping an app. Show them how to access the app settings, force-stop problematic apps, and restart them to eliminate any performance-related issues.
Demonstrate how to check available storage on the smartphone. Discuss the importance of keeping sufficient storage space to avoid device slowdown or performance issues.
Show them how to manage app permissions and disable any unnecessary permissions that could potentially cause conflicts or compromise privacy.
Teach them how to troubleshoot connectivity issues. Discuss common problems such as Wi-Fi connectivity or Bluetooth pairing and provide guidance on how to reset network settings or restart the relevant network equipment.
Guide them on how to address battery-related issues. Encourage them to identify and adjust settings or apps that may be draining the battery excessively. Provide tips on optimizing battery life, such as reducing screen brightness or disabling unused features.
Discuss common touchscreen and display issues, such as unresponsiveness or calibration problems. Show them how to clean the screen and recalibrate the touchscreen if needed.
Address common sound-related issues, including audio playback or volume problems. Show them how to check sound settings, ensure volumes are not muted, and troubleshoot any issues with headphones or external speakers.
Encourage them to seek help from manufacturers’ support websites, user forums, or customer service if they encounter persistent or more complex issues that cannot be resolved through simple troubleshooting steps.
By teaching someone how to troubleshoot common issues, you empower them to navigate and resolve problems on their own. Remind them that troubleshooting is part of the learning process, and with a little patience and resourcefulness, they can overcome challenges and enjoy a seamless smartphone experience.
Conclusion
Teaching someone how to use a smartphone is a rewarding journey that empowers them to stay connected, informed, and engaged in the digital world. By breaking down the essential tasks and features into manageable steps, you can guide them towards becoming proficient smartphone users.
Throughout this guide, we have covered various aspects of smartphone usage, from assessing needs and knowledge to providing an overview of the device and exploring its features. We have discussed making phone calls, sending text messages, connecting to Wi-Fi, installing apps, browsing the internet, managing contacts, using the camera, adjusting settings, and troubleshooting common issues.
It’s important to remember that everyone learns at their own pace, so patience and understanding are key. Encourage practice and exploration as they become more comfortable and confident in using their smartphone.
By sharing your knowledge, you have opened up a world of possibilities for them, allowing them to stay connected with loved ones, access information on the go, and enjoy the vast array of apps and services available.
Continue to support and encourage them as they navigate the smartphone landscape. Remind them to stay updated with software updates, practice good privacy and security habits, and seek assistance when needed.
Now armed with the knowledge to teach someone how to use a smartphone, you can make a meaningful impact in their lives. Embrace this opportunity to empower them in the digital age, and watch as they become confident and proficient smartphone users.
Leave a Reply
Your email address will not be published. Required fields are marked *
|
__label__pos
| 0.947179 |
Ex 8.2, 9 - In expansion of (1 + a)m + n, prove coefficients
Advertisement
Ex 8.2,9 - Chapter 8 Class 11 Binomial Theorem - Part 2
Advertisement
1. Chapter 8 Class 11 Binomial Theorem (Deleted)
2. Serial order wise
Transcript
Ex 8.2, 9 In the expansion of (1 + a)m + n, prove that coefficients of am and an are equal. We know that General term of expansion (a + b)n is Tr+1 = nCr an–r br For (1 + a)m + n, Putting n = m + n , a = 1, b = a Tr+1 = n + mCr (1)n + m – r (a)r = n + mCr (a)r Finding coefficient of am ar = am r = m Putting r = m in (1) Tm + 1 = n + mCm (a)m = ((𝑛 + 𝑚)!)/𝑚!(𝑛 + 𝑚 − 𝑚 )! (a)m = ((𝑛 + 𝑚)!)/(𝑚! (𝑛)!) (a)m Hence, coefficient of am is ((𝒏 + 𝒎)!)/𝒎!(𝒏)! Finding coefficient of an ar = an r = n Putting r = n in (1) Tn + 1 = n + mCn (a)n = ((𝑛 + 𝑚)!)/𝑛!(𝑛 + 𝑚 −𝑛 )! (a)n = ((𝑛 + 𝑚)!)/𝑛!(𝑚)! (a)n Hence, coefficient of an is ((𝒏 + 𝒎)!)/𝒏!(𝒎)! Hence, Coefficient of am = Coefficient of an Hence proved
About the Author
Davneet Singh's photo - Teacher, Engineer, Marketer
Davneet Singh
Davneet Singh is a graduate from Indian Institute of Technology, Kanpur. He has been teaching from the past 10 years. He provides courses for Maths and Science at Teachoo.
|
__label__pos
| 0.986158 |
# $Id: nestedloop.parrot,v 1.0 2002/08/20 17:00:00 dada Exp $
# http://dada.perl.it/shootout/
.constant N I0
.constant A I1
.constant B I2
.constant C I3
.constant D I4
.constant E I5
.constant F I6
.constant X I7
set .N, P0[1]
set .X, 0
set .A, .N
A_LOOP:
set .B, .N
B_LOOP:
set .C, .N
C_LOOP:
set .D, .N
D_LOOP:
set .E, .N
E_LOOP:
set .F, .N
F_LOOP:
inc .X
dec .F
if .F, F_LOOP
dec .E
if .E, E_LOOP
dec .D
if .D, D_LOOP
dec .C
if .C, C_LOOP
dec .B
if .B, B_LOOP
dec .A
if .A, A_LOOP
print .X
print "\n"
end
|
__label__pos
| 0.635385 |
Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
PerlMonks
Testing a number for oddness
by Falkkin (Chaplain)
on Jan 23, 2001 at 03:29 UTC ( #53618=perlquestion: print w/replies, xml ) Need Help??
Falkkin has asked for the wisdom of the Perl Monks concerning the following question:
Earlier today, in the CB, I talked with arturo about how to find out whether a given integer is even or odd.
The obvious way to do this involves something like: $odd = $num % 2;.
On the other hand, my CS professor claims that's a slow way of finding out the oddness of a number, and suggests something along the lines of: $odd = $num & 1; instead. This makes sense, because one would assume that a logical AND takes up less CPU time than a DIV instruction.
I decided to test this hypothesis using perl's Benchmark module, and was surprised at the results:
Here's the code:
my $t1 = timeit(1_000_000, \&odd_1); my $t2 = timeit(1_000_000, \&odd_2); print "odd_1: ",timestr($t1),"\n"; print "odd_2: ",timestr($t2),"\n"; sub odd_1 { my $num = rand(2**31); return $num % 2; } sub odd_2 { my $num = rand(2**31); return $num & 1; }
And here, the results:
[falkkin@shadow ~/perl] perl odd.pl odd_1: 6 wallclock secs ( 6.29 usr + -0.00 sys = 6.29 CPU) @ 158982. +51/s (n=1000000) odd_2: 10 wallclock secs ( 9.36 usr + -0.01 sys = 9.35 CPU) @ 106951. +87/s (n=1000000)
It appears that the "slow" method of computing this is actually faster, but I have no idea why. I was wondering if any monks here who know the internals of perl could provide any insight on this.
The only causes I can think of are:
- My CS teacher's claim is simply wrong; she maybe didn't account for newer hardware that is optimized for multiplication & division (although this script is being run on a Pentium I with MMX instructions, which is hardly cutting-edge any more...)
- Perhaps perl's compiler optimizes $num % 2 into "return the last bit of $num"?
Thoughts, anyone?
Replies are listed 'Best First'.
Re: Testing a number for oddness
by Adam (Vicar) on Jan 23, 2001 at 03:52 UTC
Your results imply a significant savings using % instead of &, which made me wonder about them. Thank you for posting your code, I ran it myself (on a dual P3-650 running NT4 with Perl 5.6) and got:
odd_1: 2 wallclock secs ( 1.70 usr + 0.00 sys = 1.70 CPU) @ 586854. +46/s (n=1000000) odd_2: 3 wallclock secs ( 1.67 usr + 0.00 sys = 1.67 CPU) @ 598086. +12/s (n=1000000)
Which implies that the two are roughly equivalent, which is what I expected. I ran a second test with this code (and the following results):
#!perl -w use strict; use Benchmark; timethese( 1_000_000, { odd_1 => sub { my $num = rand(2**31); return $num % 2 }, odd_2 => sub { my $num = rand(2**31); return $num & 2 }, }) __END__ Benchmark: timing 1000000 iterations of odd_1, odd_2... odd_1: 3 wallclock secs ( 1.69 usr + 0.00 sys = 1.69 CPU) @ 59 +2417.06/s (n=1000000) odd_2: 3 wallclock secs ( 1.69 usr + 0.00 sys = 1.69 CPU) @ 59 +2417.06/s (n=1000000)
Ok, I lied. I ran it 5 times, and that result only happened once. But the other 4 runs were also very close. Perhaps there is an optimization running, since %2 would look like "grab the bit shifted off when doing >>1". And I would be surprised if no one (from the authors of Perl on down to the folks at intel) took the time to optimize this rather common operation.
Update:
So I was thinking about this some more, and thought, "I wonder what the deparser has to say about this." Turns out, nothing. Sigh.
>perl -MO=Deparse -we "$n=1231234;print $n % 2" $n = 1231234; print $n % 2; -e syntax OK >perl -MO=Deparse -we "$n=1231234;print $n & 1" $n = 1231234; print $n & 1; -e syntax OK >perl -MO=Deparse,-p -we "$n=1231234;print $n % 2" ($n = 1231234); print(($n % 2)); -e syntax OK >perl -MO=Deparse,-p -we "$n=1231234;print $n & 1" ($n = 1231234); print(($n & 1)); -e syntax OK
Re: Testing a number for oddness
by runrig (Abbot) on Jan 23, 2001 at 04:30 UTC
Whenever running a benchmark, you should, as much as possible, take out things that you are not comparing and use functions/operations that are as low cost as possible (in comparison to what you're comparing). That call to rand() is slowing things down alot, and if you remove it, you get a better comparison:
#!/usr/local/bin/perl -w use strict; use Benchmark; my $i = 0; timethese(200000, { RAND_AND=>\&and_rand, RAND_MOD=>\&mod_rand, TWO_AND=>\&two_and, TWO_MOD=>\&two_mod, }); sub and_rand { my $num = rand(2**31); return $num & 1; } sub mod_rand { my $num = rand(2**31); return $num % 2; } sub two_mod { $i++ % 2; } sub two_and { $i++ & 1; } ~ "tst" 31 lines, 359 characters ~/tst>./tst Benchmark: timing 200000 iterations of RAND_AND, RAND_MOD, TWO_AND, TW +O_MOD... RAND_AND: 1 wallclock secs ( 1.12 usr + 0.00 sys = 1.12 CPU) @ 17 +8571.43/s (n=200000) RAND_MOD: 0 wallclock secs ( 1.10 usr + 0.00 sys = 1.10 CPU) @ 18 +1818.18/s (n=200000) TWO_AND: 0 wallclock secs ( 0.36 usr + -0.01 sys = 0.35 CPU) @ 57 +1428.57/s (n=200000) (warning: too few iterations for a reliable count) TWO_MOD: 2 wallclock secs ( 0.42 usr + -0.00 sys = 0.42 CPU) @ 47 +6190.48/s (n=200000) ~/tst>
Update: Even the ++ in the other two subroutines is a sort of unwanted operator. If I take it out and set $i to a constant, the AND method is almost twice as fast as the MOD method (ok, on second checking maybe that twice as fast was a fluke, its more like 30-40% faster consistently).
On constants, the AND may be getting optimized away, and in checking I find that it is...
# perl -MO=Deparse,-p -we "print 15 & 1" print(1); -e syntax OK # perl -MO=Deparse,-p -we "print 16 & 1" print(0); -e syntax OK
--
$you = new YOU;
honk() if $you->love(perl)
It turns out that almost all operators in Perl get optimized away in this manner. 'Constant folding', as it's called, is a very common optimization.
% perl -MO=Deparse print 15 + 1, 15 - 1, 15 * 1, 15 % 1, 15 & 1, 15 ^ 1, 15 << 1, !15, 15 || $x, 15 . 1, 15 < 1, 15 <=> 1, 15 ? $x : $y; __END__ print 16, 14, 15, 0, 1, 14, 30, 0, 15, '151', 0, 1, $x;
In fact, the only operator I've found that could have this optimization but doesn't is x.
That's why I set '$i' to a constant (my $i=15), then AND'ed it. I checked, and THAT won't get optimized away.
Re: Testing a number for oddness
by Fastolfe (Vicar) on Jan 23, 2001 at 05:02 UTC
Update: chipmunk notes that I was using % 1 instead of % 2, which was a stupid mistake on my part. I've updated the code and benchmarks, but the results do not differ significantly.
Because I'm bored and in love with Inline:
use Benchmark 'timethese'; use Inline C => <<'EoF'; int c_and(int num) { return(num & 1); } int c_mod(int num) { return(num % 2); } EoF my $num = 5; sub perl_mod { $_[0] % 2 } sub perl_and { $_[0] & 1 } timethese(10_000_000, { perl_mod => sub { perl_mod($num) }, perl_and => sub { perl_and($num) }, c_mod => sub { c_mod($num) }, c_and => sub { c_and($num) }, }); __END__ c_and: 7 wallclock secs ( 7.09 usr + 0.05 sys = 7.14 CPU) @ 14 +00560.22/s (n=10000000) c_mod: 8 wallclock secs ( 7.44 usr + -0.01 sys = 7.43 CPU) @ 13 +45895.02/s (n=10000000) perl_and: 17 wallclock secs (16.63 usr + -0.01 sys = 16.62 CPU) @ 60 +1684.72/s (n=10000000) perl_mod: 16 wallclock secs (16.65 usr + 0.01 sys = 16.66 CPU) @ 60 +0240.10/s (n=10000000)
For all intents and purposes, it seems like both methods are equally fast, at least as far as any Perl implementation is concerned, and at least on my architecture (i686-linux, P3/850). A few microseconds isn't going to make a difference in any real-world application, and Perl itself may have quirks that cause one implementation to be slower or faster than another. It may very well be that a 100% C solution to all of this will show the expected results (with & being marginally faster), but it doesn't look like you're going to get those results in Perl.
Additionally, you guys are relying on Benchmark results with way too few iterations. If you're wanting to compare and contrast algorithms and are getting Benchmark results in the 0-2 second range, you need to increase your repetitions at least an order of magnitude.
(tye)Re: Testing a number for oddness
by tye (Sage) on Jan 23, 2001 at 04:46 UTC
$x & 1 will probably have to convert the double-precision floating point value stored in $x into a "long int" before it can do the fast bit-wise "and". This conversion may well take longer than the simple floating-point division (which will have the aid of floating-point acceleration hardware) that $x % 2 must do.
This probably explains some of the benchmark results.
To me, a much worse problem than the misguided "optimization" of such a simple operation is that $x & 1 will only work for integral values that fit within 32 bits (on most platforms). However, $x % 2 will work correctly on integeral values of approximately 57 bits (on most platforms). Using % 2 will probably make your code handle a much huger range of values correctly.
- tye (but my friends call me "Tye")
Re: Testing a number for oddness
by Maclir (Curate) on Jan 23, 2001 at 04:31 UTC
OK, I was struck my the significant difference Falkkin obtained. I ran the same script on my development box here (a Sun Ultra 2, with a 300MHz Ultrasparc CPU and 128 MB of ram), and these were my results:
odd_1: 9 wallclock secs ( 8.55 usr + 0.00 sys = 8.55 CPU) odd_2: 9 wallclock secs ( 9.46 usr + 0.00 sys = 9.46 CPU)
The divide is about 10% faster than the shift. Why is this so? I personally would have thought a shift operation - a basic opcode in just about any instruction set - would be faster that a division.
Update: I followed runrig's advice and took out the rand call. The results were different:
odd_1: 7 wallclock secs ( 6.41 usr + 0.00 sys = 6.41 CPU) odd_2: 7 wallclock secs ( 6.00 usr + 0.00 sys = 6.00 CPU)
Now the division is longer - by about 7%. Strange stuff.
Re: Testing a number for oddness
by lhoward (Vicar) on Jan 23, 2001 at 04:45 UTC
One thing you have to remember is that these operations are, at the perl layer, not being done on an integer (or anything else that is native to the underlying architecture) but on a perl scalar value. I bet if you ran the same tests in C (or assembler, or any language that was "right on the hardware") and you were sure that modulus division wasn't part of the CPU's instruction set (or produced as a side-effect of the div operation) the results would be much more like you expected.
Re: Testing a number for oddness
by mr.nick (Chaplain) on Jan 23, 2001 at 20:05 UTC
It's kind of funny, runrig even mentioned that when benchmarking you should exclude operations that don't concern the thing you are trying to test, yet every single example called their "perl_and/mod" function for one operation. Don't you think the function call from timethese/timeit to perl_and/mod is taking time?
So I did it this way:
sub perl_mod { for my $z (1..10_000) { $_[0] % 2; } } sub perl_and { for my $z (1..10_000) { $_[0] & 1; } } timethese(10_000, { perl_mod => sub { perl_mod($num) }, perl_and => sub { perl_and($num) }, });
and got the following results:
nicholas(/5)@neko [106 /<1>nicholas/tmp] > ./time Benchmark: timing 10000 iterations of perl_and, perl_mod... perl_and: 210 wallclock secs (209.32 usr + 0.79 sys = 210.11 CPU) perl_mod: 260 wallclock secs (258.62 usr + 0.93 sys = 259.55 CPU) nicholas(/5)@neko [107 /<1>nicholas/tmp] >
Which shows the perl_and to be around 20% faster than perl_mod: about what I would expect.
Then, I did a pure C test:
#include <stdio.h> void c_and(int i) { int a; for (a=0;a<10000;a++) { i & 1; } } void c_mod(int i) { int a; for (a=0;a<10000;a++) { i % 2; } } int main(void) { int a; for (a=0;a<100000;a++) { c_and(a); } //for (a=0;a<100000;a++) { // c_mod(a); //} exit(0); }
and ran it seperately for each of the types (I was using /bin/time to test):
For c_and: 29.800u 0.040s 0:29.84 100.0% 0+0k 0+0io 69pf+0w
and
for c_mod: 29.540u 0.390s 0:29.99 99.7% 0+0k 0+0io 69pf+0w
Which again shows and to be faster, though no wheres as much of a difference as with perl (I presume gcc is optimized).
test platform: dual PII-233 with a load avg of around 7 :)
gcc is OBVIOUSLY optimized. % is always craploads slower than &. On a modern processor, a multiply, add, subtract, bitshift, etc., can be done in one cycle (assuming all operands are already loaded into registers), whereas a divide could take 10-50 or even more cycles.
To get gcc to not optimize anything away do something like this:
#include <stdio.h> volatile int yb; int foo; void blah(int t) { foo = (t==0)? 1: 2; } int main(int argc, char **argv) { int x = 0xdeadbeef; volatile int *y = &yb; int i; int t = atoi(argv[1]); blah(t); if (t == 0) { printf("Using the & method\n"); for (i=0;i<100000000;++i) *y=x & foo; } else { printf("Using the %% method\n"); for (i=0;i<100000000;++i) *y=x % foo; } return 0; }
NOTES: x is initialized with a non-zero value. On x86 I have noticed sometimes ALU/Mult operations on zero-valued inputs can be significantly faster than on non-zero inputs.
y is a volatile pointer to prevent gcc from optimizing the loops away, if it was so inclined.
'foo' is not a constant to prevent gcc from optimizing an odd/even test.
'foo' is initialized in a non-static function to prevent gcc from (if it could/would do this) optimizing the loops to odd/even test anyway.
We do 100 million iterations, to drown out any noise.
Running on an unloaded 933Mhz P-III:
% time ./foo 0 Using the & method 0.77user 0.01system 0:00.80elapsed 96%CPU (blah blah) % time ./foo 1 Using the % method 4.29user 0.00system 0:04.43elapsed 96%CPU (blah blah)
I ran the tests about 10 times each and the results are about the same.
Now if you are just doing a odd-even test, gcc will likely be able to optimize it for you to the point that you can use whatever method you want and it will be fast. If you programming on a DSP, however, or maybe in a super-high-speed driver or something, you'd want to make sure you use the fast version, cuz the compiler in that case likely can't help you (or you don't want it to).
And in Perl anyway, you are operating many levels about the underlying machine architecture. % vs & is the least of your worries speed-wise.
See the Benchmark docs. It factors out the null loop, so even looping within your subroutine adds operations that you'd rather not time (for '&' and '%' anyway; if you are timing more expensive operations/algorithms then it is not significant). See this:
#!/usr/local/bin/perl -w use strict; use Benchmark; my $i = 34; timethese(3000000, { AND=>\&and_them, MOD=>\&mod_them, NULL_LOOP=>\&null_loop, }); sub null_loop { } sub and_them { $i & 1; } sub mod_them { $i % 2; } ~ "tst" 23 lines, 229 characters [rover:DEV]~/tst>./tst Benchmark: timing 3000000 iterations of AND, MOD, NULL_LOOP ... AND: 1 wallclock secs ( 1.68 usr + 0.00 sys = 1.68 CPU) @ 17 +85714.29/s (n=3000000) MOD: 2 wallclock secs ( 2.33 usr + 0.00 sys = 2.33 CPU) @ 12 +87553.65/s (n=3000000) NULL_LOOP: -1 wallclock secs (-0.07 usr + 0.00 sys = -0.07 CPU) @ -4 +2857142.86/s (n=3000000) (warning: too few iterations for a reliable count)
(I realize that in the end it really doesn't matter, I'd probably use '%' anyway, and this is all just for the sake of discusssion/fun/curiousity).
Log In?
Username:
Password:
What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://53618]
Approved by root
help
Chatterbox?
and all is quiet...
How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (9)
As of 2016-12-09 18:09 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
On a regular basis, I'm most likely to spy upon:
Results (154 votes). Check out past polls.
|
__label__pos
| 0.771568 |
What does Data engineers do? Tips getting into the data engineering workflow
turned on monitoring screen
What Do Data Engineers Do?
Data engineers are responsible for designing, building, and maintaining the infrastructure that supports the storage, processing, and analysis of large volumes of data. They work closely with data scientists and analysts to ensure that data is available, accessible, and of high quality.
Home Setup
Data engineers are responsible for the following tasks:
1. Data Ingestion: Data engineers are responsible for designing and building data pipelines that bring data from various sources into a centralized data repository. This may involve extracting data from databases, APIs, or other sources, and transforming it into a format that can be easily consumed and analyzed.
2. Data Storage: Data engineers are responsible for designing and implementing data storage solutions that are scalable, secure, and highly available. This may involve working with databases such as MySQL, PostgreSQL, or MongoDB, or big data storage solutions such as Hadoop or S3.
3. Data Processing: Data engineers are responsible for designing and building data processing systems that can handle large volumes of data efficiently. This may involve working with technologies such as Apache Spark, Flink, or Kafka, which are designed to handle big data processing at scale.
4. Data Quality: Data engineers are responsible for ensuring that the data is of high quality, which means that it is accurate, complete, and consistent. This may involve developing and implementing data quality checks, and designing data validation processes.
5. Data Security: Data engineers are responsible for ensuring that the data is stored and processed securely. This may involve working with encryption technologies, implementing access controls, and monitoring for security breaches.
The Workflow of a Data Engineering Team
The workflow of a data engineering team typically follows a series of steps:
1. Planning: In this phase, the data engineering team works with stakeholders to understand their data needs and develop a plan for how data will be collected, stored, and processed.
2. Data Collection: In this phase, the data engineering team works to collect data from various sources, such as databases, APIs, or other systems.
3. Data Storage: In this phase, the data engineering team works to design and implement a data storage solution that can handle the volume of data and ensure that it is stored securely.
4. Data Processing: In this phase, the data engineering team works to design and implement a data processing system that can handle large volumes of data and transform it into a format that can be easily analyzed.
5. Data Quality: In this phase, the data engineering team works to ensure that the data is of high quality, which means that it is accurate, complete, and consistent.
6. Data Security: In this phase, the data engineering team works to ensure that the data is stored and processed securely, which may involve implementing access controls, encryption technologies, and monitoring for security breaches.
7. Maintenance: In this phase, the data engineering team works to maintain the infrastructure that supports the storage, processing, and analysis of data, and ensure that it continues to meet the needs of the organization.
Conclusion
Data engineers are an essential part of any organization that deals with large volumes of data. They are responsible for designing, building, and maintaining the infrastructure that supports the storage, processing, and analysis of data. The workflow of a data engineering team typically involves planning, data collection, data storage, data processing, data quality, data security, and maintenance. By following these steps, data engineering teams can ensure that their data is available, accessible, and of high quality, and support data-driven decision making within the organization.
|
__label__pos
| 0.994691 |
How to Scale UI Text for DaVinci Resolve
How to Change UI Text Size in DaVinci Resolve
If you found yourself having trouble reading the UI text in DaVinci Resolve, don’t worry you’re not alone. Currently Resolve does not have any settings available that allows you to change the font size of the UI. Rest assured because we do have a work around.
For Windows
1. Go to settings and click on the “Display Tab”. Under “Scale and Layout”, change the size of text, app and other items. You can set this to 125%, 150% or whatever is comfortable for you. Changing this alone won’t change the size in Resolve unless we tweak something first.
davinci resolve scale font size step 1
2. Right click DaVinci Resolve on your desktop then Click On “Open file location”
davinci resolve scale font size step 2
3. This will open up the Resolve folder. Right click on Icon in file location and select “Properties”
davinci resolve scale font size step 3
4. Click on “Compatibility” tab
davinci resolve scale font size step 4
5. Click on “Change high DPI settings”
davinci resolve scale font size step 5
6. Check the box “Override high DPI scaling behavior.”
7. In “Scaling performed by:” drop down menu Select “System (Enhanced)”
davinci resolve scale font size step 6
8. Click “OK”
9. Open up Resolve and the UI should have scaled with your Display Settings
That sums up the steps to scaling the UI font size inside DaVinci Resolve. Now you are free to scale the text size as much as you want, making it easier to edit videos.
|
__label__pos
| 0.679285 |
label
Specifies options for value axis labels.
Type: Object
Axis labels represent textual values for axis ticks, which are not visible by default. To specify custom settings for the value axis labels, use the label configuration object. If you need to set a common value for labels on all axes, use the commonAxisSettings | label configuration object. This object exposes the properties that can be specified for labels on all axes simultaneously. Note that a value specified for the value axis individually (in the valueAxis | label object) overrides the value that is specified in the commonAxisSettings | label object.
Show Example:
jQuery
In this example, additional text is added to the value axis labels using the customizeText option.
alignment
Specifies the label's position relative to the tick (grid line).
Type: String
Default Value: undefined
Accepted Values: 'left' | 'center' | 'right'
Show Example:
jQuery
Use the drop-down menu at the bottom to change the value axis' alignment option.
customizeHint
Specifies the text for a hint that appears when a user hovers the mouse pointer over a label on the value axis.
Type: function(axisValue)
Function parameters:
axisValue: Object
An object providing access to the value displayed by the axis label.
Object structure:
The value as it is specified in the data source.
valueText: String
The value with applied format and precision.
Return Value: String
The text to be displayed in the hint.
This option accepts a function that must return the required text. When implementing this function, use its parameter to access the value displayed by the axis label.
customizeText
Specifies a callback function that returns the text to be displayed in value axis labels.
Type: function(axisValue)
Function parameters:
axisValue: Object
Defines an axis value.
Object structure:
Specifies the axis value that is currently represented.
valueText: String
Specifies the currently represented axis value with an applied format, if the format and precision (optional) properties are specified.
Return Value: String
The text to be displayed by a value axis label.
Cannot be used in themes.
When implementing a callback function for this configuration option, use the value to be displayed in a label. This value can be accessed using the fields of the object that is passed as the function's parameter. Alternatively, you can use the this object within the function. This object has the same structure as the object passed as a parameter.
For general information on data formatting, refer to the Data Formatting topic.
Show Example:
jQuery
In the example below, additional text is added to the value axis' label values using the customizeText option.
font
Specifies font options for axis labels.
Type: Object
Show Example:
jQuery
In this example, the font color of the value axis label text is black, and the font size is increased to 15 pixels.
format
Specifies a format for the text displayed by axis labels.
Type: String
Default Value: ''
Accepted Values: 'currency' | 'fixedPoint' | 'percent' | 'decimal' | 'exponential' | 'largeNumber' | 'thousands' | 'millions' | 'billions' | 'trillions' | 'longDate' | 'longTime' | 'monthAndDay' | 'monthAndYear' | 'quarterAndYear' | 'shortDate' | 'shortTime' | 'millisecond' | 'day' | 'month' | 'quarter' | 'year'
Labels display axis values. You can apply formatting to the label text by using one of the available formats.
NOTE
You can set a precision for a label text when the 'fixedPoint', 'exponential', 'currency' or 'percent' format is applied. Use the precision property to do this.
For details on formatting, refer to the Data Formatting topic.
Show Example:
jQuery
The example below shows a chart with formatted value axis labels. The format of these labels is set to 'fixedPoint' using the format option.
indentFromAxis
Specifies the spacing between an axis and its labels in pixels.
Type: Number
Default Value: 10
IdentFromAxis ChartJS
overlappingBehavior
Specifies the overlap resolving algorithm to be applied to axis labels.
Type: String|Object
Default Value: 'auto'
Accepted Values: object | 'auto' | 'ignore' | 'stagger' | 'rotate' | 'enlargeTickInterval'
When labels overlap each other, you can specify how these labels will be displayed by setting the overlappingBehavior option. The values accepted by this option depend on whether an axis is horizontal or vertical.
NOTE
By default, the argument axis is horizontal and the value axis is vertical. To swap the axes over, assign true to the rotated property.
For a vertical axis, the following values can be assigned to the overlappingBehavior option.
• auto
Resolve the label overlapping automatically.
• ignore
Leave the labels overlapped.
• enlargeTickInterval
Leave the labels as they are, but enlarge the axis tick intervals so that the labels do not overlap.
Horizontal axis' labels have two more modes. These modes are always applied regardless of there being a label overlap or not.
• stagger
Arrange labels in a staggered manner. The spacing between label rows will be 5 pixels.
• rotate
Rotate labels so that they are perpendicular to the axis.
To set custom spacing between staggered rows or the custom rotation angle for the 'stagger' and 'rotate' modes, assign an object to the overlappingBehavior configuration property. Set the object's mode property to the required mode, and set the staggeringSpacing or rotationAngle property to the required value.
Show Example:
jQuery
In the following example, the chart is rotated and the value axis tick interval is intentionally set to a very small value, so that the labels overlap each other. The overlap is resolved by staggering the labels with 2 pixel spacing.
precision
Specifies a precision for the formatted value displayed in the axis labels.
Type: Number
Default Value: 0
This property's value must be an integer indicating the number of digits to show in the axis values displayed in labels. This property value is used when labels display axis values in one of the following numeric formats: 'fixedPoint', 'exponential', 'currency' or 'percent'. To learn how to set a format for axis values, refer to the format property description.
For general information on data formatting, refer to the Data Formatting topic.
Show Example:
jQuery
The example below represents a chart with formatted value axis labels. The format of these labels is set to 'fixedPoint' using the format option, and the presicion is set to 2 using the precision option.
visible
Indicates whether or not axis labels are visible.
Type: Boolean
Default Value: true
Show Example:
jQuery
Use the check box at the bottom to change the visibility of the value axis labels.
|
__label__pos
| 0.53066 |
Company Name Starts with ...
# A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
CTS Struts Interview Questions
Questions Answers Views Company eMail
what is project architecture?give brief explanation about project architecture?
3 49708
What is Struts Flow?
17 44585
what is difference between and tag
2 13973
how canu done chechin and check out of u r project using with sample examples?
8 6422
i have list of values(e.g 100). using logic:iterate, how can i print the multiples of 5th element? how the logic:iterate will understand the multiples of 5.
2 7468
what is struts? why Struts?
6 6053
Post New CTS Struts Interview Questions
CTS Struts Interview Questions
Un-Answered Questions
can u explain about design patterns like singleton,builder,factory
1368
take 100kva DTR( delta/wye ), what ll happen if we connect 11kv to LT side instead of connecting to HT side? will the DTR behave as a step up transformer or something else????
1222
What is single stepping and how can it be achieved on the 8086?
75
What will be your approach to improve customer service?
80
How do you add/remove a payment block for particular invoice ?
1241
Tell me what do you mean by term "annuity"? : insurance sales
17
Is linux hard to learn?
42
Does a server store data?
20
what is the calculation for getting the tablet weight and the punch size, Eg..if there is a 8/32 punch then how to measure tablet weight????
4577
Explain in brief preliminaries of C/C++?
1
What is Covariance and contravariance in C#?
77
Explain the system log?
59
In which forms arsenic impurities present in drug.
292
What is the function of trim?
29
Is microsoft autoupdate a virus?
23
|
__label__pos
| 1 |
Ширина блока контента
7 года 3 мес. назад #436 от KocH
Здравствуйте.
Пытаюсь сделать свой шаблон. Возник вопрос - как сделать, чтобы ширина блока контента автоматически растягивалась до краев, если в колонках слева и справа нет никаких модулей и уменьшалась при включении модуля. А то у меня при включении модулей в правой колонке, они (модули)съежают под контент, хотя заданы float left для контента и float right для правой колонки.
Это index.php
<?php
// no direct access
defined( '_JEXEC' ) or die( 'Restricted access' );
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" " www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
<html xmlns=" www.w3.org/1999/xhtml " xml:lang="<?php echo $this->language; ?>" lang="<?php echo $this->language; ?>" >
<head>
<jdoc:include type="head" />
<link rel="stylesheet" href="<?php echo $this->baseurl ?>/templates/system/css/system.css" type="text/css" />
<link rel="stylesheet" href="<?php echo $this->baseurl ?>/templates/system/css/general.css" type="text/css" />
<link rel="stylesheet" href="<?php echo $this->baseurl ?>/templates/KO_odessa/css/template.css" type="text/css" />
</head>
<body>
<div id="header">
<div id="logo"><img src="<?php echo $this->baseurl ?>/templates/KO_odessa/images/logo.png"></img>
</div>
<div id="inhead">
<div id="search"> <?php if($this->countModules('top1')) : ?>
<jdoc:include type="modules" name="top1" style="xhtml" />
<?php endif; ?>
</div>
<div id="clear"></div>
<div id="topnav"> <?php if($this->countModules('top2')) : ?>
<jdoc:include type="modules" name="top2" style="xhtml" />
<?php endif; ?>
</div>
</div>
</div>
<div id="wrapper">
<div id="midbox">
<div id="leftnav"> <?php if($this->countModules('header1')) : ?>
<jdoc:include type="modules" name="header1" style="xhtml" />
<?php endif; ?>
</div>
<div id="slaider"> <?php if($this->countModules('header2')) : ?>
<jdoc:include type="modules" name="header2" style="xhtml" />
<?php endif; ?>
</div>
</div>
<div id="clear"></div>
<div id="topper">
<div id="topleft"> <?php if($this->countModules('user1')) : ?>
<jdoc:include type="modules" name="user1" style="xhtml" />
<?php endif; ?>
</div>
<div id="topright"><?php if($this->countModules('user2')) : ?>
<jdoc:include type="modules" name="user2" style="xhtml" />
<?php endif; ?>
</div>
</div>
<div id="content">
<div id="leftcol"><jdoc:include type="component" />
</div>
<?php if($this->countModules('right')) : ?>
<div id="rightcol"><jdoc:include type="modules" name="right" style="xhtml" /></div>
<?php endif; ?>
</div>
<div id="clear"></div>
<div id="footer">
<div id="botmenu"><?php if($this->countModules('footer')) : ?>
<jdoc:include type="modules" name="footer" style="xhtml" />
<?php endif; ?>
</div>
</div>
</div>
</body>
</html>
а это css :
*{
margin: 0;
padding: 0;
}
body{
background-color:#3E4B6B;
}
#header{
margin: 0 auto;
width:980px;
height:100px;
}
#logo{
width: 157px;
height: 96px;
margin-left: 30px;
float: left;
}
#inhead{
height: 100px;
width: 793px;
margin-left:187px;
}
#search{ /* Строка поиска */
margin-top: 10px;
float:right;
height: auto;
width: auto;
}
/* Модуль поиска*/
.search .button{
padding-left:2px;
padding-right:2px;
margin-left: 3px;
height:20px;
width:50px;
border:1px solid #8D99A5;
background-image:url(../images/search_but.png);
color: #ffffff;
font-size: 11px;
}
.search .button:hover{
color:#8D99A5;
cursor:pointer;
}
.search .inputbox {
border: none;
height:20px;
}
#topnav{ /* Верхнее меню */
float:right;
margin-top: -20px;
}
#topnav a:link, #topnav a:visited {
color: #FFFFFF;
width:auto;
margin-left: 5px;
margin-right: 5px;
text-decoration: none;
font-family: arial;
font-size: 11px;
}
#topnav a:hover , #topnav a:active {
color: #FFFFFF;
text-decoration: underline;
}
#wrapper {
width: 980px;
position: relative;
margin: 0 auto;
background-color: #ccccff;
}
/* Навигация и слайдер */
#midbox{
float: left;
margin: 0 auto;
margin-top: 20px;
margin-left:20px;
width: 940px;
height: 250px;
}
#clear{
clear: both;
}
/* Навигация слева */
#leftnav {
width: 200px;
min-height:240px;
float: left;
border: 1px solid white;
background:#3E4B6B;
padding-bottom: 10px;
}
#slaider{
width: 740px;
height: 250px;
margin-left: 200px;
border: 1px solid white;
}
.moduletable_menu h3{
font-family: Arial;
background: #ffffff;
text-indent: 10px;
color: #44516F;
}
.moduletable_menu ul{
list-style:url(../images/str.png);
margin-left: 30px;
margin-top: 5px;
margin-right: 25px;
}
.moduletable_menu ul li{
border-bottom: 1px solid #ffffff;
line-height: 25px;
font-size: 12px;
font-family: arial;
padding-right: 20px;
}
.moduletable_menu ul li a:link,
.moduletable_menu ul li a:visited{
text-decoration: none;
color: #ffffff;
}
.moduletable_menu ul li a :hover,
.moduletable_menu ul li a :active{
text-decoration: underline;
color: #ccccff;
}
#current a{
color: #ccccff;
}
#topper{
margin-left:20px;
margin-top:20px;
}
#topleft{
margin-left: 20px;
float: left;
background: white;
}
#topright{
margin-right: 20px;
float: right;
background: white;
}
/* Контент */
#content{
margin-left:20px;
margin-right:20px;
background-color: #ccccff;
}
#leftcol {
float: left;
margin-top: 10px;
background-color: white;
}
#rightcol{
width: 250px;
margin-top: 10px;
background-color: #ccccff;
float: right;
}
#footer{
margin: 0 auto;
width: 980px;
height: 70px;
background: #ccccff;
}
#botmenu {
margin-top: 10px;
margin-left: 40px;
float:left;
width:900px;
height: 25px;
}
Пожалуйста Войдите или Зарегистрируйтесь, чтобы присоединиться к беседе.
7 года 2 мес. назад #442 от Wedal
KocH, не знаю какой кусок кода выводит левую колонку, но допустим этот:
<div id="topleft"> <?php if($this->countModules('user1')) : ?>
<jdoc:include type="modules" name="user1" style="xhtml" />
<?php endif; ?>
Т.е. у вас есть условие: если в позиции user1 есть хотя бы один модуль, то показать его.
Отталкиваясь от этого, вы должны правильно оперировать стилями и версткой. Т.е. если у вас имеется левая колонка фиксированной ширины, в которую уже входит вышеприведенный код, то, естественно, ничего не получится. Вам нужно поместить код создания колонки внутрь этого условия так, чтобы остальной код работал в любом случае, либо вы можете создать еще одно такое условия, изменяя для него стили. Например, если модули есть, то левая колонка 200px, если нет, то 0px. Аналогично должна расширяться и центральная часть. Короче говоря, решений тут очень много. Если все это не очень понятно, почитайте серию статей про создание шаблона Joomla. Там я как раз описывал такой случай.
Спасибо сказали: KocH
Пожалуйста Войдите или Зарегистрируйтесь, чтобы присоединиться к беседе.
7 года 2 мес. назад - 7 года 2 мес. назад #445 от KocH
Извините если выразился не правильно (а похоже что так и есть). Вопрос в том, чтобы колонка контента уменьшалась или увеличивалась по ширине, в зависимости от того есть ли в ней включенный модуль. Код что вы указали прекрасно работает, но когда подключаются модули - правая колонка падает под контент, а ширина самого контента не изменяется. Имеет ли в этом случае значение резиновый шаблон или нет (в моем случае должен быть не резиновый)?
блок контента <divid="leftcol">.Правая колонка - rightcol. Оба находятся в блоке content
Пожалуйста Войдите или Зарегистрируйтесь, чтобы присоединиться к беседе.
7 года 2 мес. назад #450 от Wedal
KocH, "резиновость" шаблона значения не имеет. Вот такой пример:
Предположим, что у вас есть сайт, содержащий левую колонку(150px) правую колонку(150px) и основную часть(500px). Вам нужно сделать так, чтобы если в правой колонке нет модулей, то центральная честь растягивалась на ширину этой правой колонки, т.е. становилась 650px.
Теперь, все, что необходимо сделать - добавить все это дело в условие, которое я приводил выше. Если в правой колонке есть модули, то установить ее ширину в 150px, а ширину основной части в 500px, если модулей нет, то ширину правой колонки 0px, а основной части 650px.
Честно говоря, это не совсем правильно. Лучше было бы не устанавливать ширину правой колонки в 0px, а вообще убрать код ее отображения. Способов много, выбирайте любой.
Пожалуйста Войдите или Зарегистрируйтесь, чтобы присоединиться к беседе.
7 года 2 мес. назад - 7 года 2 мес. назад #453 от KocH
Разобрался. Но возник другой вопрос к Вам Wedal. Как в шаблоне можно реализовать главную страницу без отображения статей. А контент чтоб отображался уже на других страницах. Только различные модули. В Вашем платном разделе есть много таких шаблонов. Как например эти.
www.templatehelp.com/preset/pr_preview.php?i=33159&pr_code=nLz72g9u8P8746K7xV09MVxLq67tq1
www.templatehelp.com/preset/pr_preview.php?i=33097&pr_code=nLz72g9u8P8746K7xV09MVxLq67tq1
Пожалуйста Войдите или Зарегистрируйтесь, чтобы присоединиться к беседе.
7 года 2 мес. назад #457 от Wedal
KocH, зайдите в менеджере меню в настройки главной страницы. Там справа можно будет указать количество материалов, выводимых на главной. Оставьте только один материал. Далее в менеджере материалов создайте пустую статью, укажите ее отображение для главной. Для остальных статей отключите отображение на главной. Далее, с помощью плагина loadmodule вставляйте в эту статью какие угодно модули. Подробно об этом можно почитать в одной из статей, которые я писал: wedal.ru/rasshireniya-joomla/virtuemart-internet-magazin-na-joomla-chast-18-vivod-kategoriy-virtuemart-s-izobrazeniyami-na-glavnoy-stranice-saita.html
Спасибо сказали: KocH
Пожалуйста Войдите или Зарегистрируйтесь, чтобы присоединиться к беседе.
Вверх
|
__label__pos
| 0.852633 |
lobo_tuerto's notes
Home
Blog
Notes
About
A confirmation dialog component in Vue 3 with Tailwind CSS
Let's write a reusable confirmation dialog with Vue and Tailwind CSS.
📅Published31 July 2022
🏷️
demofrontendtailwindcsstypescriptvue 3
Table of contents
I’d like to have a basic confirmation dialog I can use instead of the default browser confirm() function.
Let’s make it reusable and configurable for different scenarios.
Prerequisites
We’ll use the <BaseModal> component we wrote in:
A basic modal component in Vue 3 with Tailwind CSS.
Desired API
Let’s suppose we already have a <ConfirmationDialog> component, and we’d like to use it like this:
Dialog 1
<script setup lang="ts">
import { ref } from 'vue'
import ConfirmationDialog from '@/components/modals/ConfirmationDialog.vue'
const showDialog = ref(false)
function handleResult(value: boolean) {
showDialog.value = false
// Do something with `value`
console.log('value', value)
}
</script>
<template>
<ConfirmationDialog :show="showDialog1" @result="handleResult" />
</template>
Here is where you can think about and define the API you want to provide for users of your component.
Is it better to have a @result event that gets passed a boolean?
Or would it better to have two type of events emitted like @confirm and @cancel?
That depends on your taste. For now I’ll go with the simple approach of having a single event that we can handle on the host.
Customizability
Ideally we’d like to have a default implementation that’s good enough for the majority of use cases; but then we’d like to have the option to provide alternative markup for the different parts that compose our component.
This is the perfect use case for slots in Vue.
Let’s say we want to customize the title and body, maybe with something like this:
Dialog 2
<script setup lang="ts">
import { ref } from 'vue'
import ConfirmationDialog from '@/components/modals/ConfirmationDialog.vue'
const showDialog = ref(false)
function handleResult(value: boolean) {
showDialog.value = false
// Do something with `value`
console.log('value', value)
}
</script>
<template>
<ConfirmationDialog :show="showDialog" @result="handleResult">
<template #title="{ emitResult }">
<div class="flex justify-between">
<div class="text-xl font-semibold tracking-wide">
Cool confirmation
</div>
<CloseIcon
class="w-6 cursor-pointer text-pink-600"
@click="emitResult(false)"
/>
</div>
</template>
<template #body>
<div class="py-4 text-sm">Are you super duper sure about THIS?</div>
</template>
</ConfirmationDialog>
</template>
Again, if you use a named slot for the body or the default slot comes down to taste and the type of API you want to provide.
In my case I will provide named slots for all the parts, and a default slot to override the whole component.
What about customizing the dialog buttons?
Another easy one:
Dialog 3
<script setup lang="ts">
import { ref } from 'vue'
import ConfirmationDialog from '@/components/modals/ConfirmationDialog.vue'
const showDialog = ref(false)
function handleResult(value: boolean) {
showDialog.value = false
// Do something with `value`
console.log('value', value)
}
</script>
<template>
<ConfirmationDialog :show="showDialog3" @result="handleResult">
<template #actions="{ emitResult }">
<div class="flex gap-3">
<button
class="border border-red-400 bg-gray-200 px-3 font-semibold uppercase"
@click="emitResult(false)"
>
No way!
</button>
<button
class="border border-cyan-400 bg-gray-200 px-3 font-semibold uppercase"
@click="emitResult(true)"
>
Yes, please
</button>
</div>
</template>
</ConfirmationDialog>
</template>
Note
A first level of customizability could be achieved by passing props to change the title or the confirmation question, but even in this case I'd just provide slots for those parts if needed.
For example:
<slot name="title" :emit-result="emitResult">
<div class="text-lg font-medium">
<slot name="inner-title">Please confirm</slot>
</div>
</slot>
In this way you can change the title and still keep the default styling.
But, what if we want to completely override the design of the confirmation dialog?
WDYT? 🤔
Dialog 4
<script setup lang="ts">
import { ref } from 'vue'
import ConfirmationDialog from '@/components/modals/ConfirmationDialog.vue'
const showDialog = ref(false)
function handleResult(value: boolean) {
showDialog.value = false
// Do something with `value`
console.log('value', value)
}
</script>
<template>
<ConfirmationDialog
v-slot="{ emitResult }"
:show="showDialog"
@result="handleResult"
>
<div class="bg-black p-3 text-lg font-bold text-white">
A very custom title
</div>
<div class="max-w-sm p-4">
<div class="text-sm">
Do you REALLY agree to the terms of the agreement presented in here?
</div>
<div class="flex justify-between pt-5">
<button
class="bg-pink-600 px-4 py-2 text-sm font-bold text-white"
@click="emitResult(false)"
>
NOPE NOPE NOPE
</button>
<button
class="bg-sky-600 px-4 py-2 text-sm font-bold text-white"
@click="emitResult(true)"
>
YEP
</button>
</div>
</div>
</ConfirmationDialog>
</template>
So many possibilities! 🤔 💫
Demo
Have a look at the four dialogs described above:
Result:
Source code
Let me show you the implementation I used for the four demos above.
Here, I present to you src/components/modals/ConfirmationDialog.vue:
<script setup lang="ts">
import BaseModal from '@/components/modals/BaseModal.vue'
defineProps<{
show: boolean
}>()
const emit = defineEmits<{
(e: 'result', value: boolean): void
}>()
// We might want to delegate the process of emitting
// the result to somewhere else, so we define a function
// we can pass through scoped slots
function emitResult(value: boolean) {
emit('result', value)
}
</script>
<template>
<BaseModal :show="show">
<!-- Default slot, when we want to override the whole component -->
<slot :emit-result="emitResult">
<div class="p-4">
<!-- Title slot, we pass the `emitResult` in case
we add a close button or something to it -->
<slot name="title" :emit-result="emitResult">
<div class="text-lg font-medium">Please confirm</div>
</slot>
<!-- Body slot to customize the content -->
<slot name="body">
<div class="py-2 text-sm">Are you sure?</div>
</slot>
<!-- Actions slot, to customize the dialog buttons -->
<slot name="actions" :emit-result="emitResult">
<div class="flex justify-end gap-2">
<button
class="bg-indigo-200 px-3 py-1 font-medium"
@click="$emit('result', false)"
>
Cancel
</button>
<button
class="bg-indigo-200 px-3 py-1 font-medium"
@click="$emit('result', true)"
>
Ok
</button>
</div>
</slot>
</div>
</slot>
</BaseModal>
</template>
That’s it! 🎉
Got comments or feedback?
Follow me on
v-529da0c
|
__label__pos
| 0.732947 |
James Dickens James Dickens - 5 months ago 32
Java Question
Unique Login and SQLiteConstraintException in Android
I have the following code for inserting login information into a SQL Lite database.
public boolean addLogin(Login login) {
SQLiteDatabase Db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(TABLE1_COL1, login.getUser_Name());
values.put(TABLE1_COL2, login.getPassword());
try {
Db.insert(TABLE1_NAME, null, values);
} catch (SQLiteConstraintException ex) {
System.out.println("here");
return false;
}
return true;
}
When I try to test my code with this method executed in my main activity:
//Testing Adding Logins
Login login1 = new Login("having1", "fun1");
Login login2 = new Login("having1", "fun1");
db.addLogin(login1);
db.addLogin(login2);
I get the error:
E/SQLiteDatabase: Error inserting User_Names=having1 Password=fun1
android.database.sqlite.SQLiteConstraintException: UNIQUE constraint failed: Login_Table.User_Names (code 1555)
But isn't this what the try and catch statement is supposed to prevent? I also do not see the
System.out.println("here")
statement. Any insights as to why this is happening much appreciated.
Answer
Then you should use insertOrThrow() method. insert() just returns -1 if failed.
|
__label__pos
| 0.985391 |
首页 WordPress函数大全 load_plugin_textdomain()
load_plugin_textdomain()
2020-05-02 / 4163阅 / 悠然
如何你看完本文还不知道如何使用该函数,可以联系我定制视频教程,50元/个函数,学不会全额退款
load_plugin_textdomain( string $domain, string|false $deprecated = false, string|false $plugin_rel_path = false )
加载插件的翻译字符串。
描述
如果未给出路径,则它将是插件目录的根目录。
.mo文件应基于>
参数
$domain
(string)
(Required)
Unique identifier for retrieving translated strings
$deprecated
(string|false)
(Optional)
Deprecated. Use the $plugin_rel_path parameter instead.
Default value: false
$plugin_rel_path
(string|false)
(Optional)
Relative path to WP_PLUGIN_DIR where the .mo file resides.
Default value: false
返回
(bool) True when textdomain is successfully loaded, false otherwise.
大家谈论
我的见解
|
__label__pos
| 0.553598 |
Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
PerlMonks
Re: Are Perl patterns universal?
by blokhead (Monsignor)
on Nov 09, 2004 at 06:41 UTC ( #406290=note: print w/replies, xml ) Need Help??
in reply to Are Perl patterns universal?
The question is trivial if you allow (?{code}) and (??{code}) constructs, as you can encapsulate arbitrary Perl in the regex.
Do you mean, given an arbitrary Turing machine, can you build a regex $foo such that $x =~ /$foo/ if and only if $x is accepted by the Turing machine? Using just lookaheads/lookbehinds and captures/backreferences, I'd definitely say no. You don't even get all CFLs this way (consider {a^n b^n : n > 0}) but yet you get some CSLs (consider {a^n b a^n b a^n : n > 0}). See also Perl regular expressions vs. RL, CFL, CSL.
A Turing machine must have unbounded memory. A Perl regex using only captures & backreferences has a bounded (linear in the size of input) amount of "memory" about the its input -- the number of captures is fixed when the regular expression is compiled, and each capture contains at most the entire string. Not only that, but the type of access to this memory is very stricly limited: you can only match substrings. In addition, you don't have write access to this memory in any sort of arbitrary fashion (apart from trying a different substring of the input -- which is hardly arbitrary, and could be viewed as just a form of nondeterminism). This is an essential feature for the power of a Turing machine.
Even allowing (??{$re}) just gets you all CFLs (and various closures -- intersection and complement, etc), but doesn't allow for universal behavior because the unbounded memory just isn't there.
To do most "interesting" things with regexes, you'll need a layer of Perl around (or inside) the regex, to do either iterated substitutions, multiple matches, or build a different regex for each input. The last approach is a fun one used by various regex-reductions: Hamiltonian Cycle, 3SAT, N-Queens.
blokhead
Replies are listed 'Best First'.
Re^2: Are Perl patterns universal?
by sleepingsquirrel (Hermit) on Nov 09, 2004 at 17:30 UTC
A Turing machine must have unbounded memory.
Yeah. But I'm encouraged because of the possibility of infinite recursion (from above).
In addition, you don't have write access to this memory in any sort of arbitrary fashion
It is not obvious to me how to do arbitrary memory access in any of the following, but they're all universal.
-- All code is 100% tested and functional unless otherwise noted.
infinite recursion
Recursion with (??{$re}) is only sufficient for context-free matching. Even primitive recursion requires some sort of argument passing. Pretty much the only thing you can "pass" is the current pos of the string, which is way too restricted: You have only a fixed number of values for pos, and a fixed number of regexes you could be "recursing" to, so you can answer the halting problem for these creatures (see footnote below).
cellular automata
Here the grid of automata must be unbounded. Otherwise, you only have a finite number of possible grid configurations (number of automata states ^ size of grid).
Diophantine equations
The number of variables in the equation is fixed, but their values can be arbitrarily large integers. If their values are bounded, then you only have a finite number of combinations to try (possible values ^ number of variables), and you can always halt while determining if a Diophantine equation has a solution.
cyclical tag systems
This is just like an automaton with a queue -- take from the front and add to the back. But you must allow for rules which increase the size of data in the queue, which can happen indefinitely. If you are not allowed to increase the size of the queue data (or if you have an upper limit on the queue size), you only have a finite number of queue contents and thus configurations of the automaton (number of states * (queue alphabet size ^ max queue size))
SK combinators
I don't pretend to have any special insight on SK combinators. But what you have is a very restricted projection operator K, and a very restricted recursion operator S which still encompasses primitive recursion and μ recursion. The μ recursion is the key part of the universality of general recursive functions, as the value being minimized may grow arbitrarily large.
Footnote: when a system has a finite number (say, N) of possible configurations on a given input, you can answer the halting problem for it as follows (where "halting" means entering some special subset of configurations): Simulate it for N steps. If it hasn't reached a halting configuration by then, it must repeat a configuration. Since the next configuration depends only on the previous configuration, it must be in an infinite loop and thus will never reach a halting configuration. Turing machines have an infinite tape and thus an infinite number of possible configurations.
Clearly if you can answer halting queries on a system, it is not universal (Halting Problem).
blokhead
Log In?
Username:
Password:
What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://406290]
help
Chatterbox?
and all is quiet...
How do I use this? | Other CB clients
Other Users?
Others wandering the Monastery: (4)
As of 2017-04-30 06:40 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
I'm a fool:
Results (534 votes). Check out past polls.
|
__label__pos
| 0.773771 |
(ld.info.gz) PHDRS
Info Catalog (ld.info.gz) MEMORY (ld.info.gz) Scripts (ld.info.gz) VERSION
3.8 PHDRS Command
=================
The ELF object file format uses "program headers", also knows as
"segments". The program headers describe how the program should be
loaded into memory. You can print them out by using the `objdump'
program with the `-p' option.
When you run an ELF program on a native ELF system, the system loader
reads the program headers in order to figure out how to load the
program. This will only work if the program headers are set correctly.
This manual does not describe the details of how the system loader
interprets program headers; for more information, see the ELF ABI.
The linker will create reasonable program headers by default.
However, in some cases, you may need to specify the program headers more
precisely. You may use the `PHDRS' command for this purpose. When the
linker sees the `PHDRS' command in the linker script, it will not
create any program headers other than the ones specified.
The linker only pays attention to the `PHDRS' command when
generating an ELF output file. In other cases, the linker will simply
ignore `PHDRS'.
This is the syntax of the `PHDRS' command. The words `PHDRS',
`FILEHDR', `AT', and `FLAGS' are keywords.
PHDRS
{
NAME TYPE [ FILEHDR ] [ PHDRS ] [ AT ( ADDRESS ) ]
[ FLAGS ( FLAGS ) ] ;
}
The NAME is used only for reference in the `SECTIONS' command of the
linker script. It is not put into the output file. Program header
names are stored in a separate name space, and will not conflict with
symbol names, file names, or section names. Each program header must
have a distinct name. The headers are processed in order and it is
usual for them to map to sections in ascending load address order.
Certain program header types describe segments of memory which the
system loader will load from the file. In the linker script, you
specify the contents of these segments by placing allocatable output
sections in the segments. You use the `:PHDR' output section attribute
to place a section in a particular segment. Output Section
Phdr.
It is normal to put certain sections in more than one segment. This
merely implies that one segment of memory contains another. You may
repeat `:PHDR', using it once for each segment which should contain the
section.
If you place a section in one or more segments using `:PHDR', then
the linker will place all subsequent allocatable sections which do not
specify `:PHDR' in the same segments. This is for convenience, since
generally a whole set of contiguous sections will be placed in a single
segment. You can use `:NONE' to override the default segment and tell
the linker to not put the section in any segment at all.
You may use the `FILEHDR' and `PHDRS' keywords after the program
header type to further describe the contents of the segment. The
`FILEHDR' keyword means that the segment should include the ELF file
header. The `PHDRS' keyword means that the segment should include the
ELF program headers themselves. If applied to a loadable segment
(`PT_LOAD'), all prior loadable segments must have one of these
keywords.
The TYPE may be one of the following. The numbers indicate the
value of the keyword.
`PT_NULL' (0)
Indicates an unused program header.
`PT_LOAD' (1)
Indicates that this program header describes a segment to be
loaded from the file.
`PT_DYNAMIC' (2)
Indicates a segment where dynamic linking information can be found.
`PT_INTERP' (3)
Indicates a segment where the name of the program interpreter may
be found.
`PT_NOTE' (4)
Indicates a segment holding note information.
`PT_SHLIB' (5)
A reserved program header type, defined but not specified by the
ELF ABI.
`PT_PHDR' (6)
Indicates a segment where the program headers may be found.
EXPRESSION
An expression giving the numeric type of the program header. This
may be used for types not defined above.
You can specify that a segment should be loaded at a particular
address in memory by using an `AT' expression. This is identical to the
`AT' command used as an output section attribute ( Output Section
LMA). The `AT' command for a program header overrides the output
section attribute.
The linker will normally set the segment flags based on the sections
which comprise the segment. You may use the `FLAGS' keyword to
explicitly specify the segment flags. The value of FLAGS must be an
integer. It is used to set the `p_flags' field of the program header.
Here is an example of `PHDRS'. This shows a typical set of program
headers used on a native ELF system.
PHDRS
{
headers PT_PHDR PHDRS ;
interp PT_INTERP ;
text PT_LOAD FILEHDR PHDRS ;
data PT_LOAD ;
dynamic PT_DYNAMIC ;
}
SECTIONS
{
. = SIZEOF_HEADERS;
.interp : { *(.interp) } :text :interp
.text : { *(.text) } :text
.rodata : { *(.rodata) } /* defaults to :text */
...
. = . + 0x1000; /* move to a new page in memory */
.data : { *(.data) } :data
.dynamic : { *(.dynamic) } :data :dynamic
...
}
Info Catalog (ld.info.gz) MEMORY (ld.info.gz) Scripts (ld.info.gz) VERSION
automatically generated by info2html
|
__label__pos
| 0.956497 |
Midi channel value changed automatically?
Hi !
Etonnant non ?
Hi there,
the MIDI spec only allows channels to have values from 1 to 16 inclusive. Channel 0 is therefore not a valid channel. Similarly, channel 17 would also not be a valid channel.
Rather than throw an error, Sonic Pi simply gives you the closest valid channel. Therefore, if you specify a channel of 0 or lower it will revert to 1 and on the flip side if you specify a channel of 17 or higher it will give you a channel of 16.
I hope that this makes sense :slight_smile:
ok it’s a choice. To me it would be better to send an error otherwise people can keep thinking 0 is a correct value :-).
|
__label__pos
| 0.999743 |
Jump to content
associative array?
Maiskolben
Share
Recommended Posts
Hello Folks,
I just wondering why JS cannot handle associative arrays like php does. Ok, after a while of investigation I stuck with a little code now. Once I've written a simple q&a spamcheck for my contact form in php, hence, I try to adapt it to a js contact form: It's a beautiful pop-up form that costs me 7 dollars, I was just missing that in this script I bought one week ago comes with NO spamcheck functionality, so I would like to build it on my own, maybe with your help?
I know that there are no associative arrays in js. My basement is this code:
var questions = { 'The color of the sky?': 'blue', 'Abraham...': 'lincoln', '10 minus 2, plus 3..': '11', 'Rupert the rednose...': 'reindeer' };
So, next I just need to count the "keys" or array-entries, object parameters, you name it.
Finally I want to shuffle the indexies and return one single question.
To count the "array" I tried this:
var count = 0; // initializefor (var i in questions) { if (questions.hasOwnProperty(i)) { ++count; } }var min = 0; var max = count;alert(count);
...and it works like a charm! My problem is now the indexies e.g. the KEYS of this Object... I don't know how can I shuffle them, and even put out then. Any suggestions to this?
Maybe something in this direction:
var qsingle = shuffle(min, max);alert(qsingle);
But the output is nothing, the script even breaks... But works fine in php! :) Any help would be greatly appreciated!
Edited by Maiskolben
Link to comment
Share on other sites
Those are properties of an object, and you can't shuffle properties of an object. It would probably be better to have an array of question objects, I don't see a reason to put the question text as a property name either:
var questions = [ {q: 'question 1', a: 'answer 1'}, {q: 'question 2', a: 'answer 2'}, ...];
Now questions.length will give you the number of questions, and there are several ways to shuffle an array that you can find. You would access the questions as questions.q or questions.a.
Link to comment
Share on other sites
JSG, is right in that you don't really want to use an object if you need an array. You can do something like this...
var questions = {'The color of the sky?': 'blue','Abraham...': 'Lincoln','10 minus 2, plus 3..': '11','Rupert the rednose...': 'reindeer'};var akeys = Object.keys(questions);
...where akeys is an array of the keys. You might then randomize an index into this array. Each key in the array can obviously access the value (answer) in the questions object. It is more efficient to randomize an index than to randomize an array.
Link to comment
Share on other sites
• 2 weeks later...
Hey guys,
thank you for your response! After a while of try & error and your help, I just have my spamcheck running! :)
I've found this and use it to shuffle my array (thank you JSG!):
function shuffle(array) { var m = array.length, t, i; while (m) { // Pick a remaining element… i = Math.floor(Math.random() * m--); // And swap it with the current element. t = array[m]; array[m] = array[i]; array[i] = t; } return array;} var spamcheck = [ {f: 'Question A', a: 'ANSWER A'}, {f: 'Question B', a: 'ANSWER B'}, {f: 'Question C', a: 'ANSWER C'} ]; shuffle(spamcheck);
next I get the anwser in an hidden field of my formular, base64 decoded:
<input class="kissmebaby" name="chk-hidden" id="chk-hidden" type="hidden" value="'+Base64.encode(spamcheck[1].a)+'" />
And finally I check, if the typed answer matches the right answer, all lowercase:
var rightanswer = document.getElementById("chk-hidden").value;var x = document.getElementById("answerfield").value;var givenanswer = Base64.encode(x.toLowerCase()); // note, BASE64.encode (references to a function)if (givenanswer !== rightanswer) { document.getElementById('answerfield').style.background = "#f9ef9e"; // tell the user there is something wrong... } else { //go to the serverside php-script viá ajax}
and this is it. Thanks for putting me on the right way! :)
PS: this works for me like a charm, may it be there is something "too much" in this shuffle-function, but I'm glad it works now and wouldn't change anything, the performance(s) of the entire script(s) on my website is ok..
PPS: @davej: thank you too, I gladly abandoned the idea to solve this viá the indexies! :)
Edited by Maiskolben
Link to comment
Share on other sites
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new account
Sign in
Already have an account? Sign in here.
Sign In Now
Share
×
×
• Create New...
|
__label__pos
| 0.723858 |
Android EditText Cursor Colour appears to be white
If you have created a custom Android EditText class and you see that the color of the Cursor appears to be white you can change it using textCursorDrawable attribute.
You need to set android:textCursorDrawable value as @null, this will set the cursor color as that of the Text.
Do note that android:textCursorDrawable requires minimum SDKI level to be 12 or above.
Example
<EditText
android:id="@+id/view"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="top|left"
android:lineSpacingExtra="7dp"
android:textCursorDrawable="@null"
android:textSize="20sp"
android:textColor="#010101"
android:text="Hello"
android:background="@drawable/border"
android:scrollbars="vertical">
</EditText>
Change EditText Cursor Color
Change EditText Cursor Color
Recent Posts:
Code2care is an initiative to publish and share varied knowledge in programming and technical areas gathered during day-to-day learnings and development activities.
Students and Software Developers can leverage this portal to find solutions to their various queries without re-inventing the wheel by referring to our easy to understand posts. Technical posts might include Learnings, Video Tutorials, Code Snippets, How Tos, Blogs, Articles, etc.
|
__label__pos
| 0.854386 |
Query
Create a query
A query lets you select a target according to criteria. You can associate a segment code to the query result and insert additional data into it.
For more information on query samples, refer to this this section.
For more on using and managing additional data, refer to Add data.
The Edit query… link lets you define the targeting type, the restrictions, and the selection criteria for the population in the following way:
1. Select the targeting and filtering dimension. By default, the target is selected from the recipients. The list of restriction filters is the same as those used for delivery targeting.
The targeting dimension coincides with the type of element we will be working on, e.g. the population targeted by the operation.
The filtering dimension enables to collect these elements, e.g. information related to the targeted person (contracts, full and final settlements, etc.).
For more on this, refer to Targeting and filtering dimensions.
A query can be based on data from the inbound transition, if necessary, by selecting Temporary schema when choosing targeting and filtering dimensions.
2. Define the populations using the wizard. The fields to be entered can differ according to the type of target. You can preview the targeted population with your current criteria using the Preview tab.
For more on creating and using filters or queries, refer to this .
3. If you have selected Filtering conditions at step 1 or using the Filters > Advanced filter… option, then you will have to manually add filtering criteria later on.
You can also add data grouping conditions by checking the corresponding box. To do this, the filtering dimension must be different to the query’s targeting dimension. For more information on grouping, refer to this section.
You can also add more criteria by using the Expression builder and combining it with the logical options AND, OR, and EXCEPT. You can then preview the ** .
Save your filter if you wish to re-use it later.
Add data
The additional columns let you collect additional information on the targeted population, e.g. contract numbers, subscriptions to newsletters or origin. This data can be stored in the Adobe Campaign database or in an external database.
The Add data… link lets you select the additional data to collect.
Start by selecting the type of data to add:
• Select Data linked to the filtering dimension to select the data in the Adobe Campaign database.
• Select External data to add data from an external database. This option is only available if you have purchased the Federated Data Access option. For more on this, refer to Access an external database (FDA).
• Select the An offer proposition option to add a set of columns which let you store the best proposition generated by the offer engine. This option is only available if you have purchased the Interaction module.
If no optional module is installed on the platform, this stage is not displayed. You will be taken straight to the next stage.
To add data from the Adobe Campaign database:
1. Select the type of data you want to add. This can be data belonging to the filtering dimension or data stored in linked tables.
2. If the data belongs to the query’s filtering dimension, simply select it in the list of available fields to display it in the output columns.
You can add:
• A field computed based on data taken from the targeted population or an aggregate (number of pending purchases within the last month, average amount of a receipt, etc.). For an example, go to Select data.
• A new field, created using the Add button to the right of the list of output columns.
You can also add a collection of information, for example a list of contracts, the last 5 deliveries, etc. Collections coincide with fields that can have multiple values for the same profile (1-N relationship). For more on this, refer to Edit additional data.
To add a collection of information linked to a targeted population:
1. At the first step of the wizard, select the Data linked to the filtering dimension option:
2. Select the table which contains the information you want to collect and click Next.
3. If necessary, specify the number of elements of the collection that you want to keep by selecting one of the values in the Data collected field. By default, all the lines of the collection are recovered then filtered according to the conditions specified at the following step.
• If a single element of the collection coincides with the filtering conditions for this collection, select Single row in the Data collected field.
IMPORTANT
This mode optimizes the SQL query generated thanks to a direct juncture on the collection elements.
If the initial condition is not respected, the result may be flawed (missing or overlapping lines).
• If you choose to recover several lines (Limit the line count) you can specify the number of lines to collect.
• If the collected columns contain aggregates, for example the number of failures declared, average expenditure on a site, etc. you can use the Aggregates value.
4. Specify the sub-selection of the collection.
5. If you have selected the Limit the line count option, define the order in which the collected data is to be filtered. Once the number of lines collected is more than the number of lines that you specified to keep, the filtering order allows you to specify which lines to keep.
Example: Targeting on simple recipient attributes
In the following example, the query seeks to identify men aged between 18 and 30 and living in France. This query will be used in a workflow that aims to make them an exclusive offer for example.
NOTE
Additional query samples are presented in this section.
1. Name your query then select the Edit query… link.
2. Select Filtering conditions in the list of types of filter available.
3. Enter the different criteria for the proposed target. Here criteria are combined using the AND option. To be included in the selection, the recipients will have to fulfill following four conditions:
• Recipients whose title is “Mr” (can also be found using the Gender field and selecting Male as a value).
• Recipients aged under 30.
• Recipients aged over 18.
• Recipients living in France.
You can view the SQL matching your criteria combination:
4. You can check your criteria is correct by previewing the recipients that match your query in the relevant tab:
5. Save your filters so that you can use them again at a later date by clicking Finish > OK.
6. Continue editing your workflow by adding other activities to it. Once it has been launched and the previous query step finished, the number of recipients found will be displayed. You can display further details using the mouse pop-up menu (right click the transition > Display the target…).
Output parameters
• tableName
• schema
• recCount
This set of three values identifies the population targeted by the query. tableName is the name of the table that records the target identifiers, schema is the schema of the population (usually nms:recipient) and recCount is the number of elements in the table.
This value is the schema of the work table. This parameter is valid for all transitions with tableName and schema.
Optimizing your queries
The section below provides best practices to optimize the queries running on Adobe Campaign to limit the workload on the database and improve user experience.
Joins and indexes
• Efficient queries rely on indexes.
• Use an index for all joins.
• Defining links on the schema will determine the join conditions. The linked table should have an unique index on the primary key and the join should be on this field.
• Perform joins by defining keys on numeric fields instead of string fields.
• Avoid performing outer joins. Whenever possible, use the Zero ID record to achieve outer join functionality.
• Use the correct data type for joins.
Ensure that the where clause is the same type as the field.
A common mistake is: iBlacklist='3' where iBlacklist is a numeric field, and 3 signifies a text value.
Make sure you know what the execution plan of your query will be. Avoid full table scans, especially for real-time queries or near real-time queries running every minute.
For more on this, depending on your Campaign version, refer to these sections:
!
Campaign v8 documentation
Functions
• Beware of functions like Lower(...). When the Lower function is used, the Index is not used.
• Check queries using the “like” instruction or the “upper” or “lower” instructions carefully. Apply “Upper” on the user input, not on the database field.
For more on functions, refer to .
Filtering dimensions
Use the query’s filtering dimension instead of using the “exists such as” operator.
In queries, “exists such as” conditions in filters are not efficient. They are the equivalent of a sub-query in SQL:
select iRecipientId from nmsRecipient where iRecipientId IN (select iRecipientId from nmsBroadLog where (...))
The best practice is to use the query’s filtering dimension instead:
The equivalent of the filtering dimension in SQL is the inner join:
select iRecipientId from nmsRecipient INNER JOIN nmsBroadLog ON (...)
For more on filtering dimensions, refer to this section.
Architecture
• Build a development platform with similar volumes, parameters, and architecture as the production platform.
• Use the same values for the development and production environments. As much as possible, use the same:
• Operating System,
• Version,
• Data,
• Application,
• Volumes.
NOTE
A feature that works in a development environment may not work in a production environment where the data may be different. Try to identify the main differences in order to anticipate risks and to prepare solutions.
• Make configurations that match the target volumes. Large volumes require specific configurations. A configuration that worked for 100,000 recipients may not work for 10,000,000 recipients.
Consider how the system will scale when it goes live. Just because something works on a small scale does not mean that it will be suitable with greater volumes. Testing should be done with similar volumes to the volume in production. You should also evaluate the effect of changes in volumes (number of calls, size of the database) at peak hours, peak days, and across the life of the project.
On this page
|
__label__pos
| 0.711248 |
WP_HTML_Processor::get_breadcrumbs()publicWP 6.4.0
Computes the HTML breadcrumbs for the currently-matched node, if matched.
Breadcrumbs start at the outermost parent and descend toward the matched element. They always include the entire path from the root HTML node to the matched element.
Метод класса: WP_HTML_Processor{}
Хуков нет.
Возвращает
Строку[]|null. Array of tag names representing path to matched node, if matched, otherwise NULL.
Использование
$WP_HTML_Processor = new WP_HTML_Processor();
$WP_HTML_Processor->get_breadcrumbs();
Список изменений
С версии 6.4.0 Введена.
Код WP_HTML_Processor::get_breadcrumbs() WP 6.6.1
public function get_breadcrumbs() {
$breadcrumbs = array();
foreach ( $this->state->stack_of_open_elements->walk_down() as $stack_item ) {
$breadcrumbs[] = $stack_item->node_name;
}
if ( ! $this->is_virtual() ) {
return $breadcrumbs;
}
foreach ( $this->element_queue as $queue_item ) {
if ( $this->current_element->token->bookmark_name === $queue_item->token->bookmark_name ) {
break;
}
if ( 'context-node' === $queue_item->token->bookmark_name ) {
break;
}
if ( 'real' === $queue_item->provenance ) {
break;
}
if ( WP_HTML_Stack_Event::PUSH === $queue_item->operation ) {
$breadcrumbs[] = $queue_item->token->node_name;
} else {
array_pop( $breadcrumbs );
}
}
if ( null !== parent::get_token_name() && ! parent::is_tag_closer() ) {
array_pop( $breadcrumbs );
}
// Add the virtual node we're at.
if ( WP_HTML_Stack_Event::PUSH === $this->current_element->operation ) {
$breadcrumbs[] = $this->current_element->token->node_name;
}
return $breadcrumbs;
}
|
__label__pos
| 0.990761 |
Ödüllü reklamlar
Ödüllü reklamlar video reklamlarla, oynatılabilir reklamlarla ve anketlerle etkileşimde bulunan kullanıcıları uygulama içi öğelerle ödüllendirmenize olanak tanır.
Ön koşullar
Her zaman test reklamlarıyla test etme
Uygulamalarınızı oluştururken ve test ederken canlı, üretim reklamları yerine test reklamlarını kullandığınızdan emin olun. Aksi takdirde hesabınız askıya alınabilir.
Test reklamlarını yüklemenin en kolay yolu, Android ödüllü reklamlara özel test reklam birimi kimliğimizi kullanmaktır:
ca-app-pub-3940256099942544/5224354917
Bu kod, her istek için test reklamı döndürecek şekilde özel olarak yapılandırılmıştır. Kodlama, test etme ve hata ayıklama sırasında bu reklam öğesini kendi uygulamalarınızda kullanabilirsiniz. Uygulamanızı yayınlamadan önce bu kimliği kendi reklam birimi kimliğinizle değiştirdiğinizden emin olmanız yeterlidir.
Mobile Ads SDK'sının test reklamlarının nasıl çalıştığı hakkında daha fazla bilgi için Reklamları Test Etme bölümüne bakın.
加载激励广告对象
RewardedAd 类调用静态 load() 方法并传入 RewardedAdLoadCallback 可加载激励广告。这通常在 ActivityonCreate() 方法中完成。请注意,与其他广告格式加载回调一样,RewardedAdLoadCallback 会利用 LoadAdError 提供较高保真度的错误详情。
Java
import com.google.android.gms.ads.rewarded.RewardedAd;
public class MainActivity extends Activity {
private RewardedAd rewardedAd;
private final String TAG = "MainActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
AdRequest adRequest = new AdRequest.Builder().build();
RewardedAd.load(this, "ca-app-pub-3940256099942544/5224354917",
adRequest, new RewardedAdLoadCallback() {
@Override
public void onAdFailedToLoad(@NonNull LoadAdError loadAdError) {
// Handle the error.
Log.d(TAG, loadAdError.toString());
rewardedAd = null;
}
@Override
public void onAdLoaded(@NonNull RewardedAd ad) {
rewardedAd = ad;
Log.d(TAG, "Ad was loaded.");
}
});
}
}
Kotlin
class MainActivity : AppCompatActivity() {
private var rewardedAd: RewardedAd? = null
private final var TAG = "MainActivity"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
var adRequest = AdRequest.Builder().build()
RewardedAd.load(this,"ca-app-pub-3940256099942544/5224354917", adRequest, object : RewardedAdLoadCallback() {
override fun onAdFailedToLoad(adError: LoadAdError) {
Log.d(TAG, adError?.toString())
rewardedAd = null
}
override fun onAdLoaded(ad: RewardedAd) {
Log.d(TAG, "Ad was loaded.")
rewardedAd = ad
}
})
}
}
设置 FullScreenContentCallback
FullScreenContentCallback 会处理与显示 RewardedAd 相关的事件。在显示 RewardedAd 之前,请务必按如下方式设置回调:
Java
rewardedAd.setFullScreenContentCallback(new FullScreenContentCallback() {
@Override
public void onAdClicked() {
// Called when a click is recorded for an ad.
Log.d(TAG, "Ad was clicked.");
}
@Override
public void onAdDismissedFullScreenContent() {
// Called when ad is dismissed.
// Set the ad reference to null so you don't show the ad a second time.
Log.d(TAG, "Ad dismissed fullscreen content.");
rewardedAd = null;
}
@Override
public void onAdFailedToShowFullScreenContent(AdError adError) {
// Called when ad fails to show.
Log.e(TAG, "Ad failed to show fullscreen content.");
rewardedAd = null;
}
@Override
public void onAdImpression() {
// Called when an impression is recorded for an ad.
Log.d(TAG, "Ad recorded an impression.");
}
@Override
public void onAdShowedFullScreenContent() {
// Called when ad is shown.
Log.d(TAG, "Ad showed fullscreen content.");
}
});
Kotlin
rewardedAd?.fullScreenContentCallback = object: FullScreenContentCallback() {
override fun onAdClicked() {
// Called when a click is recorded for an ad.
Log.d(TAG, "Ad was clicked.")
}
override fun onAdDismissedFullScreenContent() {
// Called when ad is dismissed.
// Set the ad reference to null so you don't show the ad a second time.
Log.d(TAG, "Ad dismissed fullscreen content.")
rewardedAd = null
}
override fun onAdFailedToShowFullScreenContent(adError: AdError?) {
// Called when ad fails to show.
Log.e(TAG, "Ad failed to show fullscreen content.")
rewardedAd = null
}
override fun onAdImpression() {
// Called when an impression is recorded for an ad.
Log.d(TAG, "Ad recorded an impression.")
}
override fun onAdShowedFullScreenContent() {
// Called when ad is shown.
Log.d(TAG, "Ad showed fullscreen content.")
}
}
展示广告
展示激励广告时,您将使用 OnUserEarnedRewardListener 对象处理奖励事件。
Java
if (rewardedAd != null) {
Activity activityContext = MainActivity.this;
rewardedAd.show(activityContext, new OnUserEarnedRewardListener() {
@Override
public void onUserEarnedReward(@NonNull RewardItem rewardItem) {
// Handle the reward.
Log.d(TAG, "The user earned the reward.");
int rewardAmount = rewardItem.getAmount();
String rewardType = rewardItem.getType();
}
});
} else {
Log.d(TAG, "The rewarded ad wasn't ready yet.");
}
Kotlin
rewardedAd?.let { ad ->
ad.show(this, OnUserEarnedRewardListener { rewardItem ->
// Handle the reward.
val rewardAmount = rewardItem.amount
val rewardType = rewardItem.type
Log.d(TAG, "User earned the reward.")
})
} ?: run {
Log.d(TAG, "The rewarded ad wasn't ready yet.")
}
[可选] 验证服务器端验证 (SSV) 回调
对于需要服务器端验证回调中额外数据的应用,应使用激励广告的自定义数据功能。在激励广告对象上设置的任何字符串值都将传递给 SSV 回调的 custom_data 查询参数。如果未设置自定义数据值,custom_data 查询参数值不会出现在 SSV 回调中。
以下代码示例演示了如何在请求广告之前对激励广告对象设置自定义数据。
Java
RewardedAd.load(MainActivity.this, "ca-app-pub-3940256099942544/5354046379",
new AdRequest.Builder().build(), new RewardedAdLoadCallback() {
@Override
public void onAdLoaded(RewardedAd ad) {
Log.d(TAG, "Ad was loaded.");
rewardedAd = ad;
ServerSideVerificationOptions options = new ServerSideVerificationOptions
.Builder()
.setCustomData("SAMPLE_CUSTOM_DATA_STRING")
.build();
rewardedAd.setServerSideVerificationOptions(options);
}
@Override
public void onAdFailedToLoad(LoadAdError loadAdError) {
Log.d(TAG, loadAdError.toString());
rewardedAd = null;
}
});
Kotlin
RewardedAd.load(this, "ca-app-pub-3940256099942544/5354046379",
AdRequest.Builder().build(), object : RewardedAdLoadCallback() {
override fun onAdLoaded(ad: RewardedAd) {
Log.d(TAG, "Ad was loaded.")
rewardedInterstitialAd = ad
val options = ServerSideVerificationOptions.Builder()
.setCustomData("SAMPLE_CUSTOM_DATA_STRING")
.build()
rewardedAd.setServerSideVerificationOptions(options)
}
override fun onAdFailedToLoad(adError: LoadAdError) {
Log.d(TAG, adError?.toString())
rewardedAd = null
}
})
如果您要设置自定义奖励字符串,则必须在展示广告之前设置。
SSS
Başlatma çağrısı için zaman aşımı var mı?
10 saniye sonra, uyumlulaştırma ağı başlatma işlemini henüz tamamlamamış olsa bile Google Mobile Ads SDK'sı OnInitializationCompleteListener özelliğini çağırır.
Bazı uyumlulaştırma ağları başlatma geri çağırma işlemini aldığımda hazır değilse ne olur?
OnInitializationCompleteListener öğesinin geri çağırma içerisine bir reklam yüklemenizi öneririz. Bir uyumlulaştırma ağı hazır olmasa bile, Google Mobile Ads SDK'sı bu ağdan reklam istemeye devam eder. Dolayısıyla bir uyumlulaştırma ağı, zaman aşımı süresinden sonra ilk kullanıma hazırlamayı bitirirse bu oturumda gelecekteki reklam isteklerinde hizmet vermeye devam edebilir.
Uygulama oturumunuz boyunca MobileAds.getInitializationStatus() yöntemini çağırarak tüm bağdaştırıcıların başlatma durumunu yoklamaya devam edebilirsiniz.
Belirli bir uyumlulaştırma ağının neden hazır olmadığını nasıl anlayabilirim?
AdapterStatus.getDescription(), bir bağdaştırıcının neden reklam istekleri sunmaya hazır olmadığını açıklar.
onUserEarnedReward() geri çağırması her zaman onAdDismissedFullScreenContent() geri çağırmasından önce mi çağrılıyor?
Google Ads için onUserEarnedReward() çağrılarının tümü onAdDismissedFullScreenContent() tarihinden önce gerçekleşir. Uyumlulaştırma ile yayınlanan reklamlar için geri çağırma sırasını üçüncü taraf reklam ağı SDK'sının uygulaması belirler. Ödül bilgileriyle birlikte tek bir yakın geri çağırma sağlayan reklam ağı SDK'ları için uyumlulaştırma bağdaştırıcısı, onAdDismissedFullScreenContent() öncesinde onUserEarnedReward() yöntemini çağırır.
GitHub'daki örnekler
Sonraki adımlar
Aşağıdaki konuları inceleyin:
|
__label__pos
| 0.605421 |
You are looking at the documentation of a prior release. To read the documentation of the latest release, please visit here.
REST Backend
Stash supports restic’s REST Server as a backend. This tutorial will show you how to use this backend.
In order to use REST Server as backend, you have to create a Secret and a Repository object pointing to the desired REST Server address.
Create Storage Secret
To configure storage secret for this backend, following secret keys are needed:
KeyTypeDescription
RESTIC_PASSWORDRequiredPassword that will be used to encrypt the backup snapshots.
REST_SERVER_USERNAMEOptionalUsername for basic authentication in the REST server.
REST_SERVER_PASSWORDOptionalPassword for basic authentication in the REST Server
CA_CERT_DATAoptionalCA certificate used by storage backend. This can be used to pass the root certificate that has been used to sign the server certificate of a TLS secured REST Server.
Create storage secret as below,
$ echo -n 'changeit' > RESTIC_PASSWORD
$ echo -n '<your-rest-server-username>' > REST_SERVER_USERNAME
$ echo -n '<your-rest-server-password>' > REST_SERVER_PASSWORD
$ kubectl create secret generic -n demo rest-secret \
--from-file=./RESTIC_PASSWORD \
--from-file=./REST_SERVER_USERNAME \
--from-file=./REST_SERVER_PASSWORD
secret/rest-secret created
Create Repository
Now, you have to create a Repository crd. You have to provide the storage secret that we have created earlier in spec.backend.storageSecretName field.
Following parameters are available for rest backend,
ParameterTypeDescription
rest.urlRequiredURL of the REST Server along with an optional path inside the server where backed up snapshot will be stored.
Below, the YAML of a sample Repository crd that uses a REST Server as a backend.
apiVersion: stash.appscode.com/v1alpha1
kind: Repository
metadata:
name: rest-repo
namespace: demo
spec:
backend:
rest:
url: http://rest-server.demo.svc:8000/stash-backup-demo
storageSecretName: rest-secret
Create the Repository we have shown above using the following command,
$ kubectl apply -f https://github.com/stashed/docs/raw/v2023.10.9/docs/guides/backends/rest/examples/rest.yaml
repository/rest-repo created
Now, we are ready to use this backend to backup our desired data using Stash.
Next Steps
• Learn how to use Stash to backup workloads data from here.
• Learn how to use Stash to backup databases from here.
• Learn how to use Stash to backup stand-alone PVC from here.
|
__label__pos
| 0.520445 |
Pig Latin - Some problem with my code
Pig Latin - Some problem with my code
0
#1
Getting page as
Unable to continue with next topics nor click any of the options in code camp page, page got stuck.
#2
#3
Would you mind copying/pasting your code into your next reply? It would make it easier for us to test out your code.
To enter a code block into the forum, precede it with a line of three backticks and follow it with a line of three backticks to make easier to read. See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.
EDIT: If it is freezing upon running, then add ?run=disabled to the end of the challenge url to prevent running your code.
#5
getting this error page after adding ?run=disabled to the url
#6
My code -
function translatePigLatin(str)
{
if(!isConsonent(str.charAt(0)))
str.concat(“way”);
else
{
strarr=str.split("");
while(isConsonent(str[0])))
{
st=strarr.slice(1);
strarr.push(st);
}
strarr.join("");
strarr.concat(“ay”);
}
function isConsonent(char)
{
return ![aeiou]/.test(char);
}
return str;
}
translatePigLatin(“consonent”);
#7
I have to run some errands, but I will be back on later today. Hopefully, someone else will be able to assist you.
|
__label__pos
| 0.720295 |
You are implementing an application that uses Entity Framework. You load an Order entity by querying the Orders property of a strongly typed ObjectContext. After you modify the Order entity, you need to compare a current property value with the cached original property value.
What should you do?
Posted by Rajkatie on 8/31/2012 | Category: ADO.NET Interview questions | Views: 2556 | Points: 40
Select from following answers:
1. Query the ObjectStateManager object given by the ObjectContext's ObjectStateManager property.
2. Call the TryGetObjectByKey method on the ObjectContext.
3. Call the Attach method on the ObjectContext.
4. All Above
Show Correct Answer
Source: MeasureUp.com | | Alert Moderator
Comments or Responses
Login to post response
|
__label__pos
| 0.981273 |
next up previous contents
Next: Creating and accessing fixed Up: Fixed size matrices and Previous: Fixed size matrices and Contents
Fixed size vectors
Vectors of sizes two, three and four are represented by specific structures in Gandalf. The structure and function definitions are nearly identical, so we shall only describe the workings of 3-vectors. To use 3-vectors include the header file
#include <gandalf/linalg/3vector.h>
for double precision, or
#include <gandalf/linalg/3vectorf.h>
for single precision 3-vectors. A double precision 3-vector is defined as
typedef struct Gan_Vector3
{
double x, y, z;
} Gan_Vector3, Gan_Vector3_d
and a single precision 3-vector as
typedef struct Gan_Vector3_f
{
float x, y, z;
} Gan_Vector3_f;
Most of the routines below return a pointer to the result vector/matrix. This may be used as an argument to another routine, although care must be taken with macros as regards multiple evaluation. The routines are very safe, because everything using fixed size vectors & matrices can be written to involve only automatic variables with no dynamic allocation, and the only failure modes are arithmetic overflow (Gandalf does not check for this). The few exceptions are noted in the text.
Subsections
2006-03-17
|
__label__pos
| 0.948087 |
Hybrid Approaches to Large File Sharing
The vitality of numerous businesses hinges on the seamless exchange of large files. In a world where geographical boundaries have virtually dissolved, global collaboration has become the new standard.
The ability to efficiently share these substantial files has emerged as the linchpin for fostering collaboration, enhancing productivity, and ensuring the timely completion of projects. In the modern business landscape, information flows rapidly and across diverse locations.
Teams from different corners of the world often need to collaborate on projects, and the exchange of substantial files has become a fundamental aspect of this global connectivity.
Combining Cloud and On-Premises Solutions for Efficiency
To optimize large file sharing, first, assess your organization’s specific needs. This step ensures that your hybrid approach aligns seamlessly with your operational requirements.
Hybrid file sharing combines the strengths of cloud-based and on-premises solutions:
• Cloud-based solutions provide global file access with an internet connection.
• On-premises solutions offer control over security and compliance.
For users, seamless access and sharing across storage locations are vital. Application Programming Interfaces (APIs) facilitate efficient data exchange between systems, offering synchronization, automated backups, and advanced encryption. This integration ensures your hybrid file sharing operates as a unified and coordinated system.
Hybrid Security ─ Ensuring Data Protection in Hybrid File Sharing
Hybrid file sharing balances flexibility with robust security, anchored by two pillars: data encryption and access control. Encryption ensures data remains inaccessible to unauthorized users during transit and at rest, requiring the correct keys for access. Access control, especially through role-based access (RBAC), limits data access to those with legitimate needs.
To maintain security and integrity, continuous monitoring and audits are vital. Real-time monitoring swiftly detects suspicious activities, enabling rapid responses to potential threats. Regular audits proactively ensure compliance and security, reviewing protocols, access controls, encryption, and training programs. Active monitoring and auditing anticipate and prevent security issues, safeguarding data throughout its journey.
Source: learn.g2.com
Tailoring Security Measures
In the realm of hybrid file sharing, the one-size-fits-all approach falls conspicuously short. To harness the full potential of this approach, the security measures must be meticulously tailored to your business’s unique needs.
A crucial step in this journey is the identification and mitigation of potential risks endemic to your industry. This empowers you to tailor your security protocols, aligning them seamlessly with your organizational objectives and regulatory obligations.
Developer Collaboration ─ Creating Custom Solutions
Working with skilled developers offers tailored file sharing solutions that align perfectly with your organization’s needs. These developers design custom applications and integrations, seamlessly connecting your cloud and on-premises systems for efficient and secure data transfers. They can also create personalized security features, such as encryption protocols or compliance monitoring tools.
A successful partnership with developers relies on clear communication and a deep understanding of your organization’s requirements. With expertise in both cloud and on-premises technologies, developers can create solutions that capitalize on each platform’s strengths while addressing vulnerabilities.
Navigating Regulatory and Compliance Challenges
In the complex web of international data exchange, navigating through the myriad of regulatory and compliance challenges is paramount. As organizations extend their reach across borders, they inherently encounter a diverse array of data protection laws, such as the General Data Protection Regulation (GDPR) in Europe or the California Consumer Privacy Act (CCPA) in the United States.
These regulations impose stringent requirements on data protection, storage, and transfer, necessitating that hybrid file sharing systems are adeptly configured to comply with varied jurisdictional mandates. Moreover, establishing a robust data governance framework that inherently supports adherence to global data protection standards not only safeguards against legal repercussions but also fortifies customer trust and enhances brand reputation.
Source: europarl.europa.eu
Leveraging Artificial Intelligence and Machine Learning
Incorporating Artificial Intelligence (AI) and Machine Learning (ML) into hybrid file sharing can exponentially enhance the system’s efficiency and security. By leveraging AI and ML, organizations can develop predictive analytics to optimize data transfer routes, enhance security protocols through anomaly detection, and automate data management tasks, such as backup, recovery, and archival, based on usage patterns and organizational needs.
Implementing intelligent algorithms helps in smartly allocating resources, thereby reducing costs and energy consumption, while ML algorithms continuously learn and adapt to evolving data usage patterns and potential cybersecurity threats.
The synergistic integration of AI and ML with hybrid file sharing solutions thus propels organizations towards realizing a future where large file-sharing is not only secure and efficient but also inherently intelligent and adaptive to emerging organizational needs and global trends.
Ensuring File Strategy Scalability and Flexibility
A successful hybrid file sharing strategy needs to smoothly adjust to changes in your organization’s size, structure, and strategic objectives. Scalability is the key to ensuring that your file sharing solution can handle increasing data volumes and users without any impact on performance. Cloud components offer the flexibility to scale both horizontally and vertically, catering to growing demands. On the other hand, your on-premises infrastructure can be expanded or upgraded as needed to keep up with surges in demand.
As your organization embraces new technologies or responds to shifting industry trends, it’s crucial for your hybrid approach to remain flexible. This evolution may involve integrating new solutions, strengthening security measures, or migrating data to more suitable platforms. Flexibility is the cornerstone that ensures your file sharing solution continues to support, rather than hinder, your organization’s growth journey.
Source: redswitches.com
In Conclusion
In conclusion, customization plays a pivotal role in strengthening hybrid file sharing strategies. It ensures that security measures are tailored to meet your organization’s specific needs, fosters collaboration with developers to create bespoke solutions, and guarantees scalability and flexibility. Embracing this journey allows organizations to unlock the full potential of hybrid file sharing, driving productivity, collaboration, and data security into the ever-evolving landscape of the digital world.
Furthermore, navigating through the complex terrains of regulatory compliance and integrating advanced technologies such as AI and ML not only elevate the robustness of file sharing systems but also future-proof them against evolving challenges and opportunities.
The harmonization of strategic developer collaborations, technological innovations, and an adherence to global compliance standards cultivates a resilient and agile environment, where data flows securely and efficiently across global corridors. By embedding these principles, businesses not only safeguard their operational continuity and data integrity but also fuel the collaborative spirit that is intrinsic to innovation and growth in the digital era.
|
__label__pos
| 0.612015 |
Android Intune COBE Device, deregister current user without wiping the device
Occasional Contributor
Hey guys,
we have a problem with some Android full managed company owned devices. The problem is, that we changed some users, so their UPN isnt the same anymore.
Let me explain my problem step by step:
1. The user "[email protected]" registered his android phone as a full managed company device with our intune. That went fine, and the registration was successfull.
2. We changed the upn suffix of that user, because we had a mail and domain migration going on.
3. So the new upn is "[email protected]"
So now I dont get it to work, that I change this user in his android device. If I want to add his new Mail Account in the Outlook App, it wont let me. It says "you already got a business account running"
Do I really have to wipe the entire device now and re enroll it?
Thank you
0 Replies
|
__label__pos
| 0.630265 |
shawnXiao shawnXiao - 2 years ago 158
Javascript Question
Is there a ternary operator in handlebars.js?
In Handlebars, is there a ternary operator? I don't mean
if else
; I mean like
a == true ? "a" : "b"
.
Answer Source
You can build your own helper in handlbars if you really want to. Something like ternary(a==true, "a", "b"). For more information on that see the documentation. The idea from m90 is not the idea behind handlebars. The idea is to not have explicit code in your templates, only calls to helpers and objects.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download
|
__label__pos
| 0.630029 |
Haven't seen a reply to this yet, so I'll start the bidding at 2¢.
Generally, I like the idea of using Annotated in this fashion. I'm currently using it for expressing validation rules and hints about how parameters are handled in HTTP requests. Handy!
If = field(...) weren't already established, I'd say it should be as an annotated value instead of an assignment. Since = field(...) pattern is well established, I'm not so sure what the value would be of changing this in dataclass now.
Paul
On Sat, 2021-04-03 at 20:57 +0000, [email protected] wrote:
typing.Annotated could be used to build dataclasses. Using Annotated will allow libraries to add functionality to a dataclass without having to change dataclass creation or behavior. The example below shows how a dataclass could be implemented. It continues the example of struct2 shown in pep593. From a dataclass point of view, the Sample and AnnotatedSample would be equivalent.
```python
@dataclass
class Sample:
a: int
b: int
c: int = field(default=5)
d: int = 10
e: int = field(default=10)
@packed
@dataclass
class AnnotatedSample:
a: Annotated[int, ctype("I")]
b: int
c: Annotated[int, field(default=5), ctype("I")]
d: Annotated[int, ctype("h")] = 10
e: Annotated[int, ctype("h")] = field(default=10)
out_bytes = struct2.pack(AnnotatedSample())
```
When parsing the Annotated parameters, the dataclass decorator will only look at the type parameter and ```field``` parameter if present. If not Annotated, it falls back to existing behavior.
Let me know what you think.
Thanks!
_______________________________________________
Python-ideas mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at https://mail.python.org/archives/list/[email protected]/message/TI4ZHEJSP5NWPO4NHR2EKNZQYLZMGR2J/
Code of Conduct: http://python.org/psf/codeofconduct/
|
__label__pos
| 0.870114 |
One-to-one Matching on Confounders Using Python Package Causal Inference. Bias-adjusted one-to-one and one-to-many matching on Confounders in python
One-to-one Matching on Confounders Using Python Package Causal Inference
One-to-one matching on confounders takes a sample in the treatment group, and finds a similar sample in the non-treatment group based on the confounder similarities. The goal of matching is to create a synthetic control group that is comparable to the treatment group.
In this tutorial, we will talk about how to do one-to-one matching on confounders using the Python CausalInference package. You will learn:
• How to do one-to-one matching on confounders?
• How to adjust the bias in one-to-one confounder matching?
• How to expand one-to-one matching to one-to-many matching?
Resources for this post:
One-to-one Matching on Confounders in Python – GrabNGoInfo.com
Let’s get started!
Step 1: Install and Import Libraries
In step 1, we will install and import libraries.
Firstly, let’s install dowhy for dataset creation and causalinference for confounders matching.
# Install dowhy
!pip install dowhy
# Install causal inference
!pip install causalinference
After the installation is completed, we can import the libraries.
• The datasets is imported from dowhy for dataset creation.
• pandas and numpy are imported for data processing.
• CausalModel is imported from the causalinference package for confounders matching.
# Package to create synthetic data for causal inference
from dowhy import datasets
# Data processing
import pandas as pd
import numpy as np
# Causal inference
from causalinference import CausalModel
Step 2:Create Dataset
In step 2, we will create a synthetic dataset for the causal inference.
• Firstly, we set a random seed using np.random.seed to make the dataset reproducible.
• Then a dataset with the true causal impact of 10, four confounders, 10,000 samples, a binary treatment variable, and a continuous outcome variable is created.
• After that, we created a dataframe for the data. In the dataframe, the columns W0, W1, W2, and W3 are the four confounders, v0 is the treatment indicator, and y is the outcome.
# Set random seed
np.random.seed(42)
# Create a synthetic dataset
data = datasets.linear_dataset(
beta=10,
num_common_causes=4,
num_samples=10000,
treatment_is_binary=True,
outcome_is_binary=False)
# Create Dataframe
df = data['df']
# Take a look at the data
df.head()
Causal Inference Data — GrabNGoInfo.com
Next, let’s rename v0 to treatment, rename y to outcome, and convert the boolean values to 0 and 1.
# Rename columns
df = df.rename({'v0': 'treatment', 'y': 'outcome'}, axis=1)
# Create the treatment variable, and change boolean values to 1 and 0
df['treatment'] = df['treatment'].apply(lambda x: 1 if x == True else 0)
# Take a look at the data
df.head()
Causal Inference Data — GrabNGoInfo.com
Step 3: Raw Difference
In step 3, we will initiate CausalModel and print the raw data summary statistics. CausalModel takes three arguments:
• Y is the observed outcome.
• D is the treatment indicator.
• X is the covariates matrix.
CausalModel takes arrays as inputs, so .values are used when reading the data.
# Run causal model
causal = CausalModel(Y = df['outcome'].values, D = df['treatment'].values, X = df[['W0', 'W1', 'W2', 'W3']].values)
# Print summary statistics
print(causal.summary_stats)
Python CausalInference raw balance and difference — GrabNGoInfo.com
causal.summary_stats prints out the raw summary statistics. The output shows that:
• There are 2,269 units in the control group and 7,731 units in the treatment group.
• The average outcome for the treatment group is 13.94, and the average outcome for the control group is -2.191. So the raw difference between the treatment and the control group is 16.132, which is much higher than the actual treatment effect of 10.
• Nor-diff is the standardized mean difference (SMD) for covariates between the treatment group and the control group. Standardized Mean Differences(SMD) greater than 0.1 means that the data is imbalanced between the treatment and the control group. We can see that most of the covariates have SMD greater than 0.1.
Step 4: Basic One-to-one Matching on Confounders
In step 4, we will implement the basic matching estimator on confounders.
Confounders matching usually involve the following steps:
• Step 1: Compute the distance between the units in the treatment group and the control group using the confounders. The units with similar covariates produce smaller distances.
• Step 2: Match subjects in the treatment and control groups using the shortest distance. There are different measures of distance. The python package CausalInference uses the inverse variance matrix as the weighting matrix to standardize the covariates, but this weighting matrix can be changed as a hyperparameter.
• Step 3: Estimate the unit-level treatment effect for each matched pair.
• Step 4: Calculate the overall treatment effect by averaging the unit-level treatment effects.
We do not need to manually implement the steps. In python CausalInferencecausal.est_via_matching does the one-to-one matching on confounders automatically, and causal.estimates gives us the estimation results.
# Matching on confounders
causal.est_via_matching()
# Print out the treatment effect estimation results
print(causal.estimates)
Basic One-to-one Matching on Confounders – GrabNGoInfo.com
From the treatment effect estimation results, we can see that the average treatment effect (ATE), the average treatment effect on the control (ATC), and the average treatment effect on the treated (ATE) are all around 12, which is a much more accurate estimation than the raw difference of 16.
To learn more about the average treatment effect (ATE) and how to calculate it, please check out my previous tutorial ATE vs CATE vs ATT vs ATC for Causal Inference.
Step 5: Bias-adjusted One-to-one Matching on Confounders
Is it possible to get an estimation that is even closer to the true causal impact of 10? In step 5, we will adjust the bias in the confounder matching for a more accurate treatment effect estimation.
Bias exists because the treatment unit and the control unit in the matched pairs do not have exactly the same covariates values. This matching discrepancy caused the bias in unit-level treatment effect estimation.
To adjust the bias, an ordinary least squares (OLS) estimation is used to account for the differences in the confounders locally on the matched units. To learn more about the ordinary least squares (OLS) treatment effect estimation, check out my previous tutorial OLS Treatment Effects Estimation Using Python Package Causal Inference.
To use the bias-adjusted one-to-one matching on confounders, we can change the hyperparameter value bias_adj to True.
# Matching on confounders
causal.est_via_matching(bias_adj=True)
# Print out the treatment effect estimation results
print('bias-adjusted:', causal.estimates)
Bias-adjusted One-to-one Matching on Confounders – GrabNGoInfo.com
From the treatment effect estimation results, we can see that the average treatment effect (ATE), the average treatment effect on the control (ATC), and the average treatment effect on the treated (ATE) are all around the true causal impact of 10, which is more accurate than the base version of the confounder matching.
Step 6: One-to-many Matching on Confounders
In step 6, we will talk about how to use One-to-many matching on confounders.
To invoke multiple matching in the python package CausalInference, we can set the hyperparameter value for matches to an integer that is greater than 1.
# Matching on confounders
causal.est_via_matching(bias_adj=True, matches=2)
# Print out the treatment effect estimation results
print('bias-adjusted one-to-many:', causal.estimates)
One-to-many Matching on Confounders – GrabNGoInfo.com
From the treatment effect estimation results, we can see that after applying the one-to-two matching, the average treatment effect (ATE), the average treatment effect on the control (ATC), and the average treatment effect on the treated (ATE) are all around the true causal impact of 10, which is similar to the results of the one-to-one matching. The documentation of python package CausalInference suggests keeping the matches value below 4 although it’s not a hard rule.
For more information about data science and machine learning, please check out my YouTube channel and Medium Page or follow me on LinkedIn.
Recommended Tutorials
References
1 thought on “One-to-one Matching on Confounders Using Python Package Causal Inference”
Leave a Comment
Your email address will not be published. Required fields are marked *
|
__label__pos
| 0.834211 |
Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. Join them; it only takes a minute:
Sign up
Here's how it works:
1. Anybody can ask a question
2. Anybody can answer
3. The best answers are voted up and rise to the top
Edit: There will be a bonus of -20 for random masking
Hello fellow Whistleblowers and carriers of secret knowledge.
I am due to an interview by mail and I - of course - cannot say specific names in full length. But as I want to disclose it in a rather not-so-obvious-way I need your help.
I will provide these names in the form of
"evil_company_that_makes_me_shiver"
but surely I do not want to spell it out completely. Your task to help me and the whole world is that you provide a nice program that turns the above into
"ev**************************"
or
"**il************************"
or even
"****_c**********************"
I think you get it. But there is one flaw: I want to disclose the name in total, so I need to pass the number of occurrences and the word itself to the script and it will disclose the letters bit by bit. An example could be
~$ ./whistle NSA 3
> "N**"
> "**A"
> "*S*"
or
~$ ./whistle nuclear 3
> "nu*****"
> "***lea*"
> "**c***r"
or
~$ ./whistle nuclear 2
> "nuc****"
> "***lear"
I hope you can help me and as we know that size matters the shortest code wins. Help make this world a better place!
share|improve this question
1
You give no details about how the masking should happen, so you should get whatever is shortest code, no matter your examples. – Bill Woodger Apr 3 '14 at 8:47
I thought that it was clear that the shortest code wins? Hmmm, maybe I need to improve my english grammar according to this :( /Edit: I don't really care on how the masking ist done, the above is just an example, but it should be "unreadable" if you read one accorrence alone" – german_guy Apr 3 '14 at 9:13
Yes, shortest code was clear. But you will mostly get "regular" masking, not like your samples. Perhaps, since you don't mind anyway, change your sample outputs to regular ones. Specifically your second example of it running, plus the example in your question – Bill Woodger Apr 3 '14 at 9:19
1
Or you could a bonus for random masking. – ɐɔıʇǝɥʇuʎs Apr 3 '14 at 10:45
18 Answers 18
up vote 12 down vote accepted
GolfScript, 26 charaters
Since no specific way of disclosure was specified I decided to go for the shortest:
:f,\`{{\)f%.!@42if}%\;n}+%
You may experiment with this code online.
Example:
> "ABCDEFGHIJKLMNOPQRSTUVWXYZ" 7
******G******N******U*****
*****F******M******T******
****E******L******S******Z
***D******K******R******Y*
**C******J******Q******X**
*B******I******P******W***
A******H******O******V****
Commented code:
:f # Save the second input to variable f
, # Makes the array [0 1 2 .... f-1]
\`{ # \´{}+% builds a code block where
# first the input string is pushed (done
# via the + operator and afterwards the whole
# block is applied to above array, i.e.
# For each line 0, 1, ...
# Here, the stack contains the line number (counter)
# and the string
{ # {}% -> map to each character of the string
# Stack contains counter and current character
\)f% # Increase the counter by one and calculate modulo f
. # Duplicate counter (will be used for the if below)
! # and test for zero
# I.e. if counter==0
@ # Then Current character
42 # Else 42 (which is '*')
if #
}% # The mapping operation masked most of the characters
\; # Discard the counter
n # Add newline
}+%
share|improve this answer
Nice! Could you explain what each part of the code does? – John Odom Apr 3 '14 at 21:46
8
Can't see why. GolfScript is so self-documenting. – Evpok Apr 3 '14 at 22:34
@JohnOdom Nevertheless I added some comments to the code. – Howard Apr 4 '14 at 14:25
if you randomly decide whether or not you're going to shift all *'s by one to the right, does that count for the random masking bonus? – Cruncher Apr 4 '14 at 14:42
PHP - 80 bytes
<?for(;($c=$argv[1][~-$i+=1])?:$k^++$j;)echo$c?$i%$k=&$argv[2]^$j?'*':$c:$i='
';
Sample usage:
$ php whistle-blower.php ABCDEFGHIJKLMNOPQRSTUVWXYZ 7
******G******N******U*****
A******H******O******V****
*B******I******P******W***
**C******J******Q******X**
***D******K******R******Y*
****E******L******S******Z
*****F******M******T******
share|improve this answer
Python (157 149 139 138-20=118):
def f(a,b):
from random import*;c=[["*"]*len(a) for i in range(b)]
for d in range(len(a)):choice(c)[d]=a[d]
for e in c:print "".join(e)
Cheesy python (55 35):
You didn't tell me the required distribution ;)
g=lambda a,b:["*"*len(a)]*(b-1)+[a]
Uniform python (129 123 122):
def h(a,b):
c=[["*"]*len(a)for i in range(b)]
for d in range(len(a)):c=c[1:]+c[:1];c[0][d]=a[d]
for e in c:print"".join(e)
Output:
a="Synthetica 'Evil' the Second"
b=7
f(a,b)
print
for i in g(a,b): print i
print
h(a,b)
gives
***t***i***'***** *********d
******************t** ******
******t*** ***********Se**n*
S**************l****e*******
*y******c***E************o**
**n*h****a**************c***
*****e*******vi*'**h********
****************************
****************************
****************************
****************************
****************************
****************************
Synthetica 'Evil' the Second
******t******v******e******d
S******i******i****** ******
*y******c******l******S*****
**n******a******'******e****
***t****** ****** ******c***
****h******'******t******o**
*****e******E******h******n*
share|improve this answer
Your cheesy python can be shortened to g=lambda a,b:[a]+["*"*len(a)]*(b-1). :P – cjfaure Apr 3 '14 at 9:44
@Trimsty I see, thanks :) – ɐɔıʇǝɥʇuʎs Apr 3 '14 at 9:48
3
I think but surely I do not want to spell it out completely clearly invalidates a solution which does not ensure that at least one character is masked in each line of output. – Howard Apr 3 '14 at 12:00
@Howard I know it is stretching the rules, but disclose the letters bit by bit can also mean first, disclose the first bit (that just happens to be the entire thing), repeat until the b is met. This can also happen for the first answer, so just claim you used that one, and it juuust happend to produce this result. (I just realized that you could also write it as ["*"*len(a)]*(b-1)+[a], so that you start by disclosing bits that just happen to contain 0 bytes of actual information, and on the last line, you disclose another bit.) I do however, realize, that this is stretching to the max. – ɐɔıʇǝɥʇuʎs Apr 3 '14 at 13:04
+1 for cheekiness :) – ProgrammerDan Apr 3 '14 at 14:13
Bash, 80 bytes
m=${1//?/*}
for((i=1;d=i*${#1}/$2,i++<=$2;c=d)){
echo "${m:0:c}${1:c:d-c}${m:d}"
}
In action:
$ ./anon.sh stackoverflow.com 6
st***************
**ack************
*****ove*********
********rfl******
***********ow.***
**************com
$
share|improve this answer
C#, 226
This can be trimmed down if you replace the random stuff with a more simple distribution (think modulus) but the randomness is what got me interested. =)
Anyway, putting everything on just one line I get 226 characters. In readable code it looks like this:
private void F(string n, int i)
{
var l = n.Length;
var r = new Random();
var a = new string[i];
for (var p = 0; p < l; p++)
{
var x = r.Next(0, i);
for (var j = 0; j < i; j++)
{
a[j] += j == x ? n.Substring(p, 1) : "*";
}
}
for (var j = 0; j < i; j++)
{
Console.WriteLine(a[j]);
}
}
Sample output:
Anonymize.exe ABCDEFGHIJKLMNOPQRSTUVWXYZ 7
*****F**I**********T**W***
A*****************S****X**
**CDE**H*JKL**************
*************N************
**************O*****U****Z
*B****G*****M***QR********
***************P*****V**Y*
share|improve this answer
Does it guarantee at least on character from the input always? – Bill Woodger Apr 3 '14 at 10:08
Hmm.. no, probably not; good catch. For short strings and low values of i you probably could end up with ***/test. – deroby Apr 3 '14 at 14:12
Perl, 24
$_ x=<>;s/(.|
)./\1*/g
Requires the -p switch, which accounts for two of the bytes. Reads from STDIN.
How it works
• Because of the -p switch, Perl reads the first input lie and stores its contents in $_.
• The command $_ x=<>; duplicates the first input line the number of times the second input line (<>) specifies.
• The command s/(.|\n)./\1*/g; consumes two characters and replaces the second (which cannot be a newline) with an asterisk. It does this until it has consumed the entire contents of $_.
Since newlines count as the first character, this will obfuscate all even characters on the first line and all odd characters on the remaining lines.
• Because of the -p switch, Perl prints the contents of $_.
Example input
codegolf
4
Example output
c*d*g*l*
*o*e*o*f
*o*e*o*f
*o*e*o*f
share|improve this answer
duplicate strings, not very clean... – CSᵠ Apr 4 '14 at 10:44
What made you think you could mess around with the input to have it on two lines? – Bill Woodger Apr 4 '14 at 10:48
@BillWoodger: The question specifies no form of input. – Dennis Apr 4 '14 at 12:34
Fair enough. could lets you through :-) – Bill Woodger Apr 4 '14 at 13:06
Since newlines count as the first character, this will obfuscate all even characters on the first line and all odd characters on the remaining lines. Sounds like it will fail for codegolf\n1 – Cruncher Apr 4 '14 at 14:40
Java - 490
Yeah, not really golfed or anything. Oh well, here it is:
import java.util.ArrayList;public class Anonymise {public static void main(String[] args){ArrayList[] c=new ArrayList[Integer.parseInt(args[1])];for(int i=0;i<c.length;i++)c[i]=new ArrayList();for(char a:args[0].toCharArray()){int f=new java.util.Random().nextInt(c.length);c[f].add(a);for(int i=0;i<c.length;i++)if(i!=f)c[i].add('*');}ArrayList<String> b = new ArrayList<String>();for(ArrayList a:c){String s = "";for(Object o : a)s += o;b.add(s);}for(String s : b)System.out.println(s);}}
In a nice, legible format:
import java.util.ArrayList;
public class Anonymise {
public static void main(String[] args){
ArrayList[] c = new ArrayList[Integer.parseInt(args[1])];
for(int i=0;i<c.length;i++)
c[i]=new ArrayList();
for(char a:args[0].toCharArray()){
int f = new java.util.Random().nextInt(c.length);
c[f].add(a);
for(int i=0;i<c.length;i++)
if(i!=f)c[i].add('*');
}
ArrayList<String> b = new ArrayList<String>();
for(ArrayList a:c){
String s = "";
for(Object o : a)
s += o;b.add(s);
}
for(String s : b)
System.out.println(s);
}
}
Sample usage (When run from the compiled class)
> java Anonymise OnlinePerson 3
*n****P***o*
O*li***e****
****ne**rs*n
share|improve this answer
Are you running that or typing? How does P get to be p? – Bill Woodger Apr 3 '14 at 8:45
No problem. Just tidy away the used comments now – Bill Woodger Apr 3 '14 at 8:46
Just import java.util.* Also, ArrayList<String> = new ArrayList<>(); will work. You can also remove a lot of spaces. And most of the time, you can use List instead of ArrayList. – Ypnypn Apr 3 '14 at 20:55
Python 3 - 187 (-20 = 167)
Took me a while to write, could probably be golfed more.
import sys,random as a
b=sys.argv
x=[""for i in' '*int(b[2])]
for i in range(len(b[1])):n=a.randrange(len(x));x=[c+["*",b[1][len(c)]][j==n]for j,c in enumerate(x)]
for i in x:print(i)
Sample usage:
$ python tx.py super_anonymous_user 3
s******n**y*ou****e*
**p***a**n*m**s_us*r
*u*er_**o***********
As a function - 161 (-20 = 141)
from random import*
def f(c,n):
x=[""for i in' '*n]
for i in range(len(c)):n=randrange(len(x));x=[v+["*",c[len(v)]][j==n]for j,v in enumerate(x)]
return x
share|improve this answer
Does it guarantee at least on character from the input always? – Bill Woodger Apr 3 '14 at 10:09
@BillWoodger No. – cjfaure Apr 3 '14 at 10:10
2
Sorry, personally I regard it as not working then. then. – Bill Woodger Apr 3 '14 at 10:33
Some simple ways to shorten things: Unpack sys.argv in the assignment, and initialize x as x=['']*int(b[2]) (with b[2] replaced by whatever you name the variable you use in the unpacking). – user2357112 Apr 3 '14 at 10:57
2
I think but surely I do not want to spell it out completely clearly invalidates a solution which does not ensure that at least one character is masked in each line of output. – Howard Apr 3 '14 at 11:58
C# 184
namespace System.Linq{class P{static void Main(string[] a){int n=int.Parse(a[1]);for(int i=0;i<n;i++)Console.WriteLine(new String(a[0].Select((c,x)=>(i+x)%n==0?c:'*').ToArray()));}}}
Non-golfed
namespace System.Linq
{
class P
{
static void Main(string[] a)
{
int n = int.Parse(a[1]);
for (int i = 0; i < n; i++)
Console.WriteLine(new String(a[0].Select((c, x) => (i + x) % n == 0 ? c : '*').ToArray()));
}
}
}
Sample:
> Anonymize.exe "qwertyuio" 4
q***t***o
***r***i*
**e***u**
*w***y***
share|improve this answer
Perl 6 (77 bytes)
This may count as cheating, but it solves the problem (it doesn't print the string entirely).
($_,$!)=@*ARGS;.say for .chop~"*","*"x.chars-1~.substr(*-1),"*"x.chars xx$!-2
And the sample output.
> ./script.p6 ultimately_awesome 6
ultimately_awesom*
*****************e
******************
******************
******************
******************
share|improve this answer
JavaScript - 170
function s(a,e){o="",b=a.length,x=b/e|0,y=b-x*e;for(c=1;c<=e;c++){r="*";o+=Array((c-1)*x+1).join(r)+a.substr(c*x-x,c==e?x+y:x)+Array(c<e?b-c*x+1:0).join(r)+"\n"}return o}
Quick one, breaks if you supply a name and ask for more pieces than characters, but works up to that point and down to 1. Could be golfed more I assume, so may revise or take advice, as it's a bit of a mess.
Edit: Golfed further (from 187) with removal of brackets (@Synthetica) and Math.floor replacement from @toothbrush. For loop change as suggested results in errors in the output.
share|improve this answer
function s(d,a){o="";b=d.length;x=Math.floor(b/a);y=b-x*a;for(c=1;c<=a;c++)r="*",o+=Array((c-1)*x+1).join(r)+d.substr(c*x-x,c==a?x+y:x)+Array(c<a?b-c*x+1:0).join(r)+"\n";return o}; closure-compiler.appspot.com/home was capable of shaving off 8 chars ;) – ɐɔıʇǝɥʇuʎs Apr 3 '14 at 8:50
Are you saying if the text is five chars and it is asked for six replacements it breaks? – Bill Woodger Apr 3 '14 at 10:13
@BillWoodger He saying that using the closure compiler he shaved 8 chars from the total length of the code. – Eduard Florinescu Apr 3 '14 at 10:27
@EduardFlorinescu, sorry, I was unclear, I meant this bit breaks if you supply a name and ask for more pieces than characters – Bill Woodger Apr 3 '14 at 10:35
1
Use x=b/e|0 instead of x=Math.floor(b/e). Also, for(c=1;c<=e;c++) can be shortened to for(c=1;c++<=e;). – Toothbrush Apr 3 '14 at 11:48
R, (120-20)=100 bytes (2 different solutions of same length)
Beside the conciseness, R for sure features the best random number generator! :) Here the 1st solution of length 120:
function(s,n){
c=strsplit(s,"")[[1]]
e=sample(n,nchar(s),T)
sapply(1:n,function(i)paste(ifelse(e==i,c,"*"),collapse=""))
}
If the function is named as f, the output looks like:
> f("ABCDEFGHIJKLMNOPQRSTUVWXYZ", 7)
"******GH*****************Z"
"ABCD*********N************"
"***********L**O***********"
"*********J**M**P*RS*U**X**"
"**********K***********W***"
"*****F**I*******Q*********"
"****E**************T*V**Y*"
And here the 2nd solution, again with random masking, and again 120 bytes long:
function(s,n){
x=matrix("*",n,(m=nchar(s)))
x[cbind(sample(n,m,T),1:m)]=strsplit(s,"")[[1]]
apply(x,1,paste,collapse="")
}
share|improve this answer
Scala (1) 177 bytes
After the solution in R I also found one in Scala, here it is:
def f(s:String, n:Int)={
def c=s map (z=>z.toString)
def r=(1 to s.length) map (v=>v%n+1)
(for (i<-1 to n) yield s zip r map (t=>if(t._2==i) t._1 else "*") mkString "") map println
}
Scala (2) 129 bytes
After a short research I found the method zipWithIndex. Wonderful :)
def f(s:String, n:Int)={
(for (i<-0 until n) yield s.zipWithIndex.map (t=>if(t._2 % n==i) t._1 else "*") mkString "") map println
}
Here the solution:
f("ABCDEFGHIJKLMNOPQRSTUVWXYZ", 4)
***D***H***L***P***T***X**
A***E***I***M***Q***U***Y*
*B***F***J***N***R***V***Z
**C***G***K***O***S***W***
share|improve this answer
Javascript - 166
function s(b,a){o="";k=Array(a).join("*");t=k+b+k;for(i=a;0<i;i--)o+=t.replace(RegExp(".{"+(a-1)+"}(.)","g"),k+"$1").substr(i-1,b.length)+"\n",t=t.substr(1);return o}
Using regex.
Sample
> s("four",5)
f***
*o**
**u*
***r
****
> s("evil_company_that_makes_me_shiver",3)
e**l**o**a**_**a**m**e**m**s**v**
*v**_**m**n**t**t**a**s**e**h**e*
**i**c**p**y**h**_**k**_**_**i**r
share|improve this answer
k [50-20=30 chars]
{.{@[y#"*";z;:;x z]}[x;c]'=_d*y%#d:<<(-d)?!d:c:#x}
Explanation
1. Input: x=String which needs to be masked, y=number of lines
2. Count the number of characters c in string and create y buckets.
3. Place c mod y characters in each bucket.
4. For each bucket, print "*" for the remaining numbers not in that bucket.
Example
{.{@[y#"*";z;:;x z]}[x;c]'=_d*y%#d:<<(-d)?!d:c:#x}["abcdefghijklmnopqrstuvwxyz";4]
Output
"ab*d*f***j**********u*w***"
"**c*e*gh**k*****q*s*******"
"********i***mn*****t*v**y*"
"***********l**op*r*****x*z"
share|improve this answer
JavaScript - 139-20=119
function e(s,c){r=[];for(i=c;i--;)r[i]='';for(i=0;i<s.length*c;i++)x=i%c,n=(x<1?Math.random()*c|0:n),r[x]+=(n!=x?'*':s[(i/c)|0]);return r}
Usage and sample output:
console.log(e("evil_company_that_makes_me_shiver", 3));
["**i*_**mp*****h**_ma**********v**",
"*****co**a***t*a******s*me_*hi*e*",
"ev*l******ny_***t***ke*_***s****r"]
As the masking is random, the output may also look like this:
console.log(e("evil_company_that_makes_me_shiver", 2));
["evil_company_that_makes_me_shiver",
"*********************************"]
share|improve this answer
Julia 56-20=36 (works often)
f(s,n)=[join([rand()<1.9/n?c:"*" for c in s]) for r=1:n]
julia> f("evilcompany!!!",4)
4-element Array{Union(UTF8String,ASCIIString),1}:
"e**l**mp*ny*!*"
"***lco********"
"e*il**m*a*y!*!"
"evil**m*an***!"
Trying to go for a shorter random solution I decided to sacrifice guaranteed functioning for a shorter solution. It's really not a very good solution.
share|improve this answer
F# - 81 80 75
This is fairly similar to others that have been offered:
let a s n=[for i in 0..n-1->String.mapi(fun j c->[c;'*'].[min((j+i)%n)1])s]
Sample:
a "evil_company_that_makes_me_shiver" 7
e******m******h******e******h****
******o******t******k******s*****
*****c******_******a******_******
****_******y******m******e******r
***l******n******_******m******e*
**i******a******t******_******v**
*v******p******a******s******i***
As a full, stand-alone application it comes out to 160 155 156 characters:
[<EntryPoint>]let m (a:string array)=
let n=System.Int32.Parse a.[1]
for i in 0..n-1 do printfn"%s"(String.mapi(fun j c->[c;'*'].[min((j+i)%n)1])a.[0])
0
share|improve this answer
Your Answer
discard
By posting your answer, you agree to the privacy policy and terms of service.
Not the answer you're looking for? Browse other questions tagged or ask your own question.
|
__label__pos
| 0.955649 |
Dynamodb scan items by presence of a Document Type Map.AttributeName
Tags: ,
I have this Item structure:
{
"Items": [
{
"serviceName": {
"S": "B"
},
"sharedData": {
"M": {
"five": {
"S": "5"
}
}
}
}
}
I want to scan data by the presence of key five “five” within sharedData map. Something like sharedData.five exists or sharedData.five == *.
Is this possible?
Answer
aws dynamodb scan --table-name YOURTABLE --filter-expression 'attribute_exists(sharedData.five)'
Here is the CLI answer. You will need to turn it into Java, which is simple enough.
Source: stackoverflow
|
__label__pos
| 1 |
Answers
Solutions by everydaycalculation.com
Answers.everydaycalculation.com » Add fractions
Add 1/5 and 12/8
1st number: 1/5, 2nd number: 1 4/8
1/5 + 12/8 is 17/10.
Steps for adding fractions
1. Find the least common denominator or LCM of the two denominators:
LCM of 5 and 8 is 40
Next, find the equivalent fraction of both fractional numbers with denominator 40
2. For the 1st fraction, since 5 × 8 = 40,
1/5 = 1 × 8/5 × 8 = 8/40
3. Likewise, for the 2nd fraction, since 8 × 5 = 40,
12/8 = 12 × 5/8 × 5 = 60/40
4. Add the two like fractions:
8/40 + 60/40 = 8 + 60/40 = 68/40
5. 68/40 simplified gives 17/10
6. So, 1/5 + 12/8 = 17/10
In mixed form: 17/10
MathStep (Works offline)
Download our mobile app and learn to work with fractions in your own time:
Android and iPhone/ iPad
Related:
© everydaycalculation.com
|
__label__pos
| 0.993327 |
Section 1: Linux in the Cloud: An attraction for everyone – including threat actors
In Section 1, we embark on an insightful exploration of the intersection between Linux and cloud technology. With Chapters 1 to 3, we navigate through the intricate terrain of challenges that arise when Linux meets the cloud. From the allure of Linux’s popularity in cloud environments to the complexities faced by security professionals, this section sheds light on crucial dimensions of modern cybersecurity.
Join us as we delve into the world of Linux threats, dissecting their impact, advantages, and vulnerabilities within the dynamic realm of cloud computing.
|
__label__pos
| 0.993811 |
C++ Program to Find All Roots of a Quadratic Equation
Source Code
#include <iostream>
#include <cmath> // include the cmath library for the sqrt() function
using namespace std;
int main()
{
double a, b, c; // Declare variables to hold the coefficients of the quadratic equation
double x1, x2; // Declare variables to hold the roots of the equation
cout << "Enter the coefficient of x^2: "; // Prompt the user to enter the coefficient of x^2
cin >> a; // Read the coefficient of x^2 from the standard input stream
cout << "Enter the coefficient of x: "; // Prompt the user to enter the coefficient of x
cin >> b; // Read the coefficient of x from the standard input stream
cout << "Enter the constant term: "; // Prompt the user to enter the constant term
cin >> c; // Read the constant term from the standard input stream
// Calculate the roots of the equation using the quadratic formula
x1 = (-b + sqrt(b*b - 4*a*c)) / (2*a);
x2 = (-b - sqrt(b*b - 4*a*c)) / (2*a);
cout << "The roots of the equation are: " << x1 << " and " << x2 << endl; // Print the roots
return 0;
}
Code Explanation
This program declares three variables a, b, and c of type double to hold the coefficients of the quadratic equation, and two variables x1 and x2 of type double to hold the roots of the equation. It then uses the cout object to print prompts asking the user to enter the coefficients and the cin object to read the coefficients from the standard input stream.
To find the roots of the equation, the program uses the quadratic formula:
x = (-b +- sqrt(b^2 - 4ac)) / (2a)
where a, b, and c are the coefficients of the equation, and x is the root. The + and - signs represent the two possible roots of the equation.
The program calculates the roots using the formula and stores them in the variables x1
Explain (cmath)
<cmath> is a header file in the C++ standard library that defines a set of mathematical functions and macros. It is part of the C++ Standard Template Library (STL) and is defined in the namespace std.
The functions defined in <cmath> are a subset of the C math library (math.h) and provide a range of mathematical operations such as trigonometric functions, exponential and logarithmic functions, power and absolute value functions, and more.
Here are some examples of functions defined in <cmath>:
• sqrt(): calculates the square root of a number
• pow(): raises a number to a specified power
• exp(): calculates the exponential of a number
• log(): calculates the natural logarithm of a number
• abs(): calculates the absolute value of a number
• sin(): calculates the sine of an angle
• cos(): calculates the cosine of an angle
• tan(): calculates the tangent of an angle
To use the functions defined in <cmath>, you need to include the header file in your C++ program using the #include preprocessor directive:
#include <cmath>
You can then access the functions using the std:: namespace prefix, or by using the using namespace std; directive.
Note: C++ Complete Examples
|
__label__pos
| 0.998428 |
We use cookies to personalise content and advertisements and to analyse access to our website. Furthermore, our partners for online advertising receive pseudonymised information about your use of our website. cookie policy and privacy policy.
+0
0
39
2
avatar
If \(\lfloor x \rfloor = 4,\) find the sum of all possible values of \(\lfloor 4x \rfloor.\)
May 9, 2019
#1
avatar+110
+5
Another way of writing \(\lfloor x\rfloor = 4\) defines x values in the interval of \(4 \leq x < 5\)
If we multiply this interval by 4, we have that \(16\leq 4x < 20\).
In order to get the sum, we have to acknowledge that our 4x is still being floored, given \(\lfloor 4x \rfloor\). Therefore, only integer values within the interval can be a result of this. For example, \(x = 4.625\) satisfies that \(\lfloor x \rfloor = 4\). Then, \(\lfloor 4x \rfloor = \lfloor 4*4.625\rfloor = \lfloor 18.5 \rfloor = 18\)
The integers within \([16, 20)\) are 16, 17, 18, and 19. \(16+17+18+19= 70\).
If \(\lfloor x \rfloor = 4, \) the sum of all possible values of \(\lfloor 4x \rfloor\) is \(70\).
May 9, 2019
#2
avatar+7603
+3
Hey, that's a good way to do it! smiley
hectictar May 9, 2019
8 Online Users
avatar
|
__label__pos
| 0.628876 |
« Zurück zu Database...
Database Portal Properties
Introduction #
This page contains a bunch of portal properties that are by default either commented out or set to some default value. To use any of them, uncomment the block of code and paste it into your portal-ext.properties file. For example, to enable MySQL, you should copy and paste the below into your portal-ext.properties:
#
# MySQL
#
jdbc.default.driverClassName=com.mysql.jdbc.Driver
jdbc.default.url=jdbc:mysql://localhost/lportal?useUnicode=true&characterEncoding=UTF-8&useFastDateParsing=false
jdbc.default.username=
jdbc.default.password=
This page has similar settings for all the databases that Liferay Portal supports. These properties will work in Liferay versions 5.2 and above.
Portal Properties #
##
## JDBC
##
#
# Set the JNDI name to lookup the JDBC data source. If none is set,
# then the portal will attempt to create the JDBC data source based on the
# properties prefixed with "jdbc.default.".
#
#jdbc.default.jndi.name=jdbc/LiferayPool
#
# Set the properties used to create the JDBC data source. These properties
# will only be read if the property "jdbc.default.jndi.name" is not set.
#
# The default settings are configured for an in-memory database called
# Hypersonic that is not recommended for production use. Please change the
# properties to use another database.
#
# Add dynamic-data-source-spring.xml to the property "spring.configs" to
# configure the portal to use one database cluster for read calls and
# another database cluster for write calls. The convention is to create a
# set of properties prefixed with "jdbc.read." to handle read calls and
# another set of properties prefixed with "jdbc.write." to handle write
# calls. These data sources can also be created via JNDI by setting the
# properties "jdbc.read.jndi.name" and "jdbc.write.jndi.name". Note that
# these settings, though separate, are a copy of the default settings with
# the newly overridden values.
#
DB2 #
#
# DB2
#
#jdbc.default.driverClassName=com.ibm.db2.jcc.DB2Driver
#jdbc.default.url=jdbc:db2://localhost:50000/lportal:deferPrepares=false;fullyMaterializeInputStreams=true;fullyMaterializeLobData=true;progresssiveLocators=2;progressiveStreaming=2;
#jdbc.default.username=db2admin
#jdbc.default.password=lportal
DerbyDB #
#
# Derby
#
#jdbc.default.driverClassName=org.apache.derby.jdbc.EmbeddedDriver
#jdbc.default.url=jdbc:derby:lportal
#jdbc.default.username=
#jdbc.default.password=
Hypersonic #
This is the default database that comes with the Liferay Bundle. DO NOT USE HYPERSONIC IN PRODUCTION.
#
# Hypersonic
#
#jdbc.default.driverClassName=org.hsqldb.jdbcDriver
#jdbc.default.url=jdbc:hsqldb:${liferay.home}/data/hsql/lportal
#jdbc.default.username=
#jdbc.default.password=
IngresDB #
#
# Ingres
#
#jdbc.default.driverClassName=com.ingres.jdbc.IngresDriver
#jdbc.default.url=jdbc:ingres://localhost:II7/lportal
#jdbc.default.username=
#jdbc.default.password=
MySQL #
#
# MySQL
#
#jdbc.default.driverClassName=com.mysql.jdbc.Driver
#jdbc.default.url=jdbc:mysql://localhost/lportal?useUnicode=true&characterEncoding=UTF-8&useFastDateParsing=false
#jdbc.default.username=
#jdbc.default.password=
Oracle #
#
# Oracle
#
#jdbc.default.driverClassName=oracle.jdbc.driver.OracleDriver
#jdbc.default.url=jdbc:oracle:thin:@localhost:1521:xe
#jdbc.default.username=lportal
#jdbc.default.password=lportal
P6Spy#
#
# P6Spy
#
#jdbc.default.driverClassName=com.p6spy.engine.spy.P6SpyDriver
#jdbc.default.url=jdbc:mysql://localhost/lportal?useUnicode=true&characterEncoding=UTF-8&useFastDateParsing=false
#jdbc.default.username=
#jdbc.default.password=
PostgreSQL #
#
# PostgreSQL
#
#jdbc.default.driverClassName=org.postgresql.Driver
#jdbc.default.url=jdbc:postgresql://localhost:5432/lportal
#jdbc.default.username=
#jdbc.default.password=
SQL Server #
#
# SQL Server
#
#jdbc.default.driverClassName=net.sourceforge.jtds.jdbc.Driver
#jdbc.default.url=jdbc:jtds:sqlserver://localhost/lportal
#jdbc.default.username=sa
#jdbc.default.password=
Sybase #
#
# Sybase
#
#jdbc.default.driverClassName=net.sourceforge.jtds.jdbc.Driver
#jdbc.default.url=jdbc:jtds:sybase://localhost:5000/lportal
#jdbc.default.username=sa
#jdbc.default.password=
Connection Pooling #
#
# Liferay can use C3PO, DBCP, or Primrose for connection pooling. See
# com.liferay.portal.dao.jdbc.util.DataSourceFactoryBean for the actual
# implementation. It is important to understand the strengths and weaknesses
# of each provider so that you can choose the best one that fits your
# deployment scenario. Provider specific properties can also be passed along
# directly to the provider. For example, the property
# "jdbc.default.acquireIncrement" is read by C3PO, the property
# "jdbc.default.maxActive" is read by DBCP, and the property
# "jdbc.default.base" is read by Primrose.
#
# The default provider is C3PO.
#
jdbc.default.liferay.pool.provider=c3po
#jdbc.default.liferay.pool.provider=dbcp
#jdbc.default.liferay.pool.provider=primrose
#
# The following properties will be read by C3PO if Liferay is configured to
# use C3PO in the property "jdbc.default.liferay.pool.provider". See
# http://www.mchange.com/projects/c3p0/index.html#configuration for a list
# of additional fields used by C3PO for configuring database connections.
#
jdbc.default.acquireIncrement=5
jdbc.default.connectionCustomizerClassName=com.liferay.portal.dao.jdbc.pool.c3p0.PortalConnectionCustomizer
jdbc.default.idleConnectionTestPeriod=60
jdbc.default.maxIdleTime=3600
jdbc.default.maxPoolSize=100
jdbc.default.minPoolSize=10
jdbc.default.numHelperThreads=3
#jdbc.default.transactionIsolation=1
#
# The following properties will be read by DBCP if Liferay is configured to
# use DBCP in the property "jdbc.default.liferay.pool.provider". See
# http://commons.apache.org/dbcp/configuration.html for a list of additional
# fields used by DBCP for configuring database connections.
#
#jdbc.default.defaultTransactionIsolation=READ_UNCOMMITTED
jdbc.default.maxActive=100
jdbc.default.minIdle=10
jdbc.default.removeAbandonedTimeout=3600
#
# The following properties will be read by Primrose if Liferay is configured
# to use Primrose in the property "jdbc.default.liferay.pool.provider". See
# http://www.primrose.org.uk/primrose3/primroseConfig.html for a list of
# additional fields used by Primrose for configuring database connections.
#
jdbc.default.base=100
#jdbc.default.connectionTransactionIsolation=TRANSACTION_READ_UNCOMMITTED
jdbc.default.idleTime=1800000
jdbc.default.numberOfConnectionsToInitializeWith=10
Custom SQL #
##
## Custom SQL
##
#
# Input a list of comma delimited custom SQL configurations.
#
custom.sql.configs=custom-sql/default.xml
#
# Some databases do not recognize a NULL IS NULL check. Set the
# "custom.sql.function.isnull" and "custom.sql.function.isnotnull"
# properties for your specific database.
#
# There is no need to manually set these properties because
# com.liferay.portal.spring.PortalHibernateConfiguration already sets it.
# However, these properties are available so that you can see how you can
# override it for a database that PortalHibernateConfiguration does not yet
# know how to auto configure.
#
#
# DB2
#
#custom.sql.function.isnull=CAST(? AS VARCHAR(32672)) IS NULL
#custom.sql.function.isnotnull=CAST(? AS VARCHAR(32672)) IS NOT NULL
#
# MySQL (for testing only)
#
#custom.sql.function.isnull=IFNULL(?, '1') = '1'
#custom.sql.function.isnotnull=IFNULL(?, '1') = '0'
#
# Sybase
#
#custom.sql.function.isnull=ISNULL(CONVERT(VARCHAR,?), '1') = '1'
#custom.sql.function.isnotnull=ISNULL(CONVERT(VARCHAR,?), '1') = '0'
MySQl Engine #
##
## Database
##
#
# Specify any database vendor specific settings.
#
#
# MySQL
#
#
# Set the MySQL engine type. InnoDB is the recommended engine because it
# provides transactional integrity.
#
database.mysql.engine=InnoDB
0 Anhänge
119146 Angesehen
Durchschnitt (2 Stimmen)
Die durchschnittliche Bewertung ist 5.0 von max. 5 Sternen.
Kommentare
Antworten im Thread Autor Datum
What are the properties for DB Sharding can go... Raja Nagendra Kumar 7. Juni 2012 22:10
What are the properties for DB Sharding can go here, basically if each portal instance how does DB get impacted
1. Is it possible to create a new database for each portal instance (data is completely isolated for each tenant for security reasons) - I think as of 6.1, this is still not supported
2. is webid treated as differentor and hence data related to all tenants is in just one database differentiated through tenant id (webid)
Gepostet am 07.06.12 22:10.
|
__label__pos
| 0.874834 |
Lilster Lilster - 1 year ago 71
HTML Question
Gap in Bootstrap stacked rows
I am building a Bootstrap 3 grid that will become a portfolio page eventually. In the following bootply, in the first example, you can see it works perfectly stacking from 6 to 4 to 3 in my bootply
However in the second example, on the same bootply, there is an item where the tile for the item is longer and it causes a gap in the grid when it stacks.
What is the best bootstrap friendly ,solution to this? Any help much appreciated.
Answer
There are a couple of ways to handle this:
1. Give all of the elements in your portfolio a set height.
2. Use something like masonry to dynamically "fit" the elements into the available space.
3. Use the responsive classes and clearfix as described in the doc under the heading Responsive column resets, in the Grid secion.
4. Use jQuery to adjust the column heights dynamically.
If your content is dynamically generated so that you don't know which elements will have longer content, and you have different layouts set for different breakpoints, the responsive classes approach can be a bear to adapt. I use a little trick. After each element in the grid, I add a div that I can apply a mini clearfix to using media queries. It's extra markup, but it solves the problem nicely and allows me to have readable and maintainable markup while avoiding the use of javascript to adjust the layout. Here's an example using your markup:
Updated Bootply
<div class="row portfolio"> <!--Add a class so you can target with nth-child-->
<div class="col-lg-2 col-sm-3 col-xs-4">
<div class="panel panel-default">
<div class="panel-body">
<a href="#">
<img src="http://placehold.it/200x200" class="img-thumbnail img-responsive">
</a>
</div>
<div class="panel-footer">
This is text
</div>
</div>
</div>
<div class="clear"></div> <!--Here's the added div after every element-->
....
</div> <!--/.portfolio.row-->
CSS:
@media (max-width: 767px) {
.portfolio>.clear:nth-child(6n)::before {
content: '';
display: table;
clear: both;
}
}
@media (min-width: 768px) and (max-width: 1199px) {
.portfolio>.clear:nth-child(8n)::before {
content: '';
display: table;
clear: both;
}
}
@media (min-width: 1200px) {
.portfolio>.clear:nth-child(12n)::before {
content: '';
display: table;
clear: both;
}
}
If you prefer the jQuery route (again, this assumes that you've added a class "portfolio" to the row that contains your portfolio elements for easier targeting):
var row=$('.portfolio');
$.each(row, function() {
var maxh=0;
$.each($(this).find('div[class^="col-"]'), function() {
if($(this).height() > maxh)
maxh=$(this).height();
});
$.each($(this).find('div[class^="col-"]'), function() {
$(this).height(maxh);
});
});
|
__label__pos
| 0.964587 |
Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:
Sign up
Here's how it works:
1. Anybody can ask a question
2. Anybody can answer
3. The best answers are voted up and rise to the top
I am a spanish speaker so excuse me for my bad english.
I am learning how to compile slackware kernel, so I have downloaded linux-3.2.7.tar.bz2 from http://www.kernel.org
Conditions:
• Slackware installed on a vmware virtual machine.
• Host o.s windows 7.
• Slackware root filesystem: ext4
• Slackware old kernel: 2.6.37.6
• Slackware partitions: sda1 for swapping, sda2 for the kernel.
Basically I have followed the following steps:
#cd /usr/src
#tar jvxf linux-3.2.2.tar.bz2
#mv /usr/src/linux /usr/src/linux.old
#ln -s /usr/src/linux-3.2.2 /usr/src/linux
#cd linux-3.2.2
#make mrproper
#cp /usr/src/linux-2.6.37.6/.config /usr/src/linux-3.2.2/.config
#make menuconfig
Load an alternate configuration file: .config INCLUDED (OPTION Y):
ATA/ATAPI/MFM/RLL support (DEPRECATED) (at Device drivers)
SCSI generic support (at Device drivers)
second extended support (at filesystems)
ext3 journaling (all)
ext4 (all)
ext4 (at filesystems)
JBD (ext4) debuggin support
JBD2 (ext4) debugging support
ReiserFS support
XFS filesystem support
"compile kernel with debug info" (at kernel hacking)
make dep
make clean
make bzImage
make modules
make modules_install
mv /boot/System.map /boot/System.map.old
cp /usr/src/linux/System.map /boot/System.map-3.2.2
ln -s /boot/System.map-3.2.2 /boot/System.map
mv /boot/vmlinuz /boot/vmlinuz.old
cp /usr/src/linux/arch/i386/boot/bzImage /boot/vmlinuz-3.2.2
ln -s /boot/vmlinuz-3.2.2 /boot/vmlinuz
nano -w /etc/lilo.conf
ADDED THE FOLLOWING LINES:
image=/boot/vmlinuz.old
label = oldSlack
root = /dev/sda2
read-only
#lilo
#lilo -q
#shutdown -r now
When kernel 3.2.2 is booting, it stops showing the following:
VFS: Cannot open root device "802" or unknown-block(8,2)
Please append a correct "root=" boot option
Kernel Panic - not syncing: VFS: Unable to mount root fs on unknown-bloc(8,2)
I hate this message because I have recompiled the kernel many times, and after hours of compilation I always get this message. :(
Can anyone help me to understand what I am doing bad or why is that error?
share|improve this question
up vote 0 down vote accepted
NOTE: I am not familiar with Linux 3.
I can guess right now, wrong path cause this problem while executing lilo command. Lilo installed mbr somewhere else.
1st: Stop recompiling your kernel because i think it even didn't start booting.
2nd: Check again path for boot files, and paths when executing lilo. Read about lilo -r switch
system=sda2
mbr=sda
lilo -F -r /mnt/$system -b /dev/$mbr -C /etc/lilo.conf
Show output:
/sbin/sfdisk -d /dev/sda
ls -all /boot/
lilo
dmesg
I would suggest you to use L switch:
cp -L /usr/src/linux/System.map /boot/System.map-3.2.2
cp -L /usr/src/linux/arch/i386/boot/bzImage /boot/vmlinuz-3.2.2
Are you sure, Linux is boting?
share|improve this answer
Thanks for answering, this is what I have gotten: dl.dropbox.com/u/107789289/ERROR-PANIC.png I have done the same steps in a virtual box virtual machine and it has worked, now I am trying on vmware and it doesnt work – adrian4aes Oct 7 '12 at 17:38
You must log in to answer this question.
Not the answer you're looking for? Browse other questions tagged .
|
__label__pos
| 0.599869 |
In Android, you can use “android.widget.RatingBar” to display rating bar component in stars icon. The user is able to touch, drag or click on the stars to set the rating value easily.
In this tutorial, we show you how to use XML to display a rating bar, few textviews and a button. When user click on the rating bar’s star, the selected rating value will be displayed in the textview. And, if user clicks on the button, the selected rating value will be displayed as a floating message (toast message).
P.S This project is developed in Eclipse 3.7, and tested with Android 2.3.3.
1. Rating Bar
Open “res/layout/main.xml” file, add a rating bar component, few textviews and a button.
Note
The rating bar contains many configurable values. In this case, the rating bar contains 4 stars, each increase 1.0 value, so, it contains the minimum of 1.0 (1 star) and maximum value of 4.0 (4 stars). In addition, it made the 2nd star (2.0) selected by default.
File : res/layout/main.xml
<?xml version="1.0" encoding="utf-8"?>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/lblRateMe"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Rate Me"
android:textAppearance="?android:attr/textAppearanceMedium" />
<RatingBar
android:id="@+id/ratingBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:numStars="4"
android:stepSize="1.0"
android:rating="2.0" />
<Button
android:id="@+id/btnSubmit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Submit" />
<LinearLayout
android:id="@+id/linearLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/lblResult"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Result : "
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="@+id/txtRatingValue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:textAppearance="?android:attr/textAppearanceSmall" />
</LinearLayout>
</LinearLayout>
2. Code Code
Inside activity “onCreate()” method, attach a listener on rating bar, fire when rating value is changed. Another listener on button, fire when button is clicked. Read the code’s comment, it should be self-explanatory.
File : MyAndroidAppActivity.java
package com.mkyong.android;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RatingBar;
import android.widget.RatingBar.OnRatingBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;
public class MyAndroidAppActivity extends Activity {
private RatingBar ratingBar;
private TextView txtRatingValue;
private Button btnSubmit;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
addListenerOnRatingBar();
addListenerOnButton();
}
public void addListenerOnRatingBar() {
ratingBar = (RatingBar) findViewById(R.id.ratingBar);
txtRatingValue = (TextView) findViewById(R.id.txtRatingValue);
//if rating value is changed,
//display the current rating value in the result (textview) automatically
ratingBar.setOnRatingBarChangeListener(new OnRatingBarChangeListener() {
public void onRatingChanged(RatingBar ratingBar, float rating,
boolean fromUser) {
txtRatingValue.setText(String.valueOf(rating));
}
});
}
public void addListenerOnButton() {
ratingBar = (RatingBar) findViewById(R.id.ratingBar);
btnSubmit = (Button) findViewById(R.id.btnSubmit);
//if click on me, then display the current rating value.
btnSubmit.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MyAndroidAppActivity.this,
String.valueOf(ratingBar.getRating()),
Toast.LENGTH_SHORT).show();
}
});
}
}
3. Demo
Run the application.
1. Result, 2nd star is selected by default.
android rating demo1
2. Touch on the 3rd star, rating value is changed, display the current selected value in the result (textview).
android rating demo2
3. Touch on the 1st star, and click on the submit button, the current selected value is displayed as floating message.
android rating demo3
Download Source Code
Download it – Android-RatingBar-Example.zip (15 KB)
References
1. Android RatingBar JavaDoc
2. Android RatingBar Example
|
__label__pos
| 0.662707 |
hook.js and hook.test.js
hook.js
This file will contain the actual code of your hook. For JavaScript, we provide a hook-sdk. This hook-sdk serves as helper for retrieving findings and as entrypoint for the Dockerfile.
The only function required to be created is the handle() function. This function is called by the hook-sdk after scans are finished. As parameters for handle() the hook-sdk provides the following:
getRawResults()
This callback function will provide all raw results to the hook as a promise.
caution
When the rawResults are in form of a json file, getRawResults will return the parsed representation of the data, not the json string.
async function handle({
getRawResults,
}) {
const result = await getRawResults();
// outputs string representation of the scan result file
// e.g. the nmap xml output
console.log(result);
}
module.exports.handle = handle;
getFindings()
This callback function will provide all findings to the hook as an array of findings wrapped in a promise.
Example:
async function handle({
getFindings,
}) {
const findings = await getFindings();
// logs the findings returned by the parser of the scantype
console.log(findings);
}
module.exports.handle = handle;
updateRawResults()
This callback function will enable you to publish desired changes to raw results.
note
updateRawResults is only available in ReadAndWrite hooks.
caution
updateRawResults operates on the raw results of the scans, this means that the implementation has to be tied to the specific output format of a singular scanner. The updated raw results are also not parsed again by the parsers integrated into the secureCodeBox, making this method only viable if you are using a ReadOnly hook exporting the results into a external system like DefectDojo.
If you want to perform actions on all findings consider using the updateFindings hook.
Example
async function handle({
updateRawResults,
}) {
// Overrides the raw results with a fixed nmap report
await updateRawResults(`
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE nmaprun>
<?xml-stylesheet href="file:///usr/local/bin/../share/nmap/nmap.xsl" type="text/xsl"?>
<!-- Nmap 7.91 scan initiated Mon Dec 7 12:29:59 2020 as: nmap -oX - -p 443 fooobar.example.com -->
<nmaprun scanner="nmap" args="nmap -oX - -p 443 fooobar.example.com" start="1607340599" startstr="Mon Dec 7 12:29:59 2020" version="7.91" xmloutputversion="1.05">
<scaninfo type="connect" protocol="tcp" numservices="1" services="443"/>
<verbose level="0"/>
<debugging level="0"/>
Failed to resolve "fooobar.example.com".
WARNING: No targets were specified, so 0 hosts scanned.
<runstats><finished time="1607340599" timestr="Mon Dec 7 12:29:59 2020" summary="Nmap done at Mon Dec 7 12:29:59 2020; 0 IP addresses (0 hosts up) scanned in 0.03 seconds" elapsed="0.03" exit="success"/><hosts up="0" down="0" total="0"/>
</runstats>
</nmaprun>
`);
}
module.exports.handle = handle;
updateFindings()
This callback function will enable you to publish desired updates to the findings.
note
updateFindings is only available in ReadAndWrite hooks.
caution
If you make changes to some findings you will have to call updateFindings() with ALL findings not just with the ones that have changed or unchanged findings will get lost!
Example:
async function handle({
updateFindings,
}) {
// Overrides the findings with a fixed nmap finding
await updateFindings([
{
"id": "7475b620-0527-4679-b738-b2c69fad025f"
"name": "ssh",
"description": "Port 22 is open using tcp protocol.",
"category": "Open Port",
"location": "tcp://45.33.32.156:22",
"osi_layer": "NETWORK",
"severity": "INFORMATIONAL",
"attributes": {
"port": 22,
"state": "open",
"ip_address": "45.33.32.156",
"mac_address": null,
"protocol": "tcp",
"hostname": "scanme.nmap.org",
"method": "table",
"operating_system": null,
"service": "ssh",
"serviceProduct": null,
"serviceVersion": null,
"scripts": null
},
}
]);
}
scan
Example
This is a basic example for the generic-webhook As you can see this hook defines the handle() function but only uses getFindings() and scan provided by the hook-sdk. This is fine because the other parameters are not needed.
info
Maybe you notice that in line 5 ENVs are used. If you also need ENVs or Volumes see INSERT-LINK-HERE.
info
Notice that the handle() function has to be exported to use in the hook-sdk
const axios = require("axios");
async function handle({
getFindings,
scan,
webhookUrl = process.env["WEBHOOK_URL"],
}) {
const findings = await getFindings();
console.log(`Sending ${findings.length} findings to ${webhookUrl}`);
await axios.post(webhookUrl, { scan, findings });
}
module.exports.handle = handle;
hook.test.js
This file should contain some unit test to run against your hook.
|
__label__pos
| 0.774388 |
0 Daumen
166 Aufrufe
Hallo :)
Ich soll folgende Aussage beweisen oder widerlegen:
∀n∈ℕ : n * (n + 1) * ( n + 2) ist durch 4 teilbar
oder
n * (n + 1) * (n + 2) - 2 ist durch 4 teilbar
Ich habe bereits einen Lösungsansatz mit Modulo, würde allerdings trotzdem gerne wissen, ob es noch andere Lösungsmöglichkeiten gibt (z.B. Induktion).
Danke für die Hilfe :)
von
1 Antwort
+2 Daumen
Beste Antwort
n * (n + 1) * (n + 2) ist mit Sicherheit eine gerade Zahl.
Jede 2. gerade Zahl ist auch durch 4 teilbar.
Sollte n * (n + 1) * (n + 2) also nicht durch 4 teilbar sein braucht man nur 2 zu subtrahieren und hat damit eine Zahl die durch 4 teilbar ist.
Für n gerade gilt n = 2*k
2k * (2k + 1) * (2k + 2) = 4·(2·k^3 + 6·k^2 + k)
Ist also durch 4 teilbar
Für n ungerade gilt n = 2*k - 1
(2*k - 1) * ((2*k - 1) + 1) * ((2*k - 1) + 2) = 8·k^3 - 2·k
Wenn k gerade ost ist der Term durch 4 teilbar. Für ungerade k
8·k^3 - 2·k - 2 = 8·k^3 - 2·(k + 1)
ist dieses also durch 4 teilbar weil dann k + 1 gerade ist.
von 299 k
Ein anderes Problem?
Stell deine Frage
Willkommen bei der Mathelounge! Stell deine Frage sofort und kostenfrei
x
Made by a lovely community
...
|
__label__pos
| 0.971388 |
IP Address Classes and Ranges Explained with Subnet Mask
By | March 29, 2013
There are two types of addressing in networking: Physical addressing and logical addressing. Physical address is the MAC address (Media access control) which is fixed for a particular computer. Logical address is the IP (Internet Protocol) address. In this CCNA tutorial, you will get to know Internet Protocol version 4 (IPv4) and different network classes explained in a simple way.
What is an IP address?
Network IP address is used to identify a host (PC or any network device) in a network. IP is a 32 bit binary number divided into 4 octet groups, each octet giving a maximum of 255 in decimal. For easier addressing of these IP address octet, they are written as dotted decimals.
Must Read: [Complete Guide] Class A IP Address, Subnet Mask, and Subnetting
Note: How to find out a host IP address? You can go for the command prompt IP address check by typing ipconfig as shown in the screenshot below
Classes of IP address in networking
IP is divided into 5 classes of network addresses based on the range of first octet.
Out of the total valid addresses in each class, two dedicated IP address is reserved for;
1. Network address
2. Broadcast address
So the total number of available IP addresses will be
.
Public and Private IP addresses
To communicate over an internet, a device must have a public IP address which is provided by IANA (Internet Assigned Numbers Authority). Private range of IP addresses are used in an intranet (an internal network that uses internet technology). IANA also provides address for private networks in each class as follows:
Private Network Address Ranges in each Class
Before going in detail to IP classes we need to know about subnet masks and how to find subnet mask for IP addresses.
What is Subnet Mask?
If you’re a newbie to networking then the concept of Subnet mask may seem a little bit confusing, I also had a tough time struggling with subnet mask during my earlier days. By definition subnet mask is a 32 bit address used with an IP in order to identify its network and host portions.
Well, here I am going to put the simplest explanation for subnet mask. Please refer the network diagram below for better understanding. Let’s say you’ve got an IP address 200.1.1.2 with a subnet mask 255.255.255.0, it means that 200.1.1 is the network portion and last octet is the host portion. So any IP which starts with 200.1.1 goes to the same network (Network A), like 200.1.1.1, 200.1.1.10, 200.1.1.100 upto 200.1.1.254. And hence they don’t require a router to communicate with each other.
subnet mask explained
In Network A the first IP 200.1.1.0 is used to indicate network address and last IP 200.1.1.255 is used to send broadcast messages to all host computers in the network A.
Now another IP 200.1.2.2 which also has the same subnet mask cannot communicate with Network A without using a router because there’s a change in the network part. It belongs to another network with network address 200.1.2.0(Network B). Hope you got the point.
Another IP 10.1.1.2 with subnet mask 255.0.0.0 makes you understand that it belongs to the network 10.0.0.0(Network C), where only the first octet indicates network.
So subnet mask let’s you understand the IP belongs to which network. By default the following subnet masks are used.
Note: All host bits ‘0’ is a network address.
All host bits ‘1’is a broadcast address.
Now let us see network classes A B C D of internet protocol a little deeper.
Network Class Ranges with Subnet Mask
Class A Network
Class A network range starts from 1.0.0.0 to 126.255.255.255. See the screenshot for easier understanding.
Class A network subnet mask is 255.0.0.0, which means it has 8 network bits of which the first bit is fixed as ‘0’. And hence a total of 7 network bits and 24 host bits.
Hence total no. of network will be
Here 2 is subtracted as 0.0.0.0 is the default network and 127.0.0.0 is the loopback ip address used for checking proper functionality (self testing).
And total number of hosts per network will be
Here 2 is subtracted for network and broadcast address.
Class A network example:
Network address -1.0.0.0
Subnet Mask -255.0.0.0
First host IP address -1.0.0.1
Last host address -1.255.255.254
Broadcast address -1.255.255.255
Class B Network
Now class B network range starts from 128.0.0.0 to 191.255.255.255. Default subnet mask is 255.255.0.0, which means it has 16 network bits of which first two bits are fixed as ‘10’. And hence a total of 14 network bits and 16 host bits.
So total no. of networks will be
And the total number of hosts per network will be
2 IP’s are subtracted, one each for network and broadcast address.
Let us take an example:
Network address -128.0.0.0
Subnet Mask -255.255.0.0
First host address -128.0.0.1
Last host address -128.0.255.254
Broadcast address -128.0.255.255
Class C Network
IP range starts from 192.0.0.0 to 223.255.255.255. Class C network subnet mask is 255.255.255.0 that means it has 24 network bits of which the first three bits are fixed as ‘110’. So a total of 21 network bits and 8 host bits.
Hence total no. of network will be
And the total number of hosts per network will be
Here also 2 IP’s are subtracted, one for network and other for broadcast address.
Class C network example:
Network address -192.0.0.0
Subnet Mask -255.255.255.0
First host address -192.0.0.1
Last host address -192.0.0.254
Broadcast address -192.0.0.255
10 thoughts on “IP Address Classes and Ranges Explained with Subnet Mask
1. Ty
Thankyou so much for this. Every explanation I’ve read so far was overly complicated, but this explained it in a clear and simple way
Reply
1. Admin Post author
Hi,
You’re welcome, glad to know it helped you.
Reply
2. Bob
Thanks! On the spot! Clean logically and progressively understandable. Nice work.
Reply
3. Admin Post author
It’s great to see you here Bob, thanks for your valuable feedback. Keep visiting..
Reply
4. SD
I’ve looked all over the internet for a clear explanation of subnetting but this is the only one that made sense. Great work, cheers.
Reply
5. k v satish kumar
hi this is very very clear explanation , very very ……………….thank you .
Reply
6. Martin Bluck
I was looking for an easy to understand explanation of the function of a subnet mask, this is great; thank you.
Reply
Leave a Reply
Your email address will not be published. Required fields are marked *
|
__label__pos
| 0.567853 |
关于爬虫使用代理并发的总结
关于爬虫使用代理并发的总结
月光魔力鸭
2021-02-27 15:23 阅读 415 喜欢 1
最近一段时间想着做个资源网站,奈何没数据,准备从几个相关的站点上抓一些数据,数据量每个站点都在几千万左右,这里简单总结下最近一段时间在做的测试。
对于大部分内容网站来说,做反爬处理是必不可少的,其中最基本的就是限制ip的访问次数,然后就是做一些登录校验,做一些前端加密,再就是增加一些访问限制等等。
最近在抓的几个网站都存在限制IP访问的限制,再抓取了几百条后就无法继续抓取了,此时就需要代理IP来突破限制,最近碰到的问题是这样的:
站点本身的访问速度并不快,导致我抓一条记录接近5s ,如果按照这样下去的话,我得抓到明年去了,显然是不可行的。但是我还要保证代理IP可用且目标地址不遗漏。(代理IP存在不可用的情况)
所以最近几天一直都在尝试如何来处理这个问题,最开始的思路是:自己创建一个池子,每次池子中放进N个目标地址,然后启动M个程序来访问,成功则消掉,不成功则放回去,重新取。
经过了一天一夜的运行后发现速度还是慢的很,最多就是相对于一条一条的访问快了两三倍,但是对于如此大的数据量来讲,还是要持续很久,由于使用的代理IP是付费的,那么仅仅代理IP费用就入不敷出了。
后来又尝试着单个代理并发访问N个目标地址,但是这样又总是漏下失败的地址,而且经常会运行一段时间后卡住。
经过了几个版本的尝试,最终确定以下的一个思路:
1. 提供一个任务分配函数,由该函数提供给给定目标的任务数量
2. 启动多个进程,每个进程负责处理自己给定的目标,直到处理结束后,重新获取
3. 提供一个任务处理函数,负责处理目标任务,并返回给进程结果。
大致来说,这样兼顾的并发和多进程的处理,效率相对于之前又快了几倍,就目前来看,还是不够,主要是经常超时,需要对任务做超时处理,而且代理IP质量有点差,而且目标站点本身的抓取速度有点慢,导致整体的进度并不快。
但是并发量级又不能太大,太大了会导致目标站点访问瘫痪,导致影响站点正常用户访问。 感觉就目前这个速度,抓取完毕的话,估计还得三四年....
看来还是要做一些取舍的,数据漏一些也可以吧。
大体代码思路,以下代码不全,仅供参考。
const cluster = require('cluster');
let numCpus = 3;//require('os').cpus().length / 2;
const async = require('async');
const fetch = require('./fetch2');
let getProxy = require('./ip');
let getNext = require('./job');
const singleNum = 50;
let proxyMap = {}
function forkWorker (cluster) {
const worker = cluster.fork();
//获取任务和代理
getNext(singleNum, function (arr) {
worker.send(arr);
});
worker.on('message', async (data) => {
let type = data.type, obj = data.data;
if (type == 'changeProxy') {//更换代理
worker.send(obj);
} else if (type == 'over') {
getNext(singleNum, function (arr) {
worker.send(arr)
})
} else if (type == 'left') {
//存在剩余
worker.send(obj);
} else if (type == 'left2') {
worker.send(obj);
} else if (type == 'die') {
worker.kill();
}
})
}
if (cluster.isMaster) {
//创建worker
for (let i = 0; i < numCpus;i++) {
forkWorker(cluster);
}
cluster.on('exit', (worker, code, signal) => {
console.log(`worker ${worker.process.pid} died : ${signal}`)
})
//每隔10s检查进程
setInterval(function () {
let arr = [];
for (let id in cluster.workers) {
arr.push(cluster.workers[id].pid);
}
console.log(`当前进程数量:${arr.length} , ${arr}`)
},10 * 60 * 1000)
} else {
/**
* @params {Array} nextArr : 本次需要处理的任务数据
* @params {Object} proxy : 本地的代理数据
*/
process.on('message', async function (nextArr) {
let pid = process.pid;
if (!proxyMap[pid]) {
proxyMap[pid] = await getProxy();
}
let proxy = proxyMap[pid];
//开始工作
console.log(`${process.pid} 开始工作----`)
async.mapLimit(nextArr, nextArr.length, async function (item) {
let flag = await fetch(item, proxy);
return {
flag: flag,
item : item
};
}, async function (err, results) {
if (err) {
console.log(err);
}
let allTotal = results.length;
let sucNum = results.filter(t => {
return t.flag == 2;
});
let carr = results.filter(t => {
return t.flag != 2;
}).map(t => t.item);
console.log(`${process.pid}:结果: [总数: ${allTotal}] - [成功: ${sucNum.length}] - [失败:${carr.length}]`)
if (carr.length > 1) {
if (allTotal - carr.length < 5) {
proxyMap[pid] = await getProxy();
}
process.send({type : 'left2',data : carr })
} else {
//全部获取结束
process.send({type : 'over'})
}
})
})
}
转载请注明出处: https://chrunlee.cn/article/spider-proxy-result.html
感谢支持!
赞赏支持
提交评论
评论信息 (请文明评论)
暂无评论,快来快来写想法...
推荐
mysql数据库插入double类型确没有小数点
docker build 执行yum失败,找不到repo
接下来,我们综合上面的配置,再加一个选项页面配置,做一个天气预报的小栗子。
需求:可能会有在页面加载的时候想执行某个js,例如统计页面的DOM等等。
通过registry 自建 dockerhub
昨天客户发现了个小BUG,文章发布使用的ueditor, 上传视频的时候当时好好的,后来怎么就是播放不了?
浏览网页的时候经常会有文本无法选中,无法复制的情况,这里简单说个简单的方法,不需要下载什么东西,也不用安装什么软件、插件、油猴啥的都不需要。
简单记录下dockerfile 以及compose配置
|
__label__pos
| 0.997481 |
algebra
Factor each polynomial by factoring out the GCF.
2a^2 - 4ab^2 -ab
1. 0
2. 0
3. 10
asked by Jessica
1. By inspection, you will find a the GCF. The coefficient of the third term is -1, and the first term does not contain b, so numbers and b are not part of the GCF.
Divide each term by the GCF to get the factors:
2a² - 4ab² -ab
= a(2a-4b² -b)
1. 0
2. 0
posted by MathMate
Respond to this Question
First Name
Your Response
Similar Questions
1. polynomials
lol, i also have these Factor the polynomial x2 + 3x – 18. Which one of the following is a factor? Factor the polynomial 12x2 + 11x – 5 completely. Factor the polynomial 18a2b – 4ab + 10a completely Factor the polynomial 2x2
asked by mike on May 16, 2007
2. Algebra
Factoring Polynomials GCF and Quadratic Expressions: 5b^2k^2+25bk^2-250k^2 The answer I figured was GCF for the polynomial is 5 and the GCF for the variable is bk^2. Is this correct.
asked by Mary on December 3, 2017
3. algebra
The first three equations I have solved, I would just appreciate someone checking them over to make sure I'm doing them right. Find the GCF: 16x^2z ,40xz^2 , 72z^3 = 3^3z Factor our GCF: a(a+1) - 3(a+1) = a+1 Factor Polynomial:
asked by kay bri on January 23, 2009
4. Algebra
The first three equations I have solved, I would just appreciate someone checking them over to make sure I'm doing them right. Find the GCF: 16x^2z ,40xz^2 , 72z^3 = 3^3z Factor our GCF: a(a+1) - 3(a+1) = a+1 Factor Polynomial:
asked by KB on January 23, 2009
5. algebra 1
Can someone solve theses for me? Factor the polynomial x2 + 7x + 12 completely Factor the polynomial x2 – 4 completely Factor the polynomial 18a2b – 4ab + 10a completely x2 + 7x + 12 = (x+4)(x+3) x2 – 4 = (x+2)(x-2) 18a2b
asked by mike on May 16, 2007
6. Algebra 1-Factor by Grouping Help!
Factor. Use factoring by grouping even though it would seem reasonable to first combine like terms 3u^2-7-21u+49 Would be the same procedure as factoring polynomial? Thanks!
asked by clary on March 31, 2016
7. Algebra
I have a question I hope someone can explain it to me. We are working on Demonstrate that f actoring a polynomial. I was ask Why can you factor x² - 4 but you cannot factor x² + 4? How can you tell quickly which ones you can
asked by TOM on November 12, 2008
8. Algebra 2
I am trying to factor a 4th degree polynomial that does not have any rational roots. I need to somehow get it factored into two quadratics. Anyone know of a method to use. 3x^4 - 8x^3 - 5x^2 + 16x - 5 Two of the irrational roots
asked by Brenda on March 9, 2007
9. Math
Factor completely. Always begin by factoring the GCF. ax(squared)p-8pa-2axp
asked by Angelica on February 14, 2010
10. Liberal Arts Math
how would i solve this problem?? it says factor the polynomial completely: 2xy-3y-40x+60 I studied polynomials, but I don't know what it means to factor them. Do you have a definition in your textbook or notes or something? B-cuz
asked by Maria on May 11, 2007
More Similar Questions
|
__label__pos
| 0.812541 |
Learning to Code in One’s Own Language
I recently published a paper with Sayamindu Dasgupta that provides evidence in support of the idea that kids can learn to code more quickly when they are programming in their own language.
Millions of young people from around the world are learning to code. Often, during their learning experiences, these youth are using visual block-based programming languages like Scratch, App Inventor, and Code.org Studio. In block-based programming languages, coders manipulate visual, snap-together blocks that represent code constructs instead of textual symbols and commands that are found in more traditional programming languages.
The textual symbols used in nearly all non-block-based programming languages are drawn from English—consider “if” statements and “for” loops for common examples. Keywords in block-based languages, on the other hand, are often translated into different human languages. For example, depending on the language preference of the user, an identical set of computing instructions in Scratch can be represented in many different human languages:
Examples of a short piece of Scratch code shown in four different human languages: English, Italian, Norwegian Bokmål, and German.
Although my research with Sayamindu Dasgupta focuses on learning, both Sayamindu and I worked on local language technologies before coming back to academia. As a result, we were both interested in how the increasing translation of programming languages might be making it easier for non-English speaking kids to learn to code.
After all, a large body of education research has shown that early-stage education is more effective when instruction is in the language that the learner speaks at home. Based on this research, we hypothesized that children learning to code with block-based programming languages translated to their mother-tongues will have better learning outcomes than children using the blocks in English.
We sought to test this hypothesis in Scratch, an informal learning community built around a block-based programming language. We were helped by the fact that Scratch is translated into many languages and has a large number of learners from around the world.
To measure learning, we built on some of our our own previous work and looked at learners’ cumulative block repertoires—similar to a code vocabulary. By observing a learner’s cumulative block repertoire over time, we can measure how quickly their code vocabulary is growing.
Using this data, we compared the rate of growth of cumulative block repertoire between learners from non-English speaking countries using Scratch in English to learners from the same countries using Scratch in their local language. To identify non-English speakers, we considered Scratch users who reported themselves as coming from five primarily non-English speaking countries: Portugal, Italy, Brazil, Germany, and Norway. We chose these five countries because they each have one very widely spoken language that is not English and because Scratch is almost fully translated into that language.
Even after controlling for a number of factors like social engagement on the Scratch website, user productivity, and time spent on projects, we found that learners from these countries who use Scratch in their local language have a higher rate of cumulative block repertoire growth than their counterparts using Scratch in English. This faster growth was despite having a lower initial block repertoire. The graph below visualizes our results for two “prototypical” learners who start with the same initial block repertoire: one learner who uses the English interface, and a second learner who uses their native language.
Summary of the results of our model for two prototypical individuals.
Our results are in line with what theories of education have to say about learning in one’s own language. Our findings also represent good news for designers of block-based programming languages who have spent considerable amounts of effort in making their programming languages translatable. It’s also good news for the volunteers who have spent many hours translating blocks and user interfaces.
Although we find support for our hypothesis, we should stress that our findings are both limited and incomplete. For example, because we focus on estimating the differences between Scratch learners, our comparisons are between kids who all managed to successfully use Scratch. Before Scratch was translated, kids with little working knowledge of English or the Latin script might not have been able to use Scratch at all. Because of translation, many of these children are now able to learn to code.
This blog post and the work that it describes is a collaborative project with Sayamindu Dasgupta. Sayamindu also published a very similar version of the blog post in several places. Our paper is open access and you can read it here. The paper was published in the proceedings of the ACM Learning @ Scale Conference. We also recently gave a talk about this work at the International Communication Association’s annual conference. We received support and feedback from members of the Scratch team at MIT (especially Mitch Resnick and Natalie Rusk), as well as from Nathan TeBlunthuis at the University of Washington. Financial support came from the US National Science Foundation.
8 Replies to “Learning to Code in One’s Own Language”
1. This is a great study, thank you (both) for looking into it. In New Zealand, a similar idea has come up for Maori kids learning coding through modding [a popular Java game].
It may be out of scope for what you’ve looked at, but I’m curious as to how you think this impacts whatever comes after Scratch. I’m on a team teaching Pygame to year 5 kids who have had several terms of Scratch, so it’s common for me to refer to concepts from Scratch whilst introducing the same concepts in Python. I’m wondering whether teaching kids the “wrong” keywords like if, else, click, pressed, and so on, sets them back a little when they graduate to the next English-based programming language.
Then again, maybe it’s the concepts that Scratch teachs, more than the words, that matter, and losing the translation upon graduation is negligible.
1. Hmm, now that you mention it, I see a similar difficulty for some to do the step from Scratch to a classic programming language (Python or something else)… the comparison helps, up to a point (also, for some less imaginative participants, it’s necessary to either have Scratch open in parallel to *show* the parallelities *and* demonstrate them in a runnable example, or better to completely ignore it).
2. I quite disagree here.
I learnt three programming languages before English (with a dab of Latin in between), and just learnt the words BASIC, Assembly and Pascal have as things-that-do-something without any connection to the English words they were based on (which, I notice now, incidentally helps me to not have the wrong connotations with it).
At Teckids e.V. we also teach NXT robot programming in NXC, not a block language (while, on the other hand, we do occasionally use Scratch as a stepping stone to the pure-on-computer, less hands-on, Python game programming courses). The kids, even those not already knowing English, do not have any problem at all to grasp what few vocabulary there is.
This objection is biased because our native language also uses the Latin alphabet. I would agree with the localisation approach for languages not using left-to-right-then-top-to-bottom writing order, and languages not using the Latin alphabet or something resembling it closely enough.
1. Of course, our results might be wrong or misleading for lots of reasons that we can’t rule out. That said, I think it’s important to keep in mind that our results are not about what worked for you or what worked for the kids who attend the Techkids workshops. Our results are about what happened on average in our dataset of Scratch users and, in this dataset, kids who used localized interfaces learned slightly faster. It’s also worth keeping in mind that our results do not suggest that users of English interfaces don’t learn! Our results suggest that kids in our sample learn at a pretty similar rate when using English and localized interfaces in Scratch. As a result, we’re not suggesting that all kids will be stopped in their tracks. Our results suggest that the users of the the localized interfaces pick up blocks slightly quicker.
Leave a Reply to mirabilos Cancel reply
Your email address will not be published. Required fields are marked *
|
__label__pos
| 0.882917 |
Ecuaciones Diferenciales I: Ecuaciones lineales de segundo orden con coeficientes variables – Soluciones en series de potencias respecto a puntos singulares
Introducción
Hemos comenzado con el estudio de ecuaciones diferenciales lineales de segundo orden con coeficientes variables. Ya hemos aprendido cómo obtener soluciones con respecto a puntos ordinarios, ahora aprenderemos a obtener soluciones con respecto a puntos singulares.
En la entrada anterior vimos que para resolver ecuaciones es su forma estándar
$$\dfrac{d^{2}y}{dx^{2}} + P(x) \dfrac{dy}{dx} + Q(x)y = 0 \label{1} \tag{1}$$
se proponía una solución de la forma
$$y(x) = \sum_{n = 0}^{\infty}c_{n}(x -x_{0})^{n} \label{2} \tag{2}$$
donde $x_{0}$ es un punto ordinario de la ecuación diferencial (\ref{1}).
En ocasiones no se pueden encontrar soluciones como (\ref{2}), así que se propone una solución de la forma
$$y(x) = (x -x_{0})^{r} \sum_{n = 0}^{\infty}c_{n}(x -x_{0})^{n} \label{3} \tag{3}$$
Donde $r$ es una constante. En realidad, la solución (\ref{3}) es una generalización ya que si $r = 0$ regresamos a la forma (\ref{2}).
En esta entrada aprenderemos a resolver ecuaciones diferenciales en las que su solución es de la forma (\ref{3}).
Puntos singulares
El que la solución de una ecuación diferencial sea de la forma (\ref{3}) esta directamente relacionado con que el punto $x_{0}$ sea un punto singular y no un punto ordinario. En la entrada anterior definimos estos conceptos, sin embargo en esta entrada es necesario profundizar más acerca de los puntos singulares. Recordemos la definición de punto singular.
Nota: Las siguientes definiciones se basan en la forma estándar (\ref{1}) de una ecuación diferencial lineal de segundo orden.
Definición: Un punto $x_{0}$ en el que al menos una de las funciones $P(x)$ y $Q(x)$ no tiene representación en serie de potencias de $(x -x_{0})$ se dice que es un punto singular de (\ref{1}).
Lo nuevo ahora es que un punto singular puede ser clasificado como regular o irregular.
Definición: Un punto $x_{0}$ es singular regular si las funciones
$$p(x) = (x -x_{0})P(x) \hspace{1cm} y \hspace{1cm} q(x) = (x -x_{0})^{2}Q(x) \label{4} \tag{4}$$
son analíticas en $x_{0}$.
Definición: Si una o ambas de las funciones $p(x)$ y $q(x)$ de (\ref{4}) no son analíticas en un punto $x_{0}$, entonces $x_{0}$ es un punto singular irregular.
Para fines prácticos en conveniente definir los puntos singulares regulares e irregulares a través de un límite.
Definición: Un punto $x_{0}$ es singular regular de la ecuación (\ref{1}) si los siguientes límites existen:
$$\lim_{x \to x_{0}} p(x) = \lim_{x \to x_{0}} (x -x_{0})P(x) \hspace{1cm} y \hspace{1cm} \lim_{x \to x_{0}} q(x) = \lim_{x \to x_{0}} (x -x_{0})^{2}Q(x) \label{5} \tag{5}$$
En caso contrario decimos que $x_{0}$ es un punto singular irregular.
Realicemos algunos ejemplos.
Ejemplo: Clasificar los puntos singulares de la ecuación diferencial $x^{3}(x^{2} -9) \dfrac{d^{2}y}{dx^{2}} + (x+3) \dfrac{dy}{dx} + (x -3)^{3}y = 0$.
Solución: El primer paso es escribir a la ecuación diferencial en la forma estándar (\ref{1}), así que dividimos toda la ecuación por el coeficiente de la segunda derivada de $y$.
$$\dfrac{d^{2}y}{dx^{2}} + \dfrac{1}{x^{3}(x -3)} \dfrac{dy}{dx} + \dfrac{(x -3)^{2}}{x^{3}(x + 3)} y = 0$$
Identificamos que
$P(x) = \dfrac{1}{x^{3}(x -3)} \hspace{1cm} y \hspace{1cm} Q(x) = \dfrac{(x -3)^{2}}{x^{3}(x + 3)}$
Notamos que la función $P(x)$ no está definida en los puntos $x = 3$ y $x = 0$, mientras que la función $Q(x)$ no está definida en $x = -3$ y $x = 0$, de manera que los puntos singulares son $x_{0} = 3$, $x_{0} = 0$ y $x_{0} = -3$. El resto de puntos en $\mathbb{R}$ son puntos ordinarios de la ecuación diferencial.
Para determinar si son regulares o irregulares vamos a definir las nuevas funciones de acuerdo a (\ref{4}) y observar si dichas funciones son analíticas o no en el correspondiente punto singular.
Caso 1: $x_{0} = 3$
Definimos las nuevas funciones
$$p(x) = (x -3)P(x) = \dfrac{1}{x^{3}} \hspace{1cm} y \hspace{1cm} q(x) = (x-3)^{2}Q(x) = \dfrac{(x -3)^{4}}{x^{3}(x + 3)}$$
Es claro que las nuevas funciones $p(x)$ y $q(x)$ sí son analíticas en $x_{0} = 3$ por lo que dicho punto es un punto singular regular. Usando la definición de límite tenemos que
$$\lim_{x \to 3} p(x) = \lim_{x \to 3}\dfrac{1}{x^{3}} = \dfrac{1}{9} \hspace{1cm} y \hspace{1cm} \lim_{x \to 3} q(x) = \lim_{x \to 3} \dfrac{(x -3)^{4}}{x^{3}(x + 3)} = 0$$
Los límites existen, así que llegamos a la misma conclusión.
Caso 2: $x_{0} = 0$
Definimos las nuevas funciones
$$p(x) = x P(x) = \dfrac{1}{x^{2}(x -3)} \hspace{1cm} y \hspace{1cm} q(x) = x^{2} Q(x) = \dfrac{(x -3)^{2}}{x(x + 3)}$$
En este caso las funciones $p(x)$ y $q(x)$ siguen sin estar definidas para $x = 0$ lo que significa que no se pueden representar mediante una serie de potencias, es decir, no son analíticas en dicho punto. Veamos que ocurre con los limites. Por un lado,
$$\lim_{x \to 0}p(x) = \lim_{x \to 0}\dfrac{1}{x^{2}(x -3)} = -\infty$$
Por otro lado
$$\lim_{x \to 0^{+}} q(x) = \lim_{x \to 0^{+}} \dfrac{(x -3)^{2}}{x(x + 3)} = \infty \hspace{1cm} y \hspace{1cm} \lim_{x \to 0^{-}} q(x) = \lim_{x \to 0^{-}} \dfrac{(x -3)^{2}}{x(x + 3)} = -\infty $$
Vemos que el limite de $p(x)$ es divergente, mientras que el límite de $q(x)$ no existe en $x = 0$. En conclusión, $x_{0} = 0$ es un punto singular irregular.
Caso 3: $x_{0} = -3$
Definimos las nuevas funciones
$$p(x) = (x+3) P(x) = \dfrac{x + 3}{x^{3}(x -3)} \hspace{1cm} y \hspace{1cm} q(x) = (x + 3)^{2} Q(x) = \dfrac{(x -3)^{2}(x + 3)}{x^{3}}$$
Las nuevas funciones son analíticas en $x_{0} = -3$, confirmemos que los límites existen
$$\lim_{x \to -3} p(x) = \lim_{x \to -3} \dfrac{x + 3}{x^{3}(x -3)} = 0 \hspace{1cm} y \hspace{1cm} \lim_{x \to -3} q(x) = \lim_{x \to -3} \dfrac{(x -3)^{2}(x + 3)}{x^{3}} = 0$$
En efecto, los limites existen así que $x_{0} = -3$ es un punto singular regular.
$\square$
Realicemos un ejemplo más.
Ejemplo: Determinar el punto singular de la ecuación diferencial $(x + 1)^{2} \dfrac{d^{2}y}{dx^{2}} + x \dfrac{dy}{dx} + x^{2} y = 0$.
Solución: Escribimos a la ecuación diferencial en su forma estándar.
$$\dfrac{d^{2}y}{dx^{2}} + \dfrac{x}{(x + 1)^{2}} \dfrac{dy}{dx} + \dfrac{x^{2}}{(x + 1)^{2}} y = 0$$
Identificamos que
$$P(x) = \dfrac{x}{(x + 1)^{2}} \hspace{1cm} y \hspace{1cm} Q(x) = \dfrac{x^{2}}{(x + 1)^{2}}$$
Notamos que el único punto singular es $x_{0} = -1$. Definamos las funciones $p(x)$ y $q(x)$.
$$p(x) = (x + 1)P(x) = \dfrac{x}{x+1} \hspace{1cm} y \hspace{1cm} q(x) = (x + 1)^{2}Q(x) = x^{2}$$
Aunque la función $q(x)$ si es analítica en $x_{0} = -1$, como $p(x)$ no lo es, entonces la ecuación diferencial no es desarrollable en potencias de $x + 1$ y por definición $x_{0} = -1$ es un punto singular irregular.
$\square$
Solución a ecuaciones diferenciales
Ahora que sabemos identificar puntos singulares de una ecuación diferencial podemos resolverlas con respecto a dichos puntos proponiendo una solución de la forma (\ref{3}). Ahora bien, debido a la complejidad de los cálculos, sólo estudiaremos el caso en el que el punto $x_{0} = 0$ es un punto singular regular. Igual que en el caso anterior, si $x_{0} \neq 0$ podemos utilizar el cambio de variable $t = x -x_{0}$.
A continuación enunciamos el teorema que establece que (\ref{3}) es una solución a la ecuación diferencial (\ref{1}) con respecto al punto singular $x_{0}$.
Teorema: Sea (\ref{1}) una ecuación diferencial con un punto singular regular en $x_{0}$, entonces siempre existe al menos una solución de la forma:
$$y(x) = (x -x_{0})^{r} \sum_{n = 0}^{\infty } c_{n}(x -x_{0})^{n} = \sum_{n = 0}^{\infty } c_{n}(x -x_{0})^{n + r} \label{6} \tag{6}$$
que converge en $0 < |x -x_{0}| < R$. Esta serie recibe el nombre de serie de Frobenius.
Con este teorema podemos establecer que:
• Si $x_{0}$ es un punto ordinario, entonces $r = 0$ y (\ref{2}) es la solución general.
• Si $x_{0}$ es un punto singular regular, entonces (\ref{6}) dará una solución o la solución general.
• Si $x_{0}$ es un punto singular irregular, entonces pueden o no existir soluciones de la forma (\ref{6}).
No demostraremos este teorema pero será la base para resolver ecuaciones diferenciales.
La manera de resolver ecuaciones diferenciales con respecto a puntos singulares es bastante similar al caso de soluciones con respecto a puntos ordinarios, sin embargo en este caso, además de obtener una relación de recurrencia, obtendremos una ecuación cuadrática para $r$ que deberemos de resolver, a dicha ecuación se le conoce como ecuación indicial.
A continuación desarrollaremos el método de resolución que nos permitirá obtener la expresión general de la ecuación indicial, dicho método se conoce como método de Frobenius.
Método de Frobenius
Queremos resolver una ecuación diferencial en su forma estándar con respecto al punto singular regular $x_{0} = 0$.
$$\dfrac{d^{2}y}{dx^{2}} + P(x) \dfrac{dy}{dx} + Q(x)y = 0$$
Multipliquemos esta ecuación por $x^{2}$:
$$x^{2} \dfrac{d^{2}y}{dx^{2}} + x [xP(x)] \dfrac{dy}{dx} + [x^{2}Q(x)] y = 0$$
Si usamos las definiciones (\ref{4}) para $x_{0} = 0$, entonces podemos escribir la ecuación anterior de la siguiente manera:
$$x^{2}\dfrac{d^{2}y}{dx^{2}} + xp(x) \dfrac{dy}{dx} + q(x)y = 0 \label{7} \tag{7}$$
Con $p(x)$ y $q(x)$ funciones analíticas en $x = 0$, esto significa que se pueden representar mediante una serie de potencias con respecto a dicho punto, sean
$$p(x) = p_{0} + p_{1}x + p_{2}x^{2} + \cdots = \sum_{n = 0}^{\infty} p_{n}x^{n} \label{8} \tag{8}$$
y
$$q(x) = q_{0} + q_{1}x + q_{2}x^{2} + \cdots = \sum_{n = 0}^{\infty} q_{n}x^{n} \label{9} \tag{9}$$
dichas series. Una observación interesante es que si todos los coeficientes son cero excepto $p_{0}$ y $q_{0}$, entonces recuperamos la ecuación de Cauchy-Euler.
$$x^{2}\dfrac{d^{2}y}{dx^{2}} + p_{0}x \dfrac{dy}{dx} + q_{0}y = 0 \label{10} \tag{10}$$
El teorema anterior nos indica que la forma de la solución es
$$y(x) = \sum_{n = 0}^{\infty}c_{n}x^{n + r}$$
La primera y segunda derivada son:
$$\dfrac{dy}{dx} = \sum_{n = 0}^{\infty}(n + r)c_{n}x^{n + r -1} \hspace{1cm} y \hspace{1cm} \dfrac{d^{2}y}{dx^{2}} = \sum_{n = 0}^{\infty}(n + r)(n + r -1)c_{n}x^{n + r -2}$$
Sustituyamos todos estos resultados en la ecuación diferencial (\ref{7}):
\begin{align*}
x^{2} \sum_{n = 0}^{\infty}(n + r)(n + r -1)c_{n}x^{n + r -2} &+ x \left[ \sum_{n = 0}^{\infty} p_{n}x^{n} \right] \sum_{n = 0}(n + r)c_{n}x^{n + r -1} \\
&+ \left[ \sum_{n = 0}^{\infty} q_{n}x^{n} \right] \sum_{n = 0}^{\infty}c_{n}x^{n + r} = 0
\end{align*}
Introducimos los términos $x^{2}$ y $x$ a las series de las derivadas de $y$:
\begin{align*}
\sum_{n = 0}^{\infty}(n + r)(n + r -1)c_{n}x^{n + r} &+ \left[ \sum_{n = 0}^{\infty} p_{n}x^{n} \right] \sum_{n = 0}(n + r)c_{n}x^{n + r} \\
&+ \left[ \sum_{n = 0}^{\infty} q_{n}x^{n} \right] \sum_{n = 0}^{\infty}c_{n}x^{n + r} = 0
\end{align*}
Tomemos los términos para $n = 0$
\begin{align*}
r(r -1)c_{0}x^{r} + p_{0}rc_{0}x^{r} + q_{0}c_{0}x^{r} &= 0 \\
c_{0}x^{r} [r(r -1) + p_{0}r + q_{0}] &= 0
\end{align*}
Sabemos que $x^{r} \neq 0$ y el método nos obliga a considerar que siempre $c_{0} \neq 0$, entonces
$$r(r -1) + p_{0}r + q_{0} = 0$$
o bien,
$$r^{2} + (p_{0} -1)r + q_{0} = 0 \label{11} \tag{11}$$
Esta relación corresponde a la ecuación indicial con raíces $r_{1}$ y $r_{2}$ reales. En todos los casos se le asigna a $r_{1}$ la raíz mayor, es decir, debe ocurrir que $r_{1} > r_{2}$ siempre y cuando no sean raíces repetidas. A las raíces $r_{1}$ y $r_{2}$ se les denomina raíces indiciales.
El siguiente paso en el método es continuar igualando cada término a cero a través de una relación de recurrencia y con ello determinar los coeficientes de la solución propuesta $y(x)$, todo de manera similar que en el método de la entrada anterior.
En el enunciado del teorema enfatizamos que hay al menos una solución, esto significa que no siempre puede obtenerse una segunda serie solución que junto con la primera serie forme la solución general de la ecuación diferencial. No lo demostraremos, pero a continuación se muestra la forma de ambas soluciones linealmente independientes de acuerdo a los casos que pueden ocurrir con las raíces indiciales.
De acuerdo a la ecuación indicial (\ref{11}) se distinguen tres casos:
• Caso 1: $r_{1} -r_{2} \neq$ número entero.
En este caso las soluciones a la ecuación diferencial (\ref{1}) son:
$$y_{1}(x) = \sum_{n = 0}^{\infty}c_{n}x^{n + r_{1}}, \hspace{1cm} c_{0} \neq 0 \label{12} \tag{12}$$
$$y_{2}(x) = \sum_{n = 0}^{\infty}\hat{c}_{n}x^{n + r_{2}}, \hspace{1cm} \hat{c}_{0} \neq 0 \label{13} \tag{13}$$
• Caso 2: $r_{1} = r_{2} = r$.
En el caso en el que ambas raíces indiciales son iguales las soluciones a la ecuación diferencial (\ref{1}) son:
$$y_{1}(x) = \sum_{n = 0}^{\infty}c_{n}x^{n + r}, \hspace{1cm} c_{0} \neq 0 \label{14} \tag{14}$$
$$y_{2}(x) = y_{1}(x) \ln(x) + \sum_{n = 0}^{\infty}\hat{c}_{n}x^{n + r} \label{15} \tag{15}$$
• Caso 3: $r_{1} -r_{2} =$ entero positivo.
En este caso las soluciones a la ecuación diferencial (\ref{1}) son:
$$y_{1}(x) = \sum_{n = 0}^{\infty}c_{n}x^{n + r_{1}}, \hspace{1cm} c_{0} \neq 0 \label{16} \tag{16}$$
$$y_{2}(x) = Cy_{1}(x) \ln(x) + \sum_{n = 0}^{\infty}\hat{c}_{n}x^{n + r_{2}}, \hspace{1cm} \hat{c}_{0} \neq 0 \label{17} \tag{17}$$
Donde $C$ es una constante que podría ser cero.
En todos los casos $y_{1}(x)$ y $y_{2}(x)$ son linealmente independientes y la solución general es
$$y(x) = C_{1}y_{1}(x) + C_{2}y_{2}(x) \label{18} \tag{18}$$
En los casos en los que el método de Frobenius no nos de una segunda solución es posible obtenerla con métodos que ya hemos estudiado antes. El primero de ellos es usar variación de parámetros, en este caso se propone la solución $y_{2}(x) = u(x)y_{1}(x)$ y se sustituye, junto con las derivadas correspondientes, en la ecuación diferencial, esto nos permitirá obtener una ecuación diferencial para $u(x)$ que debemos resolver.
Otro método es usar directamente la forma de las soluciones $y_{2}(x)$ propuestas anteriormente para cada caso, calcular las derivadas correspondientes y sustituir en la ecuación diferencial.
Un tercer método se puede aplicar una vez que ya hemos determinado la primer solución $y_{1}(x)$ y es usando la expresión que deducimos en entradas anteriores.
$$y_{2}(x) = y_{1}(x) \int{\dfrac{e^{-\int{P(x) dx}}}{y_{1}^{2}(x)} dx} \label{19} \tag{19}$$
La mejor manera de comprender algo es a través de ejemplos y práctica así que hemos decidido resolver tres ejemplos, uno para cada caso y así poder comprender del todo en qué consiste el método de Frobenius.
Cabe mencionar que a lo largo de esta entrada te hemos dado las herramientas para trabajar, pero no se ha dado un fundamento formal de los resultados, si lo deseas conocer te invitamos a que estudies el tema correspondiente en la sección de videos de este curso, en él encontrarás los fundamentos de cómo es que se obtienen las soluciones linealmente independientes dadas para cada condición de las raíces indiciales.
Para concluir esta entrada te presentamos los 3 ejemplos antes mencionados.
Solución cuando la diferencia de las raíces indiciales difiere de un número entero
Ejemplo: Resolver la ecuación diferencial $3x^{2} \dfrac{d^{2}y}{dx^{2}} -x\dfrac{dy}{dx} + (1 -x) y = 0$, con respecto al punto singular $x_{0} = 0$.
Solución: Dividimos la ecuación diferencial por el coeficiente de la segunda derivada de $y$ para obtener la forma estándar.
$$\dfrac{d^{2}y}{dx^{2}} -\dfrac{1}{3x} \dfrac{dy}{dx} + \dfrac{1 -x}{3x^{2}}y = 0$$
Identificamos que
$$P(x) = -\dfrac{1}{3x} \hspace{1cm} y \hspace{1cm} Q(x) = \dfrac{1-x}{3x^{2}}$$
Nota que ninguna función está definida en $x = 0$. Definimos las funciones $p(x)$ y $q(x)$ de acuerdo a (\ref{4}).
$$p(x) = -\dfrac{1}{3} \hspace{1cm} y \hspace{1cm} q(x) = \dfrac{1-x}{3}$$
Vemos que
$$\lim_{x \to 0} p(x) = -\dfrac{1}{3} \hspace{1cm} y \hspace{1cm} \lim_{x \to 0} q(x) = \dfrac{1}{3}$$
Esto nos muestra que $p(x)$ y $q(x)$ son analíticas en $x = 0$ y que dicho punto es un punto singular regular.
Vamos a obtener la ecuación indicial directamente de la expresión (\ref{11}).
Vemos que
$$p(x) = \sum_{n = 0}^{\infty}p_{n}x^{n} = p_{0} + p_{1}x + p_{2}x^{2} + \cdots = -\dfrac{1}{3}$$
de donde, $p_{0} = -\dfrac{1}{3}$ y $p_{k} = 0$ $\forall$ $k \geqslant 1$ con $k \in \mathbb{N}$. Por otro lado
$$q(x) = \sum_{n = 0}^{\infty}q_{n}x^{n} = q_{0} + q_{1}x + q_{2}x^{2} + \cdots = \dfrac{1}{3} -\dfrac{1}{3}x$$
de donde, $q_{0} = \dfrac{1}{3}$, $q_{1} = -\dfrac{1}{3}$ y $q_{k} = 0$ $\forall$ $k \geqslant 2$ con $k \in \mathbb{N}$.
Sustituyendo $p_{0}$ y $q_{0}$ en la ecuación indicial (\ref{11}) se tiene
$$r^{2} + \left( -\dfrac{1}{3} -1 \right)r + \dfrac{1}{3} = r^{2} -\dfrac{4}{3}r + \dfrac{1}{3} = 0$$
Resolviendo para $r$ se obtiene que $r_{1} = 1$ y $r_{2}= \dfrac{1}{3}$. Notamos que $r_{1} -r_{2} = \dfrac{2}{3} \neq$ entero, es decir, la diferencia de las raíces indiciales difiere de un número entero, esto nos indica que estamos en condiciones del caso 1 en donde las soluciones están dadas por las funciones (\ref{12}) y (\ref{13}).
$$y_{1}(x) = \sum_{n = 0}^{\infty}c_{n}x^{n + 1}, \hspace{1cm} c_{0} \neq 0$$
y
$$y_{2}(x) = \sum_{n = 0}^{\infty}\hat{c}_{n}x^{n + 1/3}, \hspace{1cm} \hat{c}_{0} \neq 0$$
Para continuar con el método de Frobenius consideramos la solución general $\sum_{n = 0}^{\infty}c_{n}x^{n + r}$ y sus derivadas. Una vez obtenida la relación de recurrencia ya se podrá sustituir los valores correspondientes de $r$. Sustituimos en la ecuación diferencial.
$$3x^{2} \left[ \sum_{n = 0}^{\infty} (n + r)(n + r -1)c_{n}x^{n + r -2} \right] -x \left[ \sum_{n = 0}^{\infty}(n + r)c_{n}x^{n + r -1} \right] + (1 -x) \left[ \sum_{n = 0}^{\infty}c_{n}x^{n + r} \right] = 0$$
$$3 \sum_{n = 0}^{\infty}(n + r)(n + r -1)c_{n}x^{n + r} -\sum_{n = 0}^{\infty}(n + r)c_{n}x^{n + r} + \sum_{n = 0}^{\infty}c_{n}x^{n + r} -\sum_{n = 0}^{\infty}c_{n}x^{n + r + 1} = 0$$
En la última serie hacemos $k = n + 1$ y en el resto $k = n$.
$$3 \sum_{k = 0}^{\infty}(k + r)(k + r -1)c_{k}x^{k + r} -\sum_{k = 0}^{\infty}(k + r)c_{k}x^{k + r} + \sum_{k = 0}^{\infty}c_{k}x^{k + r} -\sum_{k = 1}^{\infty}c_{k -1}x^{k + r} = 0$$
Para que todas las series comiencen en $k = 1$ sacamos el primer término de las tres primeras series.
\begin{align*}
3r(r -1)c_{0}x^{r} -rc_{0}x^{r} + c_{0}x^{r} &= 0 \\
c_{0}x^{r} \left[ 3r(r -1) -r + 1 \right] &= 0
\end{align*}
Como $x^{r} \neq 0$ y $c_{0} \neq 0$, entonces
\begin{align*}
3r(r -1) -r + 1 &= 0 \\
3r^{2} -4r + 1 &= 0
\end{align*}
Puedes observar que hemos obtenido nuevamente la ecuación indicial. Ahora nos queda la ecuación
$$3 \sum_{k = 1}^{\infty}(k + r)(k + r -1)c_{k}x^{k + r} -\sum_{k = 1}^{\infty}(k + r)c_{k}x^{k + r} + \sum_{k = 1}^{\infty}c_{k}x^{k + r} -\sum_{k = 1}^{\infty}c_{k -1}x^{k + r} = 0$$
Podemos juntar todas las series en una sola.
$$\sum_{k = 1}^{\infty} [3(k + r)(k + r -1)c_{k} -(k + r)c_{k} + c_{k} -c_{k -1}]x^{k + r} = 0$$
Para satisfacer la igualdad es necesario que
$$c_{k} [3(k + r)(k + r -1) -(k + r) + 1] -c_{k -1} = 0$$
Despejando a $c_{k}$ obtenemos la relación de recurrencia
$$c_{k} = \dfrac{c_{k -1}}{3(k + r)(k + r -1) -(k + r) +1}, \hspace{1cm} k = 1, 2, 3, \cdots$$
Hay que determinar los coeficientes para cada valor de las raíces indiciales. Para el valor de la primer raíz indicial $r = 1$, la relación de recurrencia es
$$c_{k} = \dfrac{c_{k -1}}{k(3k + 2)}, \hspace{1cm} k = 1, 2, 3, \cdots$$
Determinemos los coeficientes para este caso.
$k = 1$:
$$c_{1} = \dfrac{c_{0}}{1(3(1) + 2)} = \dfrac{c_{0}}{5}$$
$k = 2$:
$$c_{2} = \dfrac{c_{1}}{2(3(2) + 2)} = \dfrac{c_{1}}{16} = \dfrac{c_{0}}{80}$$
$k = 3$:
$$c_{3} = \dfrac{c_{2}}{3(3(3) + 2)} = \dfrac{c_{2}}{33} = \dfrac{c_{0}}{2640}$$
$k = 4$:
$$c_{4} = \dfrac{c_{3}}{4(3(4) + 2)} = \dfrac{c_{3}}{56} = \dfrac{c_{0}}{147840}$$
Etcétera, entonces la primer solución es de la forma
\begin{align*}
y_{1}(x) &= x^{1} ( c_{0} + c_{1}x + c_{2}x^{2} + c_{3}x^{3} + c_{4}x^{4} \cdots) \\
&= x \left( c_{0} + \dfrac{c_{0}}{5}x + \dfrac{c_{0}}{80}x^{2} + \dfrac{c_{0}}{2640}x^{3} + \dfrac{c_{0}}{147840}x^{4} \cdots \right) \\
&= c_{0}x \left( 1 + \dfrac{x}{5} + \dfrac{x^{2}}{80} + \dfrac{x^{3}}{2640} + \dfrac{x^{4}}{147840} \cdots \right)
\end{align*}
Por otro lado, para $r = \dfrac{1}{3}$ la relación de recurrencia es
$$\hat{c}_{k} = \dfrac{\hat{c}_{k -1}}{k(3k -2)}, \hspace{1cm} k = 1, 2, 3, \cdots$$
Usamos la notación $\hat{c}_{k}$ sólo para hacer referencia de que son los coeficientes de la segunda solución, pero se obtiene de la misma relación de recurrencia obtenida por el método sólo que usando $r = \dfrac{1}{3}$.
Determinemos los coeficientes para este caso.
$k = 1$:
$$\hat{c}_{1} = \dfrac{\hat{c}_{0}}{1(3(1) -2)} = \hat{c}_{0}$$
$k = 2$:
$$\hat{c}_{2} = \dfrac{\hat{c}_{1}}{2(3(2) -2)} = \dfrac{\hat{c}_{0}}{8}$$
$k = 3$:
$$\hat{c}_{3} = \dfrac{\hat{c}_{2}}{3(3(3) -2)} = \dfrac{\hat{c}_{2}}{21} = \dfrac{\hat{c}_{0}}{168}$$
$k = 4$:
$$\hat{c}_{4} = \dfrac{\hat{c}_{3}}{4(3(4) -2)} = \dfrac{\hat{c}_{3}}{40} = \dfrac{\hat{c}_{0}}{6720}$$
Etcétera, entonces la segunda solución es de la forma
\begin{align*}
y_{2}(x) &= x^{1/3} (\hat{c}_{0} + \hat{c}_{1}x + \hat{c}_{2}x^{2} + \hat{c}_{3}x^{3} + \hat{c}_{4}x^{4} \cdots) \\
&= x^{1/3} \left( \hat{c}_{0} + \hat{c}_{0}x + \dfrac{\hat{c}_{0}}{8}x^{2} + \dfrac{\hat{c}_{0}}{168}x^{3} + \dfrac{\hat{c}_{0}}{6720}x^{4} + \cdots \right) \\
&= \hat{c}_{0}x^{1/3} \left( 1 + x + \dfrac{x^{2}}{8} + \dfrac{x^{3}}{168} + \dfrac{x^{4}}{6720} + \cdots \right)
\end{align*}
Si definimos $C_{1} = c_{0}$ y $C_{2} = \hat{c}_{0}$, entonces la solución general a la ecuación diferencial es
\begin{align*}
y(x) &= C_{1}x \left( 1 + \dfrac{x}{5} + \dfrac{x^{2}}{80} + \dfrac{x^{3}}{2640} + \dfrac{x^{4}}{147840} + \cdots \right) \\
&+ C_{2} x^{1/3} \left( 1 + x + \dfrac{x^{2}}{8} + \dfrac{x^{3}}{168} + \dfrac{x^{4}}{6720} + \cdots \right)
\end{align*}
$\square$
Con este ejemplo podemos aclarar algunas cosas. La primera de ellas es que desarrollando el método mismo obtendremos la ecuación indicial, así que no necesariamente debemos sustituir en la ecuación (\ref{11}), por otro lado, sustituir en la ecuación (\ref{11}) nos permitirá desde un inicio conocer las raíces indiciales y con ello podremos determinar la forma de la segunda solución según sea el caso.
Otra cosa importante a notar es que podemos calcular los coeficientes que deseemos, en el ejemplo sólo calculamos los primeros $5$ coeficientes, es decir hasta $k = 4$, pero puedes continuar, lo interesante de continuar es que en algunas ocasiones es posible determinar una relación que generaliza la forma de los coeficientes y con ello formar una serie que puede converger o no. Los siguientes ejercicios son un ejemplo de esto.
También hay que mencionar que en este ejemplo el método de Frobenius sí nos proporcionó la segunda solución usando la relación de recurrencia, esto no ocurrirá en algunos otros casos como el que sigue a continuación, en estos casos será necesario aplicar algunos de los métodos que ya mencionamos antes.
Solución cuando las raíces indiciales son repetidas
Ejemplo: Resolver la ecuación diferencial $x^{2} \dfrac{d^{2}y}{dx^{2}} + (x^{2} -x) \dfrac{dy}{dx} + y = 0$, con respecto al punto singular $x_{0} = 0$.
Solución: Escribimos la ecuación en su forma estándar.
$$\dfrac{d^{2}y}{dx^{2}} + \dfrac{x -1}{x} \dfrac{dy}{dx} + \dfrac{1}{x^{2}} y = 0$$
Identificamos que
$$P(x) = \dfrac{x -1}{x} \hspace{1cm} y \hspace{1cm} Q(x) = \dfrac{1}{x^{2}}$$
Mientras que las funciones $p(x)$ y $q(x)$ están dadas por
$$p(x) = x -1 \hspace{1cm} y \hspace{1cm} q(x) = 1$$
Como los límites existen
$$\lim_{x \to 0}p(x) = -1 \hspace{1cm} y \hspace{1cm} \lim_{x \to 0} q(x) = 1$$
entonces $x = 0$ es un punto singular regular. En esta ocasión vamos a obtener las raíces indiciales directamente de la expresión resultante para $k = 0$. Sustituyamos las funciones correspondientes en la ecuación diferencial.
$$x^{2} \left[ \sum_{n = 0}^{\infty}(n + r)(n + r -1)c_{n}x^{n + r -2} \right] + (x^{2} -x) \left[ \sum_{n = 0}^{\infty}(n + r)c_{n}x^{n + r -1} \right] + \left[ \sum_{n = 0}^{\infty}c_{n}x^{n + r} \right] = 0$$
$$\sum_{n = 0}^{\infty}(n + r)(n + r -1)c_{n}x^{n + r} + \sum_{n = 0}^{\infty}(n + r)c_{n}x^{n + r + 1} -\sum_{n = 0}^{\infty}(n + r)c_{n}x^{n + r} + \sum_{n = 0}^{\infty}c_{n}x^{n + r} = 0$$
En la segunda serie hacemos $k = n + 1$ y en el resto $k = n$.
$$ \sum_{k = 0}^{\infty}(k + r)(k + r -1)c_{k}x^{k + r} + \sum_{k = 1}^{\infty}(k -1 + r)c_{k-1}x^{k + r} -\sum_{k = 0}^{\infty}(k + r)c_{k}x^{k + r} + \sum_{k = 0}^{\infty}c_{k}x^{k + r} = 0$$
Extraemos el primer término de las series que comienzan con $k = 0$ para que todas comiencen con $k = 1$.
\begin{align*}
r(r -1)c_{0}x^{r} -rc_{0}x^{r} + c_{0}x^{r} &= 0 \\
c_{0}x^{r}[r(r -1) -r + 1] &= 0
\end{align*}
como $x^{r} \neq 0$ y $c_{0} \neq 0$, entonces
\begin{align*}
r(r -1) -r + 1 &= 0 \\
r^{2} -2r + 1 &= 0
\end{align*}
Hemos obtenido la ecuación indicial. Resolviendo para $r$ se obtiene que $r_{1} = r_{2} = 1$. Las raíces indiciales son iguales, de manera que estamos en condiciones del caso 2 en el que las soluciones son de la forma (\ref{14}) y (\ref{15}).
$$y_{1}(x) = \sum_{n = 0}^{\infty}c_{n}x^{n + 1}, \hspace{1cm} c_{0} \neq 0$$
y
$$y_{2}(x) = \ln (x) \sum_{n = 0}^{\infty}c_{n}x^{n + 1} + \sum_{n = 0}^{\infty}\hat{c}_{n}x^{n + 1}$$
Ahora tenemos la ecuación en la que todas las series tienen la misma potencia y comienzan con el mismo índice.
$$\sum_{k = 1}^{\infty}(k + r)(k + r -1)c_{k}x^{k + r} + \sum_{k = 1}^{\infty}(k -1 + r)c_{k -1}x^{k + r} -\sum_{k = 1}^{\infty}(k + r)c_{k}x^{k + r} + \sum_{k = 1}^{\infty}c_{k}x^{k + r} = 0$$
Juntamos todo en una sola serie.
$$\sum_{k = 1}^{\infty}[(k + r)(k + r -1)c_{k} + (k -1 + r)c_{k -1} -(k + r)c_{k} + c_{k}]x^{k + r} = 0$$
de donde
$$c_{k}[(k + r)(k + r -1) -(k + r) + 1] + c_{k -1}(k -1 + r) = 0$$
despejando a $c_{k}$ se obtiene la relación de recurrencia
$$c_{k} = \dfrac{c_{k -1}(k -1 + r)}{(k + r) -1 -(k + r)(k + r -1)} = \dfrac{c_{k -1}}{1 -k -r}, \hspace{1cm} k = 1, 2, 3, \cdots$$
Cómo $r = 1$, entonces la relación de recurrencia es
$$c_{k} = -\dfrac{c_{k -1}}{k}, \hspace{1cm} k = 1, 2, 3, \cdots$$
Determinemos los coeficientes.
$k = 1$:
$$c_{1} = -\dfrac{c_{0}}{1} = -c_{0}$$
$k = 2$:
$$c_{2} = -\dfrac{c_{1}}{2} = \dfrac{c_{0}}{2}$$
$k = 3$:
$$c_{3} = -\dfrac{c_{2}}{3} = -\dfrac{c_{0}}{6}$$
$k = 4$:
$$c_{4} = -\dfrac{c_{3}}{4} = \dfrac{c_{0}}{24}$$
$k = 5$:
$$c_{5} = -\dfrac{c_{4}}{5} = -\dfrac{c_{0}}{120}$$
Etcétera, la primera solución es
\begin{align*}
y_{1}(x) &= x(c_{0} + c_{1}x + c_{2}x^{2} + c_{3}x^{3} + c_{4}x^{4} + c_{5}x^{5} \cdots) \\
&= x \left( c_{0} -c_{0}x + \dfrac{c_{0}}{2}x^{2} -\dfrac{c_{0}}{6}x^{3} + \dfrac{c_{0}}{24}x^{4} -\dfrac{c_{0}}{120}x^{5} + \cdots \right) \\
&= c_{0}x \left( 1 -x + \dfrac{x^{2}}{2} -\dfrac{x^{3}}{3!} + \dfrac{x^{4}}{4!} -\dfrac{x^{5}}{5!} + \cdots \right)
\end{align*}
Lo que mencionamos antes, la solución va teniendo forma de una serie que conocemos y que converge, pues sabemos que
$$e^{-x} = \sum_{n = 0}^{\infty} \dfrac{(-x)^{n}}{n!} = 1 -x + \dfrac{x^{2}}{2} -\dfrac{x^{3}}{3!} + \dfrac{x^{4}}{4!} -\dfrac{x^{5}}{5!} + \cdots$$
entonces $y_{1}(x) = c_{0}xe^{-x}$. Consideremos que $c_{0} = 1 \neq 0$, así la primer solución a la ecuación diferencial es
$$y_{1}(x) = xe^{-x}$$
Observa que el método ya no nos ofrece una segunda solución. Para obtener la segunda solución se pueden usar tres métodos, uno de ellos es usando variación de parámetros. Un segundo método puede ser por derivación de la solución propuesta
$$y_{2}(x) = y_{1}\ln(x) + \sum_{n = 0}^{\infty}\hat{c}_{n}x^{n + 1}$$
las derivadas son
$$\dfrac{dy_{2}}{dx} = \dfrac{y_{1}}{x} + \ln (x)\dfrac{dy_{1}}{dx} + \sum_{n = 0}^{\infty}(n + 1)\hat{c}_{n}x^{n}$$
y
$$\dfrac{d^{2}y_{2}}{dx^{2}} = -\dfrac{y_{1}}{x^{2}} + \dfrac{2}{x} \dfrac{dy_{1}}{dx} + \ln(x) \dfrac{d^{2}y_{1}}{dx^{2}} + \sum_{n = 0}^{\infty}(n + 1)n \hat{c}_{n}x^{n -1}$$
Se sustituyen estos resultados en la ecuación diferencial y se procede igual que antes con la diferencia de que ahora no obtendremos una ecuación indicial pero sí una relación de recurrencia para obtener los coeficientes $\hat{c}_{k}$. ¡Seguro este método es un camino largo!.
Un tercer método es aplicar directamente la formula (\ref{19}). Por simplicidad obtendremos la segunda solución por este método.
Recordamos que $P(x) = \dfrac{x -1}{x}$ y $y_{1} = x e^{-x}$, vemos que
$$-\int{P(x)dx} = -\int{\dfrac{x -1}{x}dx} = \int{ \left( \dfrac{1}{x} -1 \right) dx} = \ln(x) -x$$
entonces
\begin{align*}
y_{2}(x) &= y_{1} \int{\dfrac{e^{\ln(x) -x}}{(xe^{-x})^{2}}dx} \\
&= y_{1} \int{\dfrac{xe^{-x}}{x^{2}e^{-2x}}dx} \\
&= y_{1} \int{\dfrac{e^{x}}{x}dx} \\
&= y_{1} \int{\dfrac{1}{x} \left( 1 + x + \dfrac{x^{2}}{2} + \dfrac{x^{3}}{3!} + \dfrac{x^{4}}{4!} + \cdots \right)dx} \\
&= y_{1} \int{ \left( \dfrac{1}{x} + 1 + \dfrac{x}{2} + \dfrac{x^{2}}{3!} + \dfrac{x^{3}}{4!} + \cdots \right) dx} \\
&= y_{1} \left[ \ln(x) + x + \dfrac{x^{2}}{2(2!)} + \dfrac{x^{3}}{3(3!)} + \dfrac{x^{4}}{4(4!)} + \cdots \right] \\
&= y_{1} \ln(x) + y_{1} \sum_{n = 1}^{\infty}\dfrac{x^{n}}{n(n!)}
\end{align*}
Vemos que
\begin{align*}
xe^{-x} \sum_{n = 1}^{\infty}\dfrac{x^{n}}{n(n!)} &= x \left( 1 -x + \dfrac{x^{2}}{2!} -\dfrac{x^{3}}{3!} + \dfrac{x^{4}}{4!} -\cdots \right) \left( x + \dfrac{x^{2}}{2(2!)} + \dfrac{x^{3}}{3(3!)} + \dfrac{x^{4}}{4(4!)} + \cdots \right) \\
&= \left( x -x^{2} + \dfrac{x^{3}}{2} -\dfrac{x^{4}}{6} + \dfrac{x^{5}}{24} -\cdots \right) \left( x + \dfrac{x^{2}}{4} + \dfrac{x^{3}}{18} + \dfrac{x^{4}}{96} + \cdots \right) \\
&= x^{2} + \left( \dfrac{x^{3}}{4} -x^{3} \right) + \left( \dfrac{x^{4}}{18} -\dfrac{x^{4}}{4} + \dfrac{x^{4}}{2} \right) + \left( \dfrac{x^{5}}{96} -\dfrac{x^{5}}{18} + \dfrac{x^{5}}{8} -\dfrac{x^{5}}{6} \right) + \cdots \\
&= x^{2} -\dfrac{3}{4}x^{3} + \dfrac{11}{36}x^{4} -25x^{5} + \cdots
\end{align*}
Entonces la segunda solución es
$$y_{2}(x) = xe^{-x} \ln(x) + x^{2} -\dfrac{3}{4}x^{3} + \dfrac{11}{36}x^{4} -25x^{5} + \cdots$$
Por lo tanto, la solución general a la ecuación diferencial es:
$$y(x) = C_{1}xe^{-x} + C_{2} \left( xe^{-x} \ln(x) + x^{2} -\dfrac{3}{4}x^{3} + \dfrac{11}{36}x^{4} -25x^{5} + \cdots \right)$$
$\square$
Solución cuando la diferencia de las raíces indiciales es un número entero positivo
Ejemplo: Resolver la ecuación diferencial $x\dfrac{d^{2}y}{dx^{2}} -\dfrac{dy}{dx} + 4x^{3} y = 0$, con respecto al punto singular $x_{0} = 0$.
Solución: Dividimos toda la ecuación por $x$ para obtener la forma estándar.
$$\dfrac{d^{2}y}{dx^{2}} -\dfrac{1}{x} \dfrac{dy}{dx} + 4x^{2}y = 0$$
Identificamos que
$$P(x) = -\dfrac{1}{x} \hspace{1cm} y \hspace{1cm} Q(x)= 4x^{2}$$
Es claro que $x = 0$ es un punto ordinario de $Q(x)$, sin embargo es un punto singular regular de $P(x)$ pues
$$\lim_{x \to 0}xP(x) = \lim_{x \to 0}-1 = -1$$
Consideramos la solución $y = \sum_{n = 0}^{\infty }c_{n}x^{n + r}$ y sus derivadas y sustituimos en la ecuación diferencial.
$$x \left[ \sum_{n = 0}^{\infty }(n + r)(n + r -1)c_{n}x^{n + r -2} \right] -\left[ \sum_{n = 0}^{\infty}(n + r)c_{n}x^{n + r -1} \right] + 4x^{3} \left[ \sum_{n = 0}^{\infty}c_{n}x^{n + r} \right] = 0$$
$$\sum_{n = 0}^{\infty}(n + r)(n + r -1)c_{n}x^{n + r -1} -\sum_{n = 0}^{\infty}(n + r)c_{n}x^{n + r -1} + 4 \sum_{n = 0}^{\infty}c_{n}x^{n + r + 3} = 0$$
En la tercer serie hacemos $k = n + 4$ y en el resto $k = n$.
$$\sum_{k = 0}^{\infty}(k + r)(k + r -1)c_{k}x^{k + r -1} -\sum_{k = 0}^{\infty}(k + r)c_{k}x^{k + r -1} + 4 \sum_{k = 4}^{\infty}c_{k -4}x^{k + r -1} = 0$$
Para $k = 0$ obtenemos que
\begin{align*}
r(r -1)c_{0}x^{r -1} -rc_{0}x^{r -1} &= 0 \\
c_{0}x^{r -1} [r(r -1) -r] &= 0
\end{align*}
de donde se obtiene la ecuación indicial
$$r^{2} -2r = 0$$
cuyas raíces son $r_{1} = 2$ y $r_{2} = 0$. Como $r_{1} -r_{2} = 2 =$ entero, entonces estamos en condiciones del caso 3 y por tanto las soluciones son de la forma (\ref{16}) y (\ref{17}).
$$y_{1}(x) = \sum_{n = 0}^{\infty}c_{n}x^{n + 2}, \hspace{1cm} c_{0} \neq 0$$
y
$$y_{2}(x) = C \ln(x) \sum_{n = 0}^{\infty}c_{n}x^{n + 2} + \sum_{n = 0}^{\infty}\hat{c}_{n}x^{n}, \hspace{1cm} \hat{c}_{0}\neq 0$$
Recuerda que $C$ puede ser cero.
Necesitamos que todas las series comiencen en $k = 4$ para poder obtener la relación de recurrencia. Extraemos los valores para $k = 1$, $k = 2$ y $k = 3$.
$k = 1$:
\begin{align*}
(1 + r)(r)c_{1}x^{r} -(1 + r)c_{1}x^{r} &= 0 \\
x^{r}[(1 + r)(r) -(1 + r)]c_{1} &= 0
\end{align*}
de donde necesariamente $c_{1} = 0$.
$k = 2$:
\begin{align*}
(2 + r)(1 + r)c_{2}x^{r + 1} -(2 + r)c_{2}x^{r + 1} &= 0 \\
x^{r + 1}[(2 + r)(1 + r) -(2 + r)] c_{2} &= 0
\end{align*}
de donde necesariamente $c_{2} = 0$.
$k = 3$:
\begin{align*}
(3 + r)(2 + r)c_{3}x^{r + 2} -(3 + r)c_{3}x^{r + 2} &= 0 \\
x^{r + 2}[(3 + r)(2 + r) -(3 + r)] c_{3} &= 0
\end{align*}
Igualmente obtenemos que $c_{3} = 0$.
Ahora tenemos la ecuación
$$\sum_{k = 4}^{\infty}(k + r)(k + r -1)c_{k}x^{k + r -1} -\sum_{k = 4}^{\infty}(k + r)c_{k}x^{k + r -1} + 4 \sum_{k = 4}^{\infty}c_{k -4}x^{k + r -1} = 0$$
La reescribimos en una sola serie.
$$\sum_{k = 4}^{\infty}[(k + r)(k + r -1)c_{k} -(k + r)c_{k} + 4c_{k -4}]x^{k + r -1} = 0$$
De donde
$$c_{k}[(k + r)(k + r -1) -(k + r)] + 4c_{k -4} = 0$$
Despejando $c_{k}$ obtenemos la relación de recurrencia.
$$c_{k} = \dfrac{4c_{k -4}}{(k + r) -(k + r)(k + r -1)}, \hspace{1cm} k = 4, 5, 6, \cdots$$
Para el caso en el que $r = 2$ la relación de recurrencia es
$$c_{k} = -\dfrac{4c_{k -4}}{k(k + 2)}, \hspace{1cm} k = 4, 5, 6, \cdots$$
Determinemos los coeficientes.
$k = 4$:
$$c_{4} = -\dfrac{4c_{0}}{4(4 + 2)} = -\dfrac{4c_{0}}{24} = -\dfrac{c_{0}}{6}$$
Para $k = 5$, $k = 6$ y $k = 7$ obtendremos que $c_{5} = 0$, $c_{6} = 0$ y $c_{7} = 0$ respectivamente.
$k = 8$:
$$c_{8} = -\dfrac{4c_{4}}{8(8 + 2)} = -\dfrac{4c_{4}}{80} = -\dfrac{c_{4}}{20} = \dfrac{c_{0}}{120}$$
De la misma manera $c_{9} = c_{10} = c_{11} = 0$.
$k = 12$:
$$c_{12} = -\dfrac{4c_{8}}{12(12 + 2)} = -\dfrac{4c_{8}}{168} = -\dfrac{c_{8}}{42} = -\dfrac{c_{0}}{5040}$$
Etcétera, entonces
\begin{align*}
y_{1}(x) &= x^{2} \left( c_{0} -\dfrac{c_{0}}{6}x^{4} + \dfrac{c_{0}}{120}x^{8} -\dfrac{c_{0}}{5040}x^{12} + \cdots \right) \\
&= c_{0} \left( x^{2} -\dfrac{x^{6}}{3!} + \dfrac{x^{10}}{5!} -\dfrac{x^{14}}{7!} + \cdots \right)
\end{align*}
Sabemos que
$$\sin(x) = x -\dfrac{x^{3}}{3!} + \dfrac{x^{5}}{5!} -\dfrac{x^{7}}{7!} + \cdots = \sum_{n = 0}^{\infty} \dfrac{(-1)^{n} x^{2n + 1}}{(2n + 1)!}$$
Entonces la primer solución es
$$y_{1}(x) = c_{0} \sin(x^{2})$$
Para obtener la segunda solución $y_{2}$ podemos probar con la relación de recurrencia que obtuvimos o por alguno de los métodos que ya conocemos.
Consideremos la relación de recurrencia obtenida
$$c_{k} = \dfrac{4c_{k -4}}{(k + r) -(k + r)(k + r -1)}, \hspace{1cm} k = 4, 5, 6, \cdots$$
Usemos la notación $\hat{c}_{k}$ y el valor de la segunda raíz indicial $r = 0$, en este caso la relación de recurrencia es
$$\hat{c}_{k} = -\dfrac{4c_{k -4}}{k(k -2)}, \hspace{1cm} k = 4, 5, 6, \cdots$$
Los mismos coeficientes que fueron cero en el caso anterior serán cero en este caso así que sólo consideraremos que $k = 4, 8, 12, \cdots$. Determinemos los coeficientes.
$k = 4$:
$$\hat{c}_{4} = -\dfrac{4 \hat{c}_{0}}{4(4 -2)} = -\dfrac{4 \hat{c}_{0}}{8} = -\dfrac{\hat{c}_{0}}{2}$$
$k = 8$:
$$\hat{c}_{8} = -\dfrac{4 \hat{c}_{4}}{8(8 -2)} = -\dfrac{4 \hat{c}_{4}}{48} = -\dfrac{\hat{c}_{4}}{12} = \dfrac{c_{0}}{24}$$
$k = 12$:
$$\hat{c}_{12} = -\dfrac{4 \hat{c}_{8}}{12(12 -2)} = -\dfrac{4 \hat{c}_{8}}{120} = -\dfrac{c_{8}}{30} = -\dfrac{\hat{c}_{0}}{720}$$
Etcétera, entonces
\begin{align*}
y &= \hat{c}_{0} -\dfrac{\hat{c}_{0}}{2}x^{4} + \dfrac{\hat{c}_{0}}{24}x^{8} -\dfrac{\hat{c}_{0}}{720}x^{12} + \cdots \\
&= \hat{c}_{0} \left( 1 -\dfrac{x^{4}}{2!} + \dfrac{x^{8}}{4!} -\dfrac{x^{12}}{6!} + \cdots \right)
\end{align*}
Sabemos que
$$\cos(x) = 1 -\dfrac{x^{2}}{2!} + \dfrac{x^{4}}{4!} -\dfrac{x^{6}}{6!} + \cdots = \sum_{n = 0}^{\infty} \dfrac{(-1)^{n} x^{2n}}{(2n)!}$$
Entonces la segunda solución es
$$y = \hat{c}_{0} \cos(x^{2})$$
Vemos que el método no nos indica la existencia de la función $\ln(x)$ y nosotros esperamos una solución de la forma
$$y_{2}(x) = C \ln(x) \sum_{n = 0}^{\infty}c_{n}x^{n + 2} + \sum_{n = 0}^{\infty}\hat{c}_{n}x^{n}, \hspace{1cm} \hat{c}_{0}\neq 0$$
Entonces podemos concluir que $C = 0$, así
$y_{2}(x) = \hat{c}_{0} \cos(x^{2})$
Veamos que se obtiene usando la fórmula (\ref{19}). Recordemos que $P(x) = -\dfrac{1}{x}$ y consideremos que $c_{0} = 1$ tal que $y_{1} = \sin(x^{2})$. Vemos que
$$-\int{P(x) dx} = \int{\dfrac{dx}{x}} = \ln(x)$$
Sustituimos en (\ref{19}):
$$y_{2} = \sin(x^{2}) \int{\dfrac{e^{\ln(x)}}{(\sin(x^{2}))^{2}} dx} = \sin(x^{2}) \int{\dfrac{x}{(\sin(x^{2}))^{2}}dx}$$
Si resuelves la integral obtendrás que
$$\int{\dfrac{x}{(\sin(x^{2}))^{2}}dx} = -\dfrac{1}{2} \cot(x^{2})$$
Entonces
$$y_{2}(x) = -\dfrac{1}{2} \sin(x^{2}) \left( \dfrac{\cos(x^{2})}{\sin(x^{2})} \right) = -\dfrac{1}{2} \cos(x^{2}) = \hat{c}_{0} \cos(x^{2})$$
Este método nos indica que efectivamente $C = 0$. Si $C_{1} = c_{0}$ y $C_{2} = \hat{c}_{0}$, entonces la solución general a la ecuación diferencial es
$$y(x) = C_{1} \sin(x^{2}) + C_{2} \cos(x^{2})$$
$\square$
Tarea moral
Los siguientes ejercicios no forman parte de la evaluación del curso, pero te servirán para entender mucho mejor los conceptos vistos en esta entrada, así como temas posteriores.
1. Usar el método de Frobenius para obtener la solución general de las siguientes ecuaciones diferenciales en el punto singular $x_{0}= 0$. Verifica que dicho punto es singular.
• $2x \dfrac{d^{2}y}{dx^{2}} + (x + 1) \dfrac{dy}{dx} + 3y = 0$.
• $x^{2} \dfrac{d^{2}y}{dx^{2}} -\dfrac{1}{6}x \dfrac{dy}{dx} + \dfrac{1}{3}y = 0$.
• $x^{2} \dfrac{d^{2}y}{dx^{2}} + 6x \dfrac{dy}{dx} + (6 -x^{2})y = 0$.
• $2x^{2} \dfrac{d^{2}y}{dx^{2}} -x^{2} \dfrac{dy}{dx} -(x + 4)y = 0$.
• $x \dfrac{d^{2}y}{dx^{2}} + (x -1) \dfrac{dy}{dx} + \left( \dfrac{1}{x} -1 \right) y = 0$.
• $(x^{2} -x) \dfrac{d^{2}y}{dx^{2}} + (3x -1) \dfrac{dy}{dx} + y = 0$.
Más adelante…
Ahora que sabemos resolver ecuaciones diferenciales lineales de segundo orden con coeficientes variables con respecto a puntos ordinarios y puntos singulares en la siguientes entradas resolveremos algunas ecuaciones diferenciales especiales cuya utilidad es de suma importancia en otras áreas del conocimiento como la física, biología e ingeniería entre otras.
Entradas relacionadas
Deja una respuesta
Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *
Este sitio usa Akismet para reducir el spam. Aprende cómo se procesan los datos de tus comentarios.
|
__label__pos
| 0.999999 |
Tox + Integration testing
[osm/N2VC.git] / n2vc / vnf.py
1 import asyncio
2 import logging
3 import os
4 import os.path
5 import re
6 import ssl
7 import sys
8 # import time
9
10 # FIXME: this should load the juju inside or modules without having to
11 # explicitly install it. Check why it's not working.
12 # Load our subtree of the juju library
13 path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
14 path = os.path.join(path, "modules/libjuju/")
15 if path not in sys.path:
16 sys.path.insert(1, path)
17
18 from juju.controller import Controller
19 from juju.model import ModelObserver
20
21
22 # We might need this to connect to the websocket securely, but test and verify.
23 try:
24 ssl._create_default_https_context = ssl._create_unverified_context
25 except AttributeError:
26 # Legacy Python doesn't verify by default (see pep-0476)
27 # https://www.python.org/dev/peps/pep-0476/
28 pass
29
30
31 # Custom exceptions
32 class JujuCharmNotFound(Exception):
33 """The Charm can't be found or is not readable."""
34
35
36 class JujuApplicationExists(Exception):
37 """The Application already exists."""
38
39
40 class N2VCPrimitiveExecutionFailed(Exception):
41 """Something failed while attempting to execute a primitive."""
42
43
44 # Quiet the debug logging
45 logging.getLogger('websockets.protocol').setLevel(logging.INFO)
46 logging.getLogger('juju.client.connection').setLevel(logging.WARN)
47 logging.getLogger('juju.model').setLevel(logging.WARN)
48 logging.getLogger('juju.machine').setLevel(logging.WARN)
49
50
51 class VCAMonitor(ModelObserver):
52 """Monitor state changes within the Juju Model."""
53 log = None
54 ns_name = None
55 applications = {}
56
57 def __init__(self, ns_name):
58 self.log = logging.getLogger(__name__)
59
60 self.ns_name = ns_name
61
62 def AddApplication(self, application_name, callback, *callback_args):
63 if application_name not in self.applications:
64 self.applications[application_name] = {
65 'callback': callback,
66 'callback_args': callback_args
67 }
68
69 def RemoveApplication(self, application_name):
70 if application_name in self.applications:
71 del self.applications[application_name]
72
73 async def on_change(self, delta, old, new, model):
74 """React to changes in the Juju model."""
75
76 if delta.entity == "unit":
77 # Ignore change events from other applications
78 if delta.data['application'] not in self.applications.keys():
79 return
80
81 try:
82
83 application_name = delta.data['application']
84
85 callback = self.applications[application_name]['callback']
86 callback_args = \
87 self.applications[application_name]['callback_args']
88
89 if old and new:
90 old_status = old.workload_status
91 new_status = new.workload_status
92
93 if old_status == new_status:
94 """The workload status may fluctuate around certain
95 events, so wait until the status has stabilized before
96 triggering the callback."""
97 if callback:
98 callback(
99 self.ns_name,
100 delta.data['application'],
101 new_status,
102 new.workload_status_message,
103 *callback_args)
104
105 if old and not new:
106 # This is a charm being removed
107 if callback:
108 callback(
109 self.ns_name,
110 delta.data['application'],
111 "removed",
112 "",
113 *callback_args)
114 except Exception as e:
115 self.log.debug("[1] notify_callback exception: {}".format(e))
116
117 elif delta.entity == "action":
118 # TODO: Decide how we want to notify the user of actions
119
120 # uuid = delta.data['id'] # The Action's unique id
121 # msg = delta.data['message'] # The output of the action
122 #
123 # if delta.data['status'] == "pending":
124 # # The action is queued
125 # pass
126 # elif delta.data['status'] == "completed""
127 # # The action was successful
128 # pass
129 # elif delta.data['status'] == "failed":
130 # # The action failed.
131 # pass
132
133 pass
134
135 ########
136 # TODO
137 #
138 # Create unique models per network service
139 # Document all public functions
140
141
142 class N2VC:
143 def __init__(self,
144 log=None,
145 server='127.0.0.1',
146 port=17070,
147 user='admin',
148 secret=None,
149 artifacts=None,
150 loop=None,
151 ):
152 """Initialize N2VC
153
154 :param vcaconfig dict A dictionary containing the VCA configuration
155
156 :param artifacts str The directory where charms required by a vnfd are
157 stored.
158
159 :Example:
160 n2vc = N2VC(vcaconfig={
161 'secret': 'MzI3MDJhOTYxYmM0YzRjNTJiYmY1Yzdm',
162 'user': 'admin',
163 'ip-address': '10.44.127.137',
164 'port': 17070,
165 'artifacts': '/path/to/charms'
166 })
167 """
168
169 # Initialize instance-level variables
170 self.api = None
171 self.log = None
172 self.controller = None
173 self.connecting = False
174 self.authenticated = False
175
176 self.models = {}
177 self.default_model = None
178
179 # Model Observers
180 self.monitors = {}
181
182 # VCA config
183 self.hostname = ""
184 self.port = 17070
185 self.username = ""
186 self.secret = ""
187
188 if log:
189 self.log = log
190 else:
191 self.log = logging.getLogger(__name__)
192
193 # Quiet websocket traffic
194 logging.getLogger('websockets.protocol').setLevel(logging.INFO)
195 logging.getLogger('juju.client.connection').setLevel(logging.WARN)
196 logging.getLogger('model').setLevel(logging.WARN)
197 # logging.getLogger('websockets.protocol').setLevel(logging.DEBUG)
198
199 self.log.debug('JujuApi: instantiated')
200
201 self.server = server
202 self.port = port
203
204 self.secret = secret
205 if user.startswith('user-'):
206 self.user = user
207 else:
208 self.user = 'user-{}'.format(user)
209
210 self.endpoint = '%s:%d' % (server, int(port))
211
212 self.artifacts = artifacts
213
214 self.loop = loop or asyncio.get_event_loop()
215
216 def __del__(self):
217 """Close any open connections."""
218 yield self.logout()
219
220 def notify_callback(self, model_name, application_name, status, message,
221 callback=None, *callback_args):
222 try:
223 if callback:
224 callback(
225 model_name,
226 application_name,
227 status, message,
228 *callback_args,
229 )
230 except Exception as e:
231 self.log.error("[0] notify_callback exception {}".format(e))
232 raise e
233 return True
234
235 # Public methods
236 async def CreateNetworkService(self, nsd):
237 """Create a new model to encapsulate this network service.
238
239 Create a new model in the Juju controller to encapsulate the
240 charms associated with a network service.
241
242 You can pass either the nsd record or the id of the network
243 service, but this method will fail without one of them.
244 """
245 if not self.authenticated:
246 await self.login()
247
248 # Ideally, we will create a unique model per network service.
249 # This change will require all components, i.e., LCM and SO, to use
250 # N2VC for 100% compatibility. If we adopt unique models for the LCM,
251 # services deployed via LCM would't be manageable via SO and vice versa
252
253 return self.default_model
254
255 async def DeployCharms(self, model_name, application_name, vnfd,
256 charm_path, params={}, machine_spec={},
257 callback=None, *callback_args):
258 """Deploy one or more charms associated with a VNF.
259
260 Deploy the charm(s) referenced in a VNF Descriptor.
261
262 :param str model_name: The name of the network service.
263 :param str application_name: The name of the application
264 :param dict vnfd: The name of the application
265 :param str charm_path: The path to the Juju charm
266 :param dict params: A dictionary of runtime parameters
267 Examples::
268 {
269 'rw_mgmt_ip': '1.2.3.4',
270 # Pass the initial-config-primitives section of the vnf or vdu
271 'initial-config-primitives': {...}
272 }
273 :param dict machine_spec: A dictionary describing the machine to
274 install to
275 Examples::
276 {
277 'hostname': '1.2.3.4',
278 'username': 'ubuntu',
279 }
280 :param obj callback: A callback function to receive status changes.
281 :param tuple callback_args: A list of arguments to be passed to the
282 callback
283 """
284
285 ########################################################
286 # Verify the path to the charm exists and is readable. #
287 ########################################################
288 if not os.path.exists(charm_path):
289 self.log.debug("Charm path doesn't exist: {}".format(charm_path))
290 self.notify_callback(
291 model_name,
292 application_name,
293 "failed",
294 callback,
295 *callback_args,
296 )
297 raise JujuCharmNotFound("No artifacts configured.")
298
299 ################################
300 # Login to the Juju controller #
301 ################################
302 if not self.authenticated:
303 self.log.debug("Authenticating with Juju")
304 await self.login()
305
306 ##########################################
307 # Get the model for this network service #
308 ##########################################
309 # TODO: In a point release, we will use a model per deployed network
310 # service. In the meantime, we will always use the 'default' model.
311 model_name = 'default'
312 model = await self.get_model(model_name)
313
314 ########################################
315 # Verify the application doesn't exist #
316 ########################################
317 app = await self.get_application(model, application_name)
318 if app:
319 raise JujuApplicationExists("Can't deploy application \"{}\" to model \"{}\" because it already exists.".format(application_name, model_name))
320
321 ################################################################
322 # Register this application with the model-level event monitor #
323 ################################################################
324 if callback:
325 self.monitors[model_name].AddApplication(
326 application_name,
327 callback,
328 *callback_args
329 )
330
331 ########################################################
332 # Check for specific machine placement (native charms) #
333 ########################################################
334 to = ""
335 if machine_spec.keys():
336 # TODO: This needs to be tested.
337 # if all(k in machine_spec for k in ['hostname', 'username']):
338 # # Enlist the existing machine in Juju
339 # machine = await self.model.add_machine(spec='ssh:%@%'.format(
340 # specs['host'],
341 # specs['user'],
342 # ))
343 # to = machine.id
344 pass
345
346 #######################################
347 # Get the initial charm configuration #
348 #######################################
349
350 rw_mgmt_ip = None
351 if 'rw_mgmt_ip' in params:
352 rw_mgmt_ip = params['rw_mgmt_ip']
353
354 # initial_config = {}
355 # self.log.debug(type(params))
356 # self.log.debug("Params: {}".format(params))
357 if 'initial-config-primitive' not in params:
358 params['initial-config-primitive'] = {}
359
360 initial_config = self._get_config_from_dict(
361 params['initial-config-primitive'],
362 {'<rw_mgmt_ip>': rw_mgmt_ip}
363 )
364
365 self.log.debug("JujuApi: Deploying charm ({}) from {}".format(
366 application_name,
367 charm_path,
368 to=to,
369 ))
370
371 ########################################################
372 # Deploy the charm and apply the initial configuration #
373 ########################################################
374 app = await model.deploy(
375 # We expect charm_path to be either the path to the charm on disk
376 # or in the format of cs:series/name
377 charm_path,
378 # This is the formatted, unique name for this charm
379 application_name=application_name,
380 # Proxy charms should use the current LTS. This will need to be
381 # changed for native charms.
382 series='xenial',
383 # Apply the initial 'config' primitive during deployment
384 config=initial_config,
385 # TBD: Where to deploy the charm to.
386 to=None,
387 )
388
389 # #######################################
390 # # Execute initial config primitive(s) #
391 # #######################################
392 await self.ExecuteInitialPrimitives(
393 model_name,
394 application_name,
395 params,
396 )
397
398 # primitives = {}
399 #
400 # # Build a sequential list of the primitives to execute
401 # for primitive in params['initial-config-primitive']:
402 # try:
403 # if primitive['name'] == 'config':
404 # # This is applied when the Application is deployed
405 # pass
406 # else:
407 # seq = primitive['seq']
408 #
409 # params = {}
410 # if 'parameter' in primitive:
411 # params = primitive['parameter']
412 #
413 # primitives[seq] = {
414 # 'name': primitive['name'],
415 # 'parameters': self._map_primitive_parameters(
416 # params,
417 # {'<rw_mgmt_ip>': rw_mgmt_ip}
418 # ),
419 # }
420 #
421 # for primitive in sorted(primitives):
422 # await self.ExecutePrimitive(
423 # model_name,
424 # application_name,
425 # primitives[primitive]['name'],
426 # callback,
427 # callback_args,
428 # **primitives[primitive]['parameters'],
429 # )
430 # except N2VCPrimitiveExecutionFailed as e:
431 # self.log.debug(
432 # "[N2VC] Exception executing primitive: {}".format(e)
433 # )
434 # raise
435
436 async def GetPrimitiveStatus(self, model_name, uuid):
437 """Get the status of an executed Primitive.
438
439 The status of an executed Primitive will be one of three values:
440 - completed
441 - failed
442 - running
443 """
444 status = None
445 try:
446 if not self.authenticated:
447 await self.login()
448
449 # FIXME: This is hard-coded until model-per-ns is added
450 model_name = 'default'
451
452 model = await self.get_model(model_name)
453
454 results = await model.get_action_status(uuid)
455
456 if uuid in results:
457 status = results[uuid]
458
459 except Exception as e:
460 self.log.debug(
461 "Caught exception while getting primitive status: {}".format(e)
462 )
463 raise N2VCPrimitiveExecutionFailed(e)
464
465 return status
466
467 async def GetPrimitiveOutput(self, model_name, uuid):
468 """Get the output of an executed Primitive.
469
470 Note: this only returns output for a successfully executed primitive.
471 """
472 results = None
473 try:
474 if not self.authenticated:
475 await self.login()
476
477 # FIXME: This is hard-coded until model-per-ns is added
478 model_name = 'default'
479
480 model = await self.get_model(model_name)
481 results = await model.get_action_output(uuid, 60)
482 except Exception as e:
483 self.log.debug(
484 "Caught exception while getting primitive status: {}".format(e)
485 )
486 raise N2VCPrimitiveExecutionFailed(e)
487
488 return results
489
490 async def ExecuteInitialPrimitives(self, model_name, application_name,
491 params, callback=None, *callback_args):
492 """Execute multiple primitives.
493
494 Execute multiple primitives as declared in initial-config-primitive.
495 This is useful in cases where the primitives initially failed -- for
496 example, if the charm is a proxy but the proxy hasn't been configured
497 yet.
498 """
499 uuids = []
500 primitives = {}
501
502 # Build a sequential list of the primitives to execute
503 for primitive in params['initial-config-primitive']:
504 try:
505 if primitive['name'] == 'config':
506 pass
507 else:
508 seq = primitive['seq']
509
510 params = {}
511 if 'parameter' in primitive:
512 params = primitive['parameter']
513
514 primitives[seq] = {
515 'name': primitive['name'],
516 'parameters': self._map_primitive_parameters(
517 params,
518 {'<rw_mgmt_ip>': None}
519 ),
520 }
521
522 for primitive in sorted(primitives):
523 uuids.append(
524 await self.ExecutePrimitive(
525 model_name,
526 application_name,
527 primitives[primitive]['name'],
528 callback,
529 callback_args,
530 **primitives[primitive]['parameters'],
531 )
532 )
533 except N2VCPrimitiveExecutionFailed as e:
534 self.log.debug(
535 "[N2VC] Exception executing primitive: {}".format(e)
536 )
537 raise
538 return uuids
539
540 async def ExecutePrimitive(self, model_name, application_name, primitive,
541 callback, *callback_args, **params):
542 """Execute a primitive of a charm for Day 1 or Day 2 configuration.
543
544 Execute a primitive defined in the VNF descriptor.
545
546 :param str model_name: The name of the network service.
547 :param str application_name: The name of the application
548 :param str primitive: The name of the primitive to execute.
549 :param obj callback: A callback function to receive status changes.
550 :param tuple callback_args: A list of arguments to be passed to the
551 callback function.
552 :param dict params: A dictionary of key=value pairs representing the
553 primitive's parameters
554 Examples::
555 {
556 'rw_mgmt_ip': '1.2.3.4',
557 # Pass the initial-config-primitives section of the vnf or vdu
558 'initial-config-primitives': {...}
559 }
560 """
561 self.log.debug("Executing {}".format(primitive))
562 uuid = None
563 try:
564 if not self.authenticated:
565 await self.login()
566
567 # FIXME: This is hard-coded until model-per-ns is added
568 model_name = 'default'
569
570 model = await self.get_model(model_name)
571
572 if primitive == 'config':
573 # config is special, and expecting params to be a dictionary
574 await self.set_config(
575 model,
576 application_name,
577 params['params'],
578 )
579 else:
580 app = await self.get_application(model, application_name)
581 if app:
582 # Run against the first (and probably only) unit in the app
583 unit = app.units[0]
584 if unit:
585 action = await unit.run_action(primitive, **params)
586 uuid = action.id
587 except Exception as e:
588 self.log.debug(
589 "Caught exception while executing primitive: {}".format(e)
590 )
591 raise N2VCPrimitiveExecutionFailed(e)
592 return uuid
593
594 async def RemoveCharms(self, model_name, application_name, callback=None,
595 *callback_args):
596 """Remove a charm from the VCA.
597
598 Remove a charm referenced in a VNF Descriptor.
599
600 :param str model_name: The name of the network service.
601 :param str application_name: The name of the application
602 :param obj callback: A callback function to receive status changes.
603 :param tuple callback_args: A list of arguments to be passed to the
604 callback function.
605 """
606 try:
607 if not self.authenticated:
608 await self.login()
609
610 model = await self.get_model(model_name)
611 app = await self.get_application(model, application_name)
612 if app:
613 # Remove this application from event monitoring
614 self.monitors[model_name].RemoveApplication(application_name)
615
616 # self.notify_callback(model_name, application_name, "removing", callback, *callback_args)
617 self.log.debug(
618 "Removing the application {}".format(application_name)
619 )
620 await app.remove()
621
622 # Notify the callback that this charm has been removed.
623 self.notify_callback(
624 model_name,
625 application_name,
626 "removed",
627 callback,
628 *callback_args,
629 )
630
631 except Exception as e:
632 print("Caught exception: {}".format(e))
633 self.log.debug(e)
634 raise e
635
636 async def DestroyNetworkService(self, nsd):
637 raise NotImplementedError()
638
639 async def GetMetrics(self, model_name, application_name):
640 """Get the metrics collected by the VCA.
641
642 :param model_name The name of the model
643 :param application_name The name of the application
644 """
645 metrics = {}
646 model = await self.get_model(model_name)
647 app = await self.get_application(model, application_name)
648 if app:
649 metrics = await app.get_metrics()
650
651 return metrics
652
653 # Non-public methods
654 async def add_relation(self, a, b, via=None):
655 """
656 Add a relation between two application endpoints.
657
658 :param a An application endpoint
659 :param b An application endpoint
660 :param via The egress subnet(s) for outbound traffic, e.g.,
661 (192.168.0.0/16,10.0.0.0/8)
662 """
663 if not self.authenticated:
664 await self.login()
665
666 m = await self.get_model()
667 try:
668 m.add_relation(a, b, via)
669 finally:
670 await m.disconnect()
671
672 # async def apply_config(self, config, application):
673 # """Apply a configuration to the application."""
674 # print("JujuApi: Applying configuration to {}.".format(
675 # application
676 # ))
677 # return await self.set_config(application=application, config=config)
678
679 def _get_config_from_dict(self, config_primitive, values):
680 """Transform the yang config primitive to dict.
681
682 Expected result:
683
684 config = {
685 'config':
686 }
687 """
688 config = {}
689 for primitive in config_primitive:
690 if primitive['name'] == 'config':
691 # config = self._map_primitive_parameters()
692 for parameter in primitive['parameter']:
693 param = str(parameter['name'])
694 if parameter['value'] == "<rw_mgmt_ip>":
695 config[param] = str(values[parameter['value']])
696 else:
697 config[param] = str(parameter['value'])
698
699 return config
700
701 def _map_primitive_parameters(self, parameters, values):
702 params = {}
703 for parameter in parameters:
704 param = str(parameter['name'])
705
706 # Typecast parameter value, if present
707 if 'data-type' in parameter:
708 paramtype = str(parameter['data-type']).lower()
709 value = None
710
711 if paramtype == "integer":
712 value = int(parameter['value'])
713 elif paramtype == "boolean":
714 value = bool(parameter['value'])
715 else:
716 value = str(parameter['value'])
717
718 if parameter['value'] == "<rw_mgmt_ip>":
719 params[param] = str(values[parameter['value']])
720 else:
721 params[param] = value
722 return params
723
724 def _get_config_from_yang(self, config_primitive, values):
725 """Transform the yang config primitive to dict."""
726 config = {}
727 for primitive in config_primitive.values():
728 if primitive['name'] == 'config':
729 for parameter in primitive['parameter'].values():
730 param = str(parameter['name'])
731 if parameter['value'] == "<rw_mgmt_ip>":
732 config[param] = str(values[parameter['value']])
733 else:
734 config[param] = str(parameter['value'])
735
736 return config
737
738 @staticmethod
739 def FormatApplicationName(self, *args):
740 """
741 Generate a Juju-compatible Application name
742
743 :param args tuple: Positional arguments to be used to construct the
744 application name.
745
746 Limitations::
747 - Only accepts characters a-z and non-consequitive dashes (-)
748 - Application name should not exceed 50 characters
749
750 Examples::
751
752 FormatApplicationName("ping_pong_ns", "ping_vnf", "a")
753 """
754
755 appname = ""
756 for c in "-".join(list(args)):
757 if c.isdigit():
758 c = chr(97 + int(c))
759 elif not c.isalpha():
760 c = "-"
761 appname += c
762 return re.sub('\-+', '-', appname.lower())
763
764 # def format_application_name(self, nsd_name, vnfr_name, member_vnf_index=0):
765 # """Format the name of the application
766 #
767 # Limitations:
768 # - Only accepts characters a-z and non-consequitive dashes (-)
769 # - Application name should not exceed 50 characters
770 # """
771 # name = "{}-{}-{}".format(nsd_name, vnfr_name, member_vnf_index)
772 # new_name = ''
773 # for c in name:
774 # if c.isdigit():
775 # c = chr(97 + int(c))
776 # elif not c.isalpha():
777 # c = "-"
778 # new_name += c
779 # return re.sub('\-+', '-', new_name.lower())
780
781 def format_model_name(self, name):
782 """Format the name of model.
783
784 Model names may only contain lowercase letters, digits and hyphens
785 """
786
787 return name.replace('_', '-').lower()
788
789 async def get_application(self, model, application):
790 """Get the deployed application."""
791 if not self.authenticated:
792 await self.login()
793
794 app = None
795 if application and model:
796 if model.applications:
797 if application in model.applications:
798 app = model.applications[application]
799
800 return app
801
802 async def get_model(self, model_name='default'):
803 """Get a model from the Juju Controller.
804
805 Note: Model objects returned must call disconnected() before it goes
806 out of scope."""
807 if not self.authenticated:
808 await self.login()
809
810 if model_name not in self.models:
811 self.models[model_name] = await self.controller.get_model(
812 model_name,
813 )
814
815 # Create an observer for this model
816 self.monitors[model_name] = VCAMonitor(model_name)
817 self.models[model_name].add_observer(self.monitors[model_name])
818
819 return self.models[model_name]
820
821 async def login(self):
822 """Login to the Juju controller."""
823
824 if self.authenticated:
825 return
826
827 self.connecting = True
828
829 self.log.debug("JujuApi: Logging into controller")
830
831 cacert = None
832 self.controller = Controller(loop=self.loop)
833
834 if self.secret:
835 self.log.debug(
836 "Connecting to controller... ws://{}:{} as {}/{}".format(
837 self.endpoint,
838 self.port,
839 self.user,
840 self.secret,
841 )
842 )
843 await self.controller.connect(
844 endpoint=self.endpoint,
845 username=self.user,
846 password=self.secret,
847 cacert=cacert,
848 )
849 else:
850 # current_controller no longer exists
851 # self.log.debug("Connecting to current controller...")
852 # await self.controller.connect_current()
853 # await self.controller.connect(
854 # endpoint=self.endpoint,
855 # username=self.user,
856 # cacert=cacert,
857 # )
858 self.log.fatal("VCA credentials not configured.")
859
860 self.authenticated = True
861 self.log.debug("JujuApi: Logged into controller")
862
863 # self.default_model = await self.controller.get_model("default")
864
865 async def logout(self):
866 """Logout of the Juju controller."""
867 if not self.authenticated:
868 return
869
870 try:
871 if self.default_model:
872 self.log.debug("Disconnecting model {}".format(
873 self.default_model
874 ))
875 await self.default_model.disconnect()
876 self.default_model = None
877
878 for model in self.models:
879 await self.models[model].disconnect()
880 model = None
881
882 if self.controller:
883 self.log.debug("Disconnecting controller {}".format(
884 self.controller
885 ))
886 await self.controller.disconnect()
887 self.controller = None
888
889 self.authenticated = False
890 except Exception as e:
891 self.log.fatal(
892 "Fatal error logging out of Juju Controller: {}".format(e)
893 )
894 raise e
895
896 # async def remove_application(self, name):
897 # """Remove the application."""
898 # if not self.authenticated:
899 # await self.login()
900 #
901 # app = await self.get_application(name)
902 # if app:
903 # self.log.debug("JujuApi: Destroying application {}".format(
904 # name,
905 # ))
906 #
907 # await app.destroy()
908
909 async def remove_relation(self, a, b):
910 """
911 Remove a relation between two application endpoints
912
913 :param a An application endpoint
914 :param b An application endpoint
915 """
916 if not self.authenticated:
917 await self.login()
918
919 m = await self.get_model()
920 try:
921 m.remove_relation(a, b)
922 finally:
923 await m.disconnect()
924
925 async def resolve_error(self, application=None):
926 """Resolve units in error state."""
927 if not self.authenticated:
928 await self.login()
929
930 app = await self.get_application(self.default_model, application)
931 if app:
932 self.log.debug(
933 "JujuApi: Resolving errors for application {}".format(
934 application,
935 )
936 )
937
938 for unit in app.units:
939 app.resolved(retry=True)
940
941 async def run_action(self, application, action_name, **params):
942 """Execute an action and return an Action object."""
943 if not self.authenticated:
944 await self.login()
945 result = {
946 'status': '',
947 'action': {
948 'tag': None,
949 'results': None,
950 }
951 }
952 app = await self.get_application(self.default_model, application)
953 if app:
954 # We currently only have one unit per application
955 # so use the first unit available.
956 unit = app.units[0]
957
958 self.log.debug(
959 "JujuApi: Running Action {} against Application {}".format(
960 action_name,
961 application,
962 )
963 )
964
965 action = await unit.run_action(action_name, **params)
966
967 # Wait for the action to complete
968 await action.wait()
969
970 result['status'] = action.status
971 result['action']['tag'] = action.data['id']
972 result['action']['results'] = action.results
973
974 return result
975
976 async def set_config(self, model_name, application, config):
977 """Apply a configuration to the application."""
978 if not self.authenticated:
979 await self.login()
980
981 app = await self.get_application(model_name, application)
982 if app:
983 self.log.debug("JujuApi: Setting config for Application {}".format(
984 application,
985 ))
986 await app.set_config(config)
987
988 # Verify the config is set
989 newconf = await app.get_config()
990 for key in config:
991 if config[key] != newconf[key]['value']:
992 self.log.debug("JujuApi: Config not set! Key {} Value {} doesn't match {}".format(key, config[key], newconf[key]))
993
994 # async def set_parameter(self, parameter, value, application=None):
995 # """Set a config parameter for a service."""
996 # if not self.authenticated:
997 # await self.login()
998 #
999 # self.log.debug("JujuApi: Setting {}={} for Application {}".format(
1000 # parameter,
1001 # value,
1002 # application,
1003 # ))
1004 # return await self.apply_config(
1005 # {parameter: value},
1006 # application=application,
1007 # )
1008
1009 async def wait_for_application(self, model_name, application_name,
1010 timeout=300):
1011 """Wait for an application to become active."""
1012 if not self.authenticated:
1013 await self.login()
1014
1015 # TODO: In a point release, we will use a model per deployed network
1016 # service. In the meantime, we will always use the 'default' model.
1017 model_name = 'default'
1018 model = await self.get_model(model_name)
1019
1020 app = await self.get_application(model, application_name)
1021 self.log.debug("Application: {}".format(app))
1022 # app = await self.get_application(model_name, application_name)
1023 if app:
1024 self.log.debug(
1025 "JujuApi: Waiting {} seconds for Application {}".format(
1026 timeout,
1027 application_name,
1028 )
1029 )
1030
1031 await model.block_until(
1032 lambda: all(
1033 unit.agent_status == 'idle' and unit.workload_status in
1034 ['active', 'unknown'] for unit in app.units
1035 ),
1036 timeout=timeout
1037 )
|
__label__pos
| 0.993532 |
blob: fcf98ee782ca02fe7f68b33a65402cc57e60908e [file] [log] [blame]
// Copyright 2017 Serde Developers
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use error::Error;
use serde::de::{self, Unexpected, Visitor};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::fmt::{self, Debug, Display};
#[cfg(feature = "arbitrary_precision")]
use itoa;
#[cfg(feature = "arbitrary_precision")]
use ryu;
#[cfg(feature = "arbitrary_precision")]
use serde::de::{IntoDeserializer, MapAccess};
use de::ParserNumber;
#[cfg(feature = "arbitrary_precision")]
use error::ErrorCode;
#[cfg(feature = "arbitrary_precision")]
/// Not public API. Should be pub(crate).
#[doc(hidden)]
pub const TOKEN: &'static str = "$serde_json::private::Number";
/// Represents a JSON number, whether integer or floating point.
#[derive(Clone, PartialEq)]
pub struct Number {
n: N,
}
#[cfg(not(feature = "arbitrary_precision"))]
#[derive(Copy, Clone, PartialEq)]
enum N {
PosInt(u64),
/// Always less than zero.
NegInt(i64),
/// Always finite.
Float(f64),
}
#[cfg(feature = "arbitrary_precision")]
type N = String;
impl Number {
/// Returns true if the `Number` is an integer between `i64::MIN` and
/// `i64::MAX`.
///
/// For any Number on which `is_i64` returns true, `as_i64` is guaranteed to
/// return the integer value.
///
/// ```rust
/// # #[macro_use]
/// # extern crate serde_json;
/// #
/// # fn main() {
/// let big = i64::max_value() as u64 + 10;
/// let v = json!({ "a": 64, "b": big, "c": 256.0 });
///
/// assert!(v["a"].is_i64());
///
/// // Greater than i64::MAX.
/// assert!(!v["b"].is_i64());
///
/// // Numbers with a decimal point are not considered integers.
/// assert!(!v["c"].is_i64());
/// # }
/// ```
#[inline]
pub fn is_i64(&self) -> bool {
#[cfg(not(feature = "arbitrary_precision"))]
match self.n {
N::PosInt(v) => v <= i64::max_value() as u64,
N::NegInt(_) => true,
N::Float(_) => false,
}
#[cfg(feature = "arbitrary_precision")]
self.as_i64().is_some()
}
/// Returns true if the `Number` is an integer between zero and `u64::MAX`.
///
/// For any Number on which `is_u64` returns true, `as_u64` is guaranteed to
/// return the integer value.
///
/// ```rust
/// # #[macro_use]
/// # extern crate serde_json;
/// #
/// # fn main() {
/// let v = json!({ "a": 64, "b": -64, "c": 256.0 });
///
/// assert!(v["a"].is_u64());
///
/// // Negative integer.
/// assert!(!v["b"].is_u64());
///
/// // Numbers with a decimal point are not considered integers.
/// assert!(!v["c"].is_u64());
/// # }
/// ```
#[inline]
pub fn is_u64(&self) -> bool {
#[cfg(not(feature = "arbitrary_precision"))]
match self.n {
N::PosInt(_) => true,
N::NegInt(_) | N::Float(_) => false,
}
#[cfg(feature = "arbitrary_precision")]
self.as_u64().is_some()
}
/// Returns true if the `Number` can be represented by f64.
///
/// For any Number on which `is_f64` returns true, `as_f64` is guaranteed to
/// return the floating point value.
///
/// Currently this function returns true if and only if both `is_i64` and
/// `is_u64` return false but this is not a guarantee in the future.
///
/// ```rust
/// # #[macro_use]
/// # extern crate serde_json;
/// #
/// # fn main() {
/// let v = json!({ "a": 256.0, "b": 64, "c": -64 });
///
/// assert!(v["a"].is_f64());
///
/// // Integers.
/// assert!(!v["b"].is_f64());
/// assert!(!v["c"].is_f64());
/// # }
/// ```
#[inline]
pub fn is_f64(&self) -> bool {
#[cfg(not(feature = "arbitrary_precision"))]
match self.n {
N::Float(_) => true,
N::PosInt(_) | N::NegInt(_) => false,
}
#[cfg(feature = "arbitrary_precision")]
{
for c in self.n.chars() {
if c == '.' || c == 'e' || c == 'E' {
return self.n.parse::<f64>().ok().map_or(false, |f| f.is_finite());
}
}
false
}
}
/// If the `Number` is an integer, represent it as i64 if possible. Returns
/// None otherwise.
///
/// ```rust
/// # #[macro_use]
/// # extern crate serde_json;
/// #
/// # fn main() {
/// let big = i64::max_value() as u64 + 10;
/// let v = json!({ "a": 64, "b": big, "c": 256.0 });
///
/// assert_eq!(v["a"].as_i64(), Some(64));
/// assert_eq!(v["b"].as_i64(), None);
/// assert_eq!(v["c"].as_i64(), None);
/// # }
/// ```
#[inline]
pub fn as_i64(&self) -> Option<i64> {
#[cfg(not(feature = "arbitrary_precision"))]
match self.n {
N::PosInt(n) => if n <= i64::max_value() as u64 {
Some(n as i64)
} else {
None
},
N::NegInt(n) => Some(n),
N::Float(_) => None,
}
#[cfg(feature = "arbitrary_precision")]
self.n.parse().ok()
}
/// If the `Number` is an integer, represent it as u64 if possible. Returns
/// None otherwise.
///
/// ```rust
/// # #[macro_use]
/// # extern crate serde_json;
/// #
/// # fn main() {
/// let v = json!({ "a": 64, "b": -64, "c": 256.0 });
///
/// assert_eq!(v["a"].as_u64(), Some(64));
/// assert_eq!(v["b"].as_u64(), None);
/// assert_eq!(v["c"].as_u64(), None);
/// # }
/// ```
#[inline]
pub fn as_u64(&self) -> Option<u64> {
#[cfg(not(feature = "arbitrary_precision"))]
match self.n {
N::PosInt(n) => Some(n),
N::NegInt(_) | N::Float(_) => None,
}
#[cfg(feature = "arbitrary_precision")]
self.n.parse().ok()
}
/// Represents the number as f64 if possible. Returns None otherwise.
///
/// ```rust
/// # #[macro_use]
/// # extern crate serde_json;
/// #
/// # fn main() {
/// let v = json!({ "a": 256.0, "b": 64, "c": -64 });
///
/// assert_eq!(v["a"].as_f64(), Some(256.0));
/// assert_eq!(v["b"].as_f64(), Some(64.0));
/// assert_eq!(v["c"].as_f64(), Some(-64.0));
/// # }
/// ```
#[inline]
pub fn as_f64(&self) -> Option<f64> {
#[cfg(not(feature = "arbitrary_precision"))]
match self.n {
N::PosInt(n) => Some(n as f64),
N::NegInt(n) => Some(n as f64),
N::Float(n) => Some(n),
}
#[cfg(feature = "arbitrary_precision")]
self.n.parse().ok()
}
/// Converts a finite `f64` to a `Number`. Infinite or NaN values are not JSON
/// numbers.
///
/// ```rust
/// # use std::f64;
/// #
/// # use serde_json::Number;
/// #
/// assert!(Number::from_f64(256.0).is_some());
///
/// assert!(Number::from_f64(f64::NAN).is_none());
/// ```
#[inline]
pub fn from_f64(f: f64) -> Option<Number> {
if f.is_finite() {
let n = {
#[cfg(not(feature = "arbitrary_precision"))]
{
N::Float(f)
}
#[cfg(feature = "arbitrary_precision")]
{
ryu::Buffer::new().format(f).to_owned()
}
};
Some(Number { n: n })
} else {
None
}
}
#[cfg(feature = "arbitrary_precision")]
/// Not public API. Only tests use this.
#[doc(hidden)]
#[inline]
pub fn from_string_unchecked(n: String) -> Self {
Number { n: n }
}
}
impl fmt::Display for Number {
#[cfg(not(feature = "arbitrary_precision"))]
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
match self.n {
N::PosInt(u) => Display::fmt(&u, formatter),
N::NegInt(i) => Display::fmt(&i, formatter),
N::Float(f) => Display::fmt(&f, formatter),
}
}
#[cfg(feature = "arbitrary_precision")]
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
Display::fmt(&self.n, formatter)
}
}
impl Debug for Number {
#[cfg(not(feature = "arbitrary_precision"))]
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let mut debug = formatter.debug_tuple("Number");
match self.n {
N::PosInt(i) => {
debug.field(&i);
}
N::NegInt(i) => {
debug.field(&i);
}
N::Float(f) => {
debug.field(&f);
}
}
debug.finish()
}
#[cfg(feature = "arbitrary_precision")]
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
write!(formatter, "Number({})", &self.n)
}
}
impl Serialize for Number {
#[cfg(not(feature = "arbitrary_precision"))]
#[inline]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
match self.n {
N::PosInt(u) => serializer.serialize_u64(u),
N::NegInt(i) => serializer.serialize_i64(i),
N::Float(f) => serializer.serialize_f64(f),
}
}
#[cfg(feature = "arbitrary_precision")]
#[inline]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
use serde::ser::SerializeStruct;
let mut s = serializer.serialize_struct(TOKEN, 1)?;
s.serialize_field(TOKEN, &self.n)?;
s.end()
}
}
impl<'de> Deserialize<'de> for Number {
#[inline]
fn deserialize<D>(deserializer: D) -> Result<Number, D::Error>
where
D: Deserializer<'de>,
{
struct NumberVisitor;
impl<'de> Visitor<'de> for NumberVisitor {
type Value = Number;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("a JSON number")
}
#[inline]
fn visit_i64<E>(self, value: i64) -> Result<Number, E> {
Ok(value.into())
}
#[inline]
fn visit_u64<E>(self, value: u64) -> Result<Number, E> {
Ok(value.into())
}
#[inline]
fn visit_f64<E>(self, value: f64) -> Result<Number, E>
where
E: de::Error,
{
Number::from_f64(value).ok_or_else(|| de::Error::custom("not a JSON number"))
}
#[cfg(feature = "arbitrary_precision")]
#[inline]
fn visit_map<V>(self, mut visitor: V) -> Result<Number, V::Error>
where
V: de::MapAccess<'de>,
{
let value = visitor.next_key::<NumberKey>()?;
if value.is_none() {
return Err(de::Error::invalid_type(Unexpected::Map, &self));
}
let v: NumberFromString = visitor.next_value()?;
Ok(v.value)
}
}
deserializer.deserialize_any(NumberVisitor)
}
}
#[cfg(feature = "arbitrary_precision")]
struct NumberKey;
#[cfg(feature = "arbitrary_precision")]
impl<'de> de::Deserialize<'de> for NumberKey {
fn deserialize<D>(deserializer: D) -> Result<NumberKey, D::Error>
where
D: de::Deserializer<'de>,
{
struct FieldVisitor;
impl<'de> de::Visitor<'de> for FieldVisitor {
type Value = ();
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("a valid number field")
}
fn visit_str<E>(self, s: &str) -> Result<(), E>
where
E: de::Error,
{
if s == TOKEN {
Ok(())
} else {
Err(de::Error::custom("expected field with custom name"))
}
}
}
deserializer.deserialize_identifier(FieldVisitor)?;
Ok(NumberKey)
}
}
#[cfg(feature = "arbitrary_precision")]
pub struct NumberFromString {
pub value: Number,
}
#[cfg(feature = "arbitrary_precision")]
impl<'de> de::Deserialize<'de> for NumberFromString {
fn deserialize<D>(deserializer: D) -> Result<NumberFromString, D::Error>
where
D: de::Deserializer<'de>,
{
struct Visitor;
impl<'de> de::Visitor<'de> for Visitor {
type Value = NumberFromString;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("string containing a number")
}
fn visit_str<E>(self, s: &str) -> Result<NumberFromString, E>
where
E: de::Error,
{
let n = try!(s.parse().map_err(de::Error::custom));
Ok(NumberFromString { value: n })
}
}
deserializer.deserialize_str(Visitor)
}
}
#[cfg(feature = "arbitrary_precision")]
fn invalid_number() -> Error {
Error::syntax(ErrorCode::InvalidNumber, 0, 0)
}
macro_rules! deserialize_any {
(@expand [$($num_string:tt)*]) => {
#[cfg(not(feature = "arbitrary_precision"))]
#[inline]
fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Error>
where
V: Visitor<'de>,
{
match self.n {
N::PosInt(u) => visitor.visit_u64(u),
N::NegInt(i) => visitor.visit_i64(i),
N::Float(f) => visitor.visit_f64(f),
}
}
#[cfg(feature = "arbitrary_precision")]
#[inline]
fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Error>
where V: Visitor<'de>
{
if let Some(u) = self.as_u64() {
return visitor.visit_u64(u);
} else if let Some(i) = self.as_i64() {
return visitor.visit_i64(i);
} else if let Some(f) = self.as_f64() {
if f.to_string() == self.n {
return visitor.visit_f64(f);
}
}
visitor.visit_map(NumberDeserializer {
number: Some(self.$($num_string)*),
})
}
};
(owned) => {
deserialize_any!(@expand [n]);
};
(ref) => {
deserialize_any!(@expand [n.clone()]);
};
}
macro_rules! deserialize_number {
($deserialize:ident => $visit:ident) => {
#[cfg(not(feature = "arbitrary_precision"))]
fn $deserialize<V>(self, visitor: V) -> Result<V::Value, Error>
where
V: Visitor<'de>,
{
self.deserialize_any(visitor)
}
#[cfg(feature = "arbitrary_precision")]
fn $deserialize<V>(self, visitor: V) -> Result<V::Value, Error>
where
V: de::Visitor<'de>,
{
visitor.$visit(self.n.parse().map_err(|_| invalid_number())?)
}
}
}
impl<'de> Deserializer<'de> for Number {
type Error = Error;
deserialize_any!(owned);
deserialize_number!(deserialize_i8 => visit_i8);
deserialize_number!(deserialize_i16 => visit_i16);
deserialize_number!(deserialize_i32 => visit_i32);
deserialize_number!(deserialize_i64 => visit_i64);
deserialize_number!(deserialize_u8 => visit_u8);
deserialize_number!(deserialize_u16 => visit_u16);
deserialize_number!(deserialize_u32 => visit_u32);
deserialize_number!(deserialize_u64 => visit_u64);
deserialize_number!(deserialize_f32 => visit_f32);
deserialize_number!(deserialize_f64 => visit_f64);
serde_if_integer128! {
deserialize_number!(deserialize_i128 => visit_i128);
deserialize_number!(deserialize_u128 => visit_u128);
}
forward_to_deserialize_any! {
bool char str string bytes byte_buf option unit unit_struct
newtype_struct seq tuple tuple_struct map struct enum identifier
ignored_any
}
}
impl<'de, 'a> Deserializer<'de> for &'a Number {
type Error = Error;
deserialize_any!(ref);
deserialize_number!(deserialize_i8 => visit_i8);
deserialize_number!(deserialize_i16 => visit_i16);
deserialize_number!(deserialize_i32 => visit_i32);
deserialize_number!(deserialize_i64 => visit_i64);
deserialize_number!(deserialize_u8 => visit_u8);
deserialize_number!(deserialize_u16 => visit_u16);
deserialize_number!(deserialize_u32 => visit_u32);
deserialize_number!(deserialize_u64 => visit_u64);
deserialize_number!(deserialize_f32 => visit_f32);
deserialize_number!(deserialize_f64 => visit_f64);
serde_if_integer128! {
deserialize_number!(deserialize_i128 => visit_i128);
deserialize_number!(deserialize_u128 => visit_u128);
}
forward_to_deserialize_any! {
bool char str string bytes byte_buf option unit unit_struct
newtype_struct seq tuple tuple_struct map struct enum identifier
ignored_any
}
}
#[cfg(feature = "arbitrary_precision")]
// Not public API. Should be pub(crate).
#[doc(hidden)]
pub struct NumberDeserializer {
pub number: Option<String>,
}
#[cfg(feature = "arbitrary_precision")]
impl<'de> MapAccess<'de> for NumberDeserializer {
type Error = Error;
fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>, Error>
where
K: de::DeserializeSeed<'de>,
{
if self.number.is_none() {
return Ok(None);
}
seed.deserialize(NumberFieldDeserializer).map(Some)
}
fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value, Error>
where
V: de::DeserializeSeed<'de>,
{
seed.deserialize(self.number.take().unwrap().into_deserializer())
}
}
#[cfg(feature = "arbitrary_precision")]
struct NumberFieldDeserializer;
#[cfg(feature = "arbitrary_precision")]
impl<'de> Deserializer<'de> for NumberFieldDeserializer {
type Error = Error;
fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Error>
where
V: de::Visitor<'de>,
{
visitor.visit_borrowed_str(TOKEN)
}
forward_to_deserialize_any! {
bool u8 u16 u32 u64 u128 i8 i16 i32 i64 i128 f32 f64 char str string seq
bytes byte_buf map struct option unit newtype_struct ignored_any
unit_struct tuple_struct tuple enum identifier
}
}
impl From<ParserNumber> for Number {
fn from(value: ParserNumber) -> Self {
let n = match value {
ParserNumber::F64(f) => {
#[cfg(not(feature = "arbitrary_precision"))]
{
N::Float(f)
}
#[cfg(feature = "arbitrary_precision")]
{
f.to_string()
}
}
ParserNumber::U64(u) => {
#[cfg(not(feature = "arbitrary_precision"))]
{
N::PosInt(u)
}
#[cfg(feature = "arbitrary_precision")]
{
u.to_string()
}
}
ParserNumber::I64(i) => {
#[cfg(not(feature = "arbitrary_precision"))]
{
N::NegInt(i)
}
#[cfg(feature = "arbitrary_precision")]
{
i.to_string()
}
}
#[cfg(feature = "arbitrary_precision")]
ParserNumber::String(s) => s,
};
Number { n: n }
}
}
macro_rules! impl_from_unsigned {
(
$($ty:ty),*
) => {
$(
impl From<$ty> for Number {
#[inline]
fn from(u: $ty) -> Self {
let n = {
#[cfg(not(feature = "arbitrary_precision"))]
{ N::PosInt(u as u64) }
#[cfg(feature = "arbitrary_precision")]
{
itoa::Buffer::new().format(u).to_owned()
}
};
Number { n: n }
}
}
)*
};
}
macro_rules! impl_from_signed {
(
$($ty:ty),*
) => {
$(
impl From<$ty> for Number {
#[inline]
fn from(i: $ty) -> Self {
let n = {
#[cfg(not(feature = "arbitrary_precision"))]
{
if i < 0 {
N::NegInt(i as i64)
} else {
N::PosInt(i as u64)
}
}
#[cfg(feature = "arbitrary_precision")]
{
itoa::Buffer::new().format(i).to_owned()
}
};
Number { n: n }
}
}
)*
};
}
impl_from_unsigned!(u8, u16, u32, u64, usize);
impl_from_signed!(i8, i16, i32, i64, isize);
impl Number {
#[cfg(not(feature = "arbitrary_precision"))]
// Not public API. Should be pub(crate).
#[doc(hidden)]
#[cold]
pub fn unexpected(&self) -> Unexpected {
match self.n {
N::PosInt(u) => Unexpected::Unsigned(u),
N::NegInt(i) => Unexpected::Signed(i),
N::Float(f) => Unexpected::Float(f),
}
}
#[cfg(feature = "arbitrary_precision")]
// Not public API. Should be pub(crate).
#[doc(hidden)]
#[cold]
pub fn unexpected(&self) -> Unexpected {
Unexpected::Other("number")
}
}
|
__label__pos
| 0.999593 |
[Fixed]-Django count related objects
21👍
I have not tried how many queries are executed, but the Django way should be using annotate(). For example:
from django.db.models import Count
q = A.objects.select_related('B').annotate(num_B=Count('B'))
print A[0].num_B
6👍
Since Django 2.0 Count() aggregate function accepts filter parameter, which allows applying additional restrictions on the related objects queryset.
Works like this:
A.objects.select_related().annotate(
total=models.Count('myrelated__pk', filter=Q(only_items='that-i-need'))
).all()
👤abcdn
5👍
I have to answer my own question 🙂 If object of A is queried something like this:
A.objects.select_related().filter(atrr=val).annotate(n_b=models.Count('B'))
This creates very long query, but at least there is just one.
👤ivan
Leave a comment
|
__label__pos
| 0.99623 |
answersLogoWhite
0
Best Answer
it means 8+3x
8 increased (plus) three times a number (3x) x is an unknown number so it is often called a number
User Avatar
Wiki User
2012-01-09 23:48:31
This answer is:
🙏
0
🤨
0
😮
0
User Avatar
Add your answer:
Earn +20 pts
Q: What does 8 increased by three times a number?
Write your answer...
Submit
Related questions
What is 8 increased by three times a number?
8+3*x
What can you times three times to get 8?
22 x 2 x 2 = 4 x 2 = 88 is a cube number = a number made by multiplying the same number by itself three times
What is Three-fourths of a number increased by one-half?
That gives you 11/8 of the number.
What is 8 more than three times a number?
3n + 8
5 more than 8 times a number?
8z + 5
What number is 8 times less then 24?
Three.
How do you know if a number is divisble by 8?
If the number is a multiple of 8 or greater than 8. or divide by two, three times
What is three times a number is 24?
3 x 8
When a number is increased by 8 the original value is 75 percent of the new value What is the original value of the number?
So 25% of the new value is the newly-added 8. Therefore the original value is three times that, i.e. 24. This means that three 8s plus the other 8 - i.e. four 8s - equals 32.
A number increased by 8?
X = number.X + 8====
When 7 times a number is decreased by 8 the answer is the same as when 3 times the number is increased by 4?
7x - 8 = 3x + 4 4x - 8 = 4 4x = 12 x = 3 Check it. 21 - 8 = 9 + 4 It checks.
What is the product in which a number is a factor three times?
A number multiplied by itself three times is a cube number. Examples are 2 x 2 x 2 or 23 = 8.
Ten times the number n decreased by 13 is equal to the square of the same number n increased by 3?
If ten times the number n decreased by 13 is equal to the square of the same number n increased by 3, then the value of n is either 8 or 2.
Eight less than three times a number?
3n>8
How do you write three times a number is equal to 8 more than twice the number?
It is: 3x = 2x+8 and the value of x is 8
A number increased by 6 is 8?
The number is 2
What is the sum of a number increased by 8?
8 greater than the original number.
What is the probability of rolling a odd number three times on a fair number cube?
1/8
What is increased in math?
A number like m increased by 8 for example it would be like m+8.
What is 8 increased by a number x?
The expression is: 8+x
What is a sentence for three times the sum of a number and eight?
3(x+8)
What is the algebraic expression of three times the number eight?
3 x 8
how many times in New Testament the reference to number three appear?
Three is referenced 63 times in the New Testament. Threescore is referenced 8 times.
What is the number of times three hours goes into a day?
24 hours in one day so 24/3 = 8
What does the difference of three times a number and eight look like as an equation?
3x + 8
People also asked
What the product of 18 and q?
View results
The sum of a number and 10?
View results
What is 8 increased by three times a number?
View results
What the sum of a number and 10?
View results
What the difference of 17 and 5 times a number?
View results
What 9 less than g to the fourth power?
View results
|
__label__pos
| 1 |
Anonymous
How Do I Write A Letter On My Mac Computer?
6
6 Answers
Ebony Nash Profile
Ebony Nash answered
It is fairly simple to write a letter on a Mac computer. Firstly for a simple blank page you can use the in-built program called Text Edit. To find Text Edit you need to head into your applications folder which is marked with an A. When you find the program called Text Edit click on it. It will then open a blank page which you can start to compose your letter on.
You may also have Microsoft Word if you loaded it onto your computer. This again will be found in the applications section if it is not on your dashboard on the bottom of your screen. It will be a blue W symbol. If you do own this; click on it and you can use this for a few extra options over the simple Text Edit program.
When writing an official letter, you need to get the layout correct. The best way is to follow the MLA guidelines. This means having the date at the very top aligned to the right. Then press the space bar twice; include the address of the person you are sending it to. Once more press the space bar twice and align back to the left
To start any formal letter you need an appropriate greeting. The best for a letter such as this is to address the person as ‘Dear’ and then put their full name. Finally, you should finish your letter with a formal sign off, such as ‘Sincerely’ and then your full name.
Oddman Profile
Oddman answered
For typing an uncomplicated letter with no graphics, you can use the TextEdit application that comes with the Mac, or you can use another word processor of your choice. NeoOffice is a free application you can download that includes a full-featured word processor.
Open the Applications folder, double-click on TextEdit. Type the text of your letter in the window. Format fonts, text size, spacing, and margins the way you want, then print. Formatting and printing can be accomplished using the menus provided.
Karl Sagan Profile
Karl Sagan answered
I've bought a makbook a few weeks ago and it's a completely different experience. I mostly like it but sometimes it gets quite har to find some software. Like looking for a proper vpn for mac took me about an hour which really is a lot of time for such a simple task.
Sophie Carroll Profile
Sophie Carroll answered
Hey there. It is quite simple with modern application. You can find a lot of guides and tutorials in internet, for example on Youtube. I think better will be to focus on content. For example check this letter to the queen, in my opinion it is quite interesting!
Judith (Irish Faerie Blessings) Kreindel Profile
You likely need Microsoft Word for Windows which may not have come on your system pre-installed.
thanked the writer.
Oddman
Oddman commented
Microsoft's marketing department has worked their magic on you. "Word for Windows" is not necessary.
A Mac comes with a suitable text editor, and there is at least one good Microsoft Word work-alike editor available for free for a Mac.
It is way more work than necessary to install Windows and Word for Windows on a Mac just to write letters. Microsoft makes "Microsoft Office 2008 for Mac Home and Student Edition" just for Mac computers, if you feel you can't live without it.
Answer Question
Anonymous
|
__label__pos
| 0.656998 |
# HG changeset patch # User Christian Stump # Date 1352623639 -3600 # Node ID 79ce1f7cd3129cb2207af0607b4012ea77251484 # Parent 4b443ee014320597ee2a9cf6c14bf267c177b4a4 #12882: Allows a generalized Cartan matrix as input for Dynkin diagrams diff --git a/sage/combinat/root_system/all.py b/sage/combinat/root_system/all.py --- a/sage/combinat/root_system/all.py +++ b/sage/combinat/root_system/all.py @@ -2,7 +2,7 @@ from sage.misc.lazy_import import lazy_i lazy_import('sage.combinat.root_system.associahedron', 'Associahedron') from cartan_type import CartanType -from dynkin_diagram import DynkinDiagram, dynkin_diagram +from dynkin_diagram import DynkinDiagram from cartan_matrix import CartanMatrix, cartan_matrix from coxeter_matrix import coxeter_matrix from root_system import RootSystem, WeylDim diff --git a/sage/combinat/root_system/cartan_matrix.py b/sage/combinat/root_system/cartan_matrix.py --- a/sage/combinat/root_system/cartan_matrix.py +++ b/sage/combinat/root_system/cartan_matrix.py @@ -228,14 +228,20 @@ class CartanMatrix(Matrix_integer_sparse cartan_type = None dynkin_diagram = None subdivisions = None - try: - cartan_type = CartanType(args[0]) - dynkin_diagram = cartan_type.dynkin_diagram() - except (TypeError, ValueError): - pass + + from sage.combinat.root_system.dynkin_diagram import DynkinDiagram_class + if isinstance(args[0], DynkinDiagram_class): + dynkin_diagram = args[0] + cartan_type = args[0]._cartan_type + else: + try: + cartan_type = CartanType(args[0]) + dynkin_diagram = cartan_type.dynkin_diagram() + except (TypeError, ValueError): + pass if dynkin_diagram is not None: - n = cartan_type.rank() + n = dynkin_diagram.rank() index_set = dynkin_diagram.index_set() reverse = dict((index_set[i], i) for i in range(len(index_set))) data = {(i, i): 2 for i in range(n)} @@ -259,7 +265,7 @@ class CartanMatrix(Matrix_integer_sparse if cartan_type is not None: index_set = tuple(cartan_type.index_set()) else: - index_set = tuple(range(M.ncols())) + index_set = tuple(range(n)) elif len(args) == 2: index_set = tuple(args[1]) if len(index_set) != n and len(set(index_set)) != n: @@ -410,17 +416,7 @@ class CartanMatrix(Matrix_integer_sparse from sage.combinat.root_system.dynkin_diagram import DynkinDiagram if self._cartan_type is not None: return DynkinDiagram(self._cartan_type) - - from dynkin_diagram import DynkinDiagram_class - n = self.nrows() - g = DynkinDiagram_class(self) - for i in range(n): - for j in range(n): - if self[i,j] == -1: - g.add_edge(i, j) - elif self[i,j] < -1: - g.add_edge(i, j, -self[i,j]) - return g + return DynkinDiagram(self) def cartan_matrix(self): r""" @@ -509,9 +505,12 @@ class CartanMatrix(Matrix_integer_sparse sage: M = CartanMatrix(['D',4,1]) sage: M.is_finite() False + sage: M = CartanMatrix([[2, -4], [-3, 2]]) + sage: M.is_finite() + False """ if self._cartan_type is None: - return False + return self.det() > 0 return self._cartan_type.is_finite() def is_affine(self): @@ -526,9 +525,12 @@ class CartanMatrix(Matrix_integer_sparse sage: M = CartanMatrix(['D',4,1]) sage: M.is_affine() True + sage: M = CartanMatrix([[2, -4], [-3, 2]]) + sage: M.is_affine() + False """ if self._cartan_type is None: - return False + return self.det() == 0 return self._cartan_type.is_affine() def is_generalized_cartan_matrix(M): diff --git a/sage/combinat/root_system/dynkin_diagram.py b/sage/combinat/root_system/dynkin_diagram.py --- a/sage/combinat/root_system/dynkin_diagram.py +++ b/sage/combinat/root_system/dynkin_diagram.py @@ -8,9 +8,13 @@ AUTHORS: - Travis Scrimshaw (2013-06-11): Changed inputs of Dynkin diagrams to handle other Dynkin diagrams and graphs. Implemented remaining Cartan type methods. + +- Christian Stump, Travis Scrimshaw (2013-04-11): Added Cartan matrix as + possible input for Dynkin diagrams. """ #***************************************************************************** -# Copyright (C) 2007 Mike Hansen , +# Copyright (C) 2007 Mike Hansen , +# Copyright (C) 2013 Travis Scrimshaw # # Distributed under the terms of the GNU General Public License (GPL) # @@ -24,18 +28,27 @@ AUTHORS: # http://www.gnu.org/licenses/ #***************************************************************************** from sage.misc.cachefunc import cached_method +from sage.matrix.matrix import is_Matrix +from sage.functions.generalized import sgn from sage.graphs.digraph import DiGraph -from cartan_type import CartanType, CartanType_abstract +from sage.combinat.root_system.cartan_type import CartanType, CartanType_abstract from sage.combinat.root_system.cartan_matrix import CartanMatrix from sage.misc.superseded import deprecated_function_alias -def DynkinDiagram(*args): +def DynkinDiagram(*args, **kwds): r""" - Return a Dynkin diagram for type ``ct``. + Return the Dynkin diagram corresponding to the input. INPUT: - - ``ct`` -- a Cartan Type + The input can be one of the following: + + - empty to obtain an empty Dynkin diagram + - a Cartan type + - a Cartan matrix + - a Cartan matrix and an indexing set + + Also one can input an index_set by The edge multiplicities are encoded as edge labels. This uses the convention in Hong and Kang, Kac, Fulton Harris, and crystals. This is the @@ -90,68 +103,138 @@ def DynkinDiagram(*args): 5 6 7 8 A2xB2xF4 + sage: R = RootSystem("A2xB2xF4") + sage: CM = R.cartan_matrix(); CM + [ 2 -1| 0 0| 0 0 0 0] + [-1 2| 0 0| 0 0 0 0] + [-----+-----+-----------] + [ 0 0| 2 -1| 0 0 0 0] + [ 0 0|-2 2| 0 0 0 0] + [-----+-----+-----------] + [ 0 0| 0 0| 2 -1 0 0] + [ 0 0| 0 0|-1 2 -1 0] + [ 0 0| 0 0| 0 -2 2 -1] + [ 0 0| 0 0| 0 0 -1 2] + sage: DD = DynkinDiagram(CM); DD + O---O + 1 2 + O=>=O + 3 4 + O---O=>=O---O + 5 6 7 8 + A2xB2xF4 + sage: DD.cartan_matrix() + [ 2 -1 0 0 0 0 0 0] + [-1 2 0 0 0 0 0 0] + [ 0 0 2 -1 0 0 0 0] + [ 0 0 -2 2 0 0 0 0] + [ 0 0 0 0 2 -1 0 0] + [ 0 0 0 0 -1 2 -1 0] + [ 0 0 0 0 0 -2 2 -1] + [ 0 0 0 0 0 0 -1 2] + + We can also create Dynkin diagrams from arbitrary Cartan matrices:: + + sage: C = CartanMatrix([[2, -3], [-4, 2]]) + sage: DynkinDiagram(C) + Dynkin diagram of rank 2 + sage: C.index_set() + (0, 1) + sage: CI = CartanMatrix([[2, -3], [-4, 2]], [3, 5]) + sage: DI = DynkinDiagram(CI) + sage: DI.index_set() + (3, 5) + sage: CII = CartanMatrix([[2, -3], [-4, 2]]) + sage: DII = DynkinDiagram(CII, ('y', 'x')) + sage: DII.index_set() + ('x', 'y') + .. SEEALSO:: :func:`CartanType` for a general discussion on Cartan types and in particular node labeling conventions. """ if len(args) == 0: - return DynkinDiagram_class() + return DynkinDiagram_class() + mat = args[0] + if is_Matrix(mat): + mat = CartanMatrix(*args) + if isinstance(mat, CartanMatrix): + if mat.cartan_type() is not None: + try: + return mat.cartan_type().dynkin_diagram() + except AttributeError: + raise ValueError("Dynkin diagram data not yet hardcoded for type %s"%ct) + if len(args) > 1: + index_set = tuple(args[1]) + elif "index_set" in kwds: + index_set = tuple(kwds["index_set"]) + else: + index_set = mat.index_set() + D = DynkinDiagram_class(index_set=index_set) + n = mat.nrows() + for i in range(n): + for j in range(n): + if i != j: + D.add_edge(index_set[i], index_set[j], -mat[j,i]) + return D ct = CartanType(*args) - if hasattr(ct, "dynkin_diagram"): + try: return ct.dynkin_diagram() - else: - raise ValueError, "Dynkin diagram data not yet hardcoded for type %s"%ct + except AttributeError: + raise ValueError("Dynkin diagram data not yet hardcoded for type %s"%ct) -def dynkin_diagram(t): + +class DynkinDiagram_class(DiGraph, CartanType_abstract): """ - Return the Dynkin diagram of type ``t``. + A Dynkin diagram. - Note that this function is deprecated, and that you should use - :func:`DynkinDiagram` instead as this will be disappearing in the - near future. + .. SEEALSO:: + + :func:`DynkinDiagram()` + + INPUT: + + - ``t`` -- a Cartan type, Cartan matrix, or ``None`` EXAMPLES:: - sage: dynkin_diagram(["A", 3]) - doctest:1: DeprecationWarning: dynkin_diagram is deprecated, use DynkinDiagram instead! - See http://trac.sagemath.org/3654 for details. + sage: DynkinDiagram(['A', 3]) O---O---O 1 2 3 A3 + sage: C = CartanMatrix([[2, -3], [-4, 2]]) + sage: DynkinDiagram(C) + Dynkin diagram of rank 2 + sage: C.dynkin_diagram().cartan_matrix() == C + True + + TESTS: + + Check that the correct type is returned when copied:: + + sage: d = DynkinDiagram(['A', 3]) + sage: type(copy(d)) + + + We check that :trac:`14655` is fixed:: + + sage: cd = copy(d) + sage: cd.add_vertex(4) + sage: d.vertices() != cd.vertices() + True + + Implementation note: if a Cartan type is given, then the nodes + are initialized from the index set of this Cartan type. """ - from sage.misc.superseded import deprecation - deprecation(3654, "dynkin_diagram is deprecated, use DynkinDiagram instead!") - return DynkinDiagram(t) - - -class DynkinDiagram_class(DiGraph, CartanType_abstract): - def __init__(self, t = None, **options): + def __init__(self, t=None, index_set=None, **options): """ - INPUT: - - - ``t`` -- a Cartan type or ``None`` + Initialize ``self``. EXAMPLES:: - + sage: d = DynkinDiagram(["A", 3]) sage: TestSuite(d).run() - - Check that the correct type is returned when copied:: - - sage: d = DynkinDiagram(["A", 3]) - sage: type(copy(d)) - - - We check that :trac:`14655` is fixed:: - - sage: cd = copy(d) - sage: cd.add_vertex(4) - sage: d.vertices() != cd.vertices() - True - - Implementation note: if a Cartan type is given, then the nodes - are initialized from the index set of this Cartan type. """ if isinstance(t, DiGraph): if isinstance(t, DynkinDiagram_class): @@ -163,7 +246,9 @@ class DynkinDiagram_class(DiGraph, Carta DiGraph.__init__(self, **options) self._cartan_type = t - if t is not None: + if index_set is not None: + self.add_vertices(index_set) + elif t is not None: self.add_vertices(t.index_set()) def _repr_(self): @@ -211,10 +296,25 @@ class DynkinDiagram_class(DiGraph, Carta ret += "\n\\end{tikzpicture}" return ret + def _matrix_(self): + """ + Return a regular matrix from ``self``. + + EXAMPLES:: + + sage: M = DynkinDiagram(['C',3])._matrix_(); M + [ 2 -1 0] + [-1 2 -2] + [ 0 -1 2] + sage: type(M) + + """ + return self.cartan_matrix()._matrix_() + def add_edge(self, i, j, label=1): """ EXAMPLES:: - + sage: from sage.combinat.root_system.dynkin_diagram import DynkinDiagram_class sage: d = DynkinDiagram_class(CartanType(['A',3])) sage: list(sorted(d.edges())) @@ -383,8 +483,13 @@ class DynkinDiagram_class(DiGraph, Carta sage: CartanType(['F',4]).dynkin_diagram().is_finite() True + sage: D = DynkinDiagram(CartanMatrix([[2, -4], [-3, 2]])) + sage: D.is_finite() + False """ - return self._cartan_type.is_finite() + if self._cartan_type is not None: + return self._cartan_type.is_finite() + return self.cartan_matrix().is_finite() def is_affine(self): """ @@ -394,8 +499,13 @@ class DynkinDiagram_class(DiGraph, Carta sage: CartanType(['F',4]).dynkin_diagram().is_affine() False + sage: D = DynkinDiagram(CartanMatrix([[2, -4], [-3, 2]])) + sage: D.is_affine() + False """ - return self._cartan_type.is_affine() + if self._cartan_type is not None: + return self._cartan_type.is_affine() + return self.cartan_matrix().is_affine() def is_irreducible(self): """
|
__label__pos
| 0.979597 |
Solved
Invalid precision value - ASP insert into Access DB
Posted on 2006-06-14
7
2,339 Views
Last Modified: 2008-01-09
Hi
I am getting the following error:
Error Type:
Microsoft OLE DB Provider for ODBC Drivers (0x80040E21)
[Microsoft][ODBC Microsoft Access Driver]Invalid precision value
/hr_v1.00/wz_emp_paydet_ins_1.asp, line 40
This is from a page that was built using the Macromedia Record Update Form Wizard. I created a recordset to select the appropriate record using a Session variable referencing the primary key of table EMP. Then I selected the DB Table EMP and the appropriate fields to be updated in the wizard. When the page tries to do the update I get the error above. The EMP.PayRate and EMP.StdHours fields are currency fields in an access DB but I only get the option to return Numeric values in the wizard. Please can anyone provide a possible solution/workaround?
CODE: appropriate head data and the body form
<%@LANGUAGE="VBSCRIPT"%>
<!--#include file="Connections/HRDB.asp" -->
<%
Dim MM_editAction
MM_editAction = CStr(Request.ServerVariables("SCRIPT_NAME"))
If (Request.QueryString <> "") Then
MM_editAction = MM_editAction & "?" & Server.HTMLEncode(Request.QueryString)
End If
' boolean to abort record edit
Dim MM_abortEdit
MM_abortEdit = false
%>
<%
' IIf implementation
Function MM_IIf(condition, ifTrue, ifFalse)
If condition = "" Then
MM_IIf = ifFalse
Else
MM_IIf = ifTrue
End If
End Function
%>
<%
If (CStr(Request("MM_update")) = "form1") Then
If (Not MM_abortEdit) Then
' execute the update
Dim MM_editCmd
Set MM_editCmd = Server.CreateObject ("ADODB.Command")
MM_editCmd.ActiveConnection = MM_HRDB_STRING
MM_editCmd.CommandText = "UPDATE EMP SET PayFreq = ?, PayMeth = ?, PayRate = ?, StdHours = ?, NiNo = ? WHERE EmpNo = ?"
MM_editCmd.Prepared = true
MM_editCmd.Parameters.Append MM_editCmd.CreateParameter("param1", 202, 1, -1, Request.Form("PayFreq")) ' adVarWChar
MM_editCmd.Parameters.Append MM_editCmd.CreateParameter("param2", 202, 1, -1, Request.Form("PayMeth")) ' adVarWChar
MM_editCmd.Parameters.Append MM_editCmd.CreateParameter("param3", 5, 1, 6, MM_IIF(Request.Form("PayRate"), Request.Form("PayRate"), null)) ' adDouble
MM_editCmd.Parameters.Append MM_editCmd.CreateParameter("param4", 5, 1, 6, MM_IIF(Request.Form("StdHours"), Request.Form("StdHours"), null)) ' adDouble
MM_editCmd.Parameters.Append MM_editCmd.CreateParameter("param5", 202, 1, 9, Request.Form("NiNo")) ' adVarWChar
MM_editCmd.Parameters.Append MM_editCmd.CreateParameter("param6", 5, 1, -1, MM_IIF(Request.Form("MM_recordId"), Request.Form("MM_recordId"), null)) ' adDouble
MM_editCmd.Execute
MM_editCmd.ActiveConnection.Close
' append the query string to the redirect URL
Dim MM_editRedirectUrl
MM_editRedirectUrl = "wz_emp_paydet_ins_0.asp"
If (Request.QueryString <> "") Then
If (InStr(1, MM_editRedirectUrl, "?", vbTextCompare) = 0) Then
MM_editRedirectUrl = MM_editRedirectUrl & "?" & Request.QueryString
Else
MM_editRedirectUrl = MM_editRedirectUrl & "&" & Request.QueryString
End If
End If
Response.Redirect(MM_editRedirectUrl)
End If
End If
%>
<%
Dim rsEMPupdPaydet1__param
rsEMPupdPaydet1__param = "-1"
If (Session("EmpNumber") <> "") Then
rsEMPupdPaydet1__param = Session("EmpNumber")
End If
%>
<%
Dim rsEMPupdPaydet1
Dim rsEMPupdPaydet1_cmd
Dim rsEMPupdPaydet1_numRows
Set rsEMPupdPaydet1_cmd = Server.CreateObject ("ADODB.Command")
rsEMPupdPaydet1_cmd.ActiveConnection = MM_HRDB_STRING
rsEMPupdPaydet1_cmd.CommandText = "SELECT EmpNo, TaxCode, PayFreq, PayMeth, PayRate, StdHours, NiNo FROM EMP WHERE EmpNo = ?"
rsEMPupdPaydet1_cmd.Prepared = true
rsEMPupdPaydet1_cmd.Parameters.Append rsEMPupdPaydet1_cmd.CreateParameter("param1", 5, 1, -1, rsEMPupdPaydet1__param) ' adDouble
Set rsEMPupdPaydet1 = rsEMPupdPaydet1_cmd.Execute
rsEMPupdPaydet1_numRows = 0
%>
</head>
<body bgcolor="#ffffff">
<td><img src="gfx/spacer.gif" width="1" height="31" border="0" alt="" /></td>
</tr>
<tr><!-- row 3 -->
<td rowspan="3" align="left" valign="top"><!-- InstanceBeginEditable name="EditContent" -->
<form method="POST" action="<%=MM_editAction%>" name="form1">
<table width="100%" border="0" cellspacing="8" cellpadding="0">
<tr align="left" valign="top">
<td colspan="3" class="form_header">Pay Details</td>
</tr>
<tr>
<td width="25%" align="left" valign="top" class="form_subhead">Pay Frequency</td>
<td width="25%" align="left" valign="top" class="form_subhead">Rate Indicator </td>
<td width="50%" align="left" valign="top" class="form_subhead">Salary Details </td>
</tr>
<tr align="left" valign="top">
<td align="left" valign="top"><table width="100%" border="0" cellspacing="1" cellpadding="0">
<tr>
<td><input type="radio" value="W" name="PayFreq" <%If ("W" = rsEMPupdPaydet1.Fields.Item("PayFreq").Value) Then Response.Write("checked='checked'") : Response.Write("")%> />
Weekly </td>
</tr>
<tr>
<td><input type="radio" value="2" name="PayFreq" <%If ("2" = rsEMPupdPaydet1.Fields.Item("PayFreq").Value) Then Response.Write("checked='checked'") : Response.Write("")%> />
2-Weekly </td>
</tr>
<tr>
<td><input type="radio" value="4" name="PayFreq" <%If ("4" = rsEMPupdPaydet1.Fields.Item("PayFreq").Value) Then Response.Write("checked='checked'") : Response.Write("")%> />
4-Weekly </td>
</tr>
<tr>
<td><input type="radio" value="M" name="PayFreq" <%If ("M" = rsEMPupdPaydet1.Fields.Item("PayFreq").Value) Then Response.Write("checked='checked'") : Response.Write("")%> />
Monthly </td>
</tr>
</table></td>
<td align="left" valign="top"><table width="100%" border="0" cellspacing="1" cellpadding="0">
<tr>
<td><input type="radio" value="H" name="PayMeth" <%If ("H" = rsEMPupdPaydet1.Fields.Item("PayMeth").Value) Then Response.Write("checked='checked'") : Response.Write("")%> />
Hourly </td>
</tr>
<tr>
<td><input type="radio" value="W" name="PayMeth" <%If ("W" = rsEMPupdPaydet1.Fields.Item("PayMeth").Value) Then Response.Write("checked='checked'") : Response.Write("")%> />
Weekly </td>
</tr>
<tr>
<td><input type="radio" value="A" name="PayMeth" <%If ("A" = rsEMPupdPaydet1.Fields.Item("PayMeth").Value) Then Response.Write("checked='checked'") : Response.Write("")%> />
Annual </td>
</tr>
</table></td>
<td align="left" valign="top"><table width="100%" border="0" cellspacing="1" cellpadding="0">
<tr valign="baseline">
<td nowrap="nowrap" align="right">Pay Rate:</td>
<td><input name="PayRate" type="text" value="<%=(rsEMPupdPaydet1.Fields.Item("PayRate").Value)%>" size="8" maxlength="6" /></td>
</tr>
<tr valign="baseline">
<td nowrap="nowrap" align="right">Hours per week:</td>
<td><input name="StdHours" type="text" value="<%=(rsEMPupdPaydet1.Fields.Item("StdHours").Value)%>" size="8" maxlength="6" /></td>
</tr>
</table></td>
</tr>
<tr class="form_subhead">
<td colspan="2" align="left" valign="top">Tax Details </td>
<td align="left" valign="top">N.I.Details</td>
</tr>
<tr>
<td colspan="2" align="left" valign="top"><table width="100%" border="0" cellspacing="1" cellpadding="0">
<tr valign="baseline">
<td nowrap="nowrap" align="right">Tax Code:</td>
<td><input name="TaxCode2" type="text" value="<%=(rsEMPupdPaydet1.Fields.Item("TaxCode").Value)%>" size="8" maxlength="6" /></td>
</tr>
</table></td>
<td align="left" valign="top"><table width="100%" border="0" cellspacing="1" cellpadding="0">
<tr valign="baseline">
<td nowrap="nowrap" align="right">N.I. Number:</td>
<td><input name="NiNo" type="text" value="<%=(rsEMPupdPaydet1.Fields.Item("NiNo").Value)%>" size="10" maxlength="9" /></td>
</tr>
</table></td>
</tr>
<tr>
<td align="right" valign="top"> </td>
<td align="right" valign="top"><input name="btnBack" type="button" id="btnBack" value="Back" onclick="history.back()" /></td>
<td align="left" valign="top"><input name="btnNext" type="submit" id="btnNext" value="Next" /></td>
</tr>
</table>
<p><input type="hidden" name="MM_update" value="form1">
<input type="hidden" name="MM_recordId" value="<%= rsEMPupdPaydet1.Fields.Item("EmpNo").Value %>">
</p>
</form>
<!-- InstanceEndEditable --></td>
<td><div align="right"><img src="gfx/layout3_r3_c2.gif" alt="" name="layout3_r3_c2" width="36" height="52" border="0" align="bottom" id="layout3_r3_c2" /></div></td>
<td valign="bottom" background="gfx/layout3_r3_c3.gif"> </td>
<td><div align="left"><img src="gfx/layout3_r3_c4.gif" alt="" name="layout3_r3_c4" width="24" height="52" border="0" align="bottom" id="layout3_r3_c4" /></div></td>
<td><img src="gfx/spacer.gif" width="1" height="52" border="0" alt="" /></td>
</tr>
<tr><!-- row 4 -->
<td background="gfx/layout3_r4_c2.gif"> </td>
<td align="left" valign="top"><!-- InstanceBeginEditable name="EditTips" -->Employee Number: <%= Session("EmpNumber") %><!-- InstanceEndEditable --></td>
<td background="gfx/layout3_r4_c4.gif"> </td>
<td><img src="gfx/spacer.gif" width="1" height="380" border="0" alt="" /></td>
</tr>
<tr><!-- row 5 -->
<td><div align="right"><img src="gfx/layout3_r5_c2.gif" alt="" name="layout3_r5_c2" width="36" height="36" border="0" align="top" id="layout3_r5_c2" /></div></td>
<td valign="top" background="gfx/layout3_r5_c3.gif"> </td>
<td><div align="left"><img src="gfx/layout3_r5_c4.gif" alt="" name="layout3_r5_c4" width="24" height="36" border="0" align="top" id="layout3_r5_c4" /></div></td>
<td><img src="gfx/spacer.gif" width="1" height="36" border="0" alt="" /></td>
</tr>
<tr><!-- row 6 -->
<td colspan="4" valign="top"><p class="small" style="margin:0px">
<script language="JavaScript1.2" src="script/date.js" type="text/javascript"></script>
</p></td>
<td><img src="gfx/spacer.gif" width="1" height="24" border="0" alt="" /></td>
</tr>
<!-- This table was automatically created with Macromedia Fireworks -->
<!-- http://www.macromedia.com -->
</table>
<!--========================= STOP COPYING THE HTML HERE =========================-->
</body>
<!-- InstanceEnd --></html>
<%
rsEMPupdPaydet1.Close()
Set rsEMPupdPaydet1 = Nothing
%>
0
Comment
Question by:matthewdacruz
• 2
• 2
7 Comments
LVL 13
Expert Comment
by:jrram
ID: 16903948
A lot of code here... can you identify line 40?
0
LVL 13
Expert Comment
by:jrram
ID: 16904015
Ok, I think it has something to do with the paramters section of your query:
Set MM_editCmd = Server.CreateObject ("ADODB.Command")
MM_editCmd.ActiveConnection = MM_HRDB_STRING
MM_editCmd.CommandText = "UPDATE EMP SET PayFreq = ?, PayMeth = ?, PayRate = ?, StdHours = ?, NiNo = ? WHERE EmpNo = ?"
MM_editCmd.Prepared = true
MM_editCmd.Parameters.Append MM_editCmd.CreateParameter("param1", 202, 1, -1, Request.Form("PayFreq")) ' adVarWChar
MM_editCmd.Parameters.Append MM_editCmd.CreateParameter("param2", 202, 1, -1, Request.Form("PayMeth")) ' adVarWChar
MM_editCmd.Parameters.Append MM_editCmd.CreateParameter("param3", 5, 1, 6, MM_IIF(Request.Form("PayRate"), Request.Form("PayRate"), null)) ' adDouble
MM_editCmd.Parameters.Append MM_editCmd.CreateParameter("param4", 5, 1, 6, MM_IIF(Request.Form("StdHours"), Request.Form("StdHours"), null)) ' adDouble
MM_editCmd.Parameters.Append MM_editCmd.CreateParameter("param5", 202, 1, 9, Request.Form("NiNo")) ' adVarWChar
MM_editCmd.Parameters.Append MM_editCmd.CreateParameter("param6", 5, 1, -1, MM_IIF(Request.Form("MM_recordId"), Request.Form("MM_recordId"), null)) ' adDouble
MM_editCmd.Execute
MM_editCmd.ActiveConnection.Close
0
LVL 46
Expert Comment
by:fritz_the_blank
ID: 16905730
When you have numerics, you have to specify more parameters. Here is an example:
Set prmNumNumberNeeded = objCommand.CreateParameter
With prmNumNumberNeeded
.Name="@numNumberNeeded"
.Direction = adParamInput
.NumericScale = 2
.Precision = 10
.Size = 19
.Type = adNumeric
.Value = Request.Form("numNumberNeeded")
End With
FtB
0
Author Comment
by:matthewdacruz
ID: 16910401
Hi jrram
Line 40 is the MM_editCmd.Execute statement in the parameters section.
Hi Fritz the blank
I'm afraid ASP is far from my first language and I am not entirely sure how your code example fits in with my code. Can you please elaborate.
0
LVL 46
Accepted Solution
by:
fritz_the_blank earned 500 total points
ID: 16911536
Sure. If your parameter is an integer, then your parameter looks pretty simple:
MM_editCmd.Parameters.Append MM_editCmd.CreateParameter.CreateParameter("@intsomeIntegerField",adInteger,adParamInput ,,varSomeIntegerValue)
However, if your value is a non-integer numeric, then you need to specify further parameters like this:
Set prmNumNumberNeeded = MM_editCmd.Parameters.CreateParameter
With prmNumNumberNeeded
.Name="@numNumberNeeded"
.Direction = adParamInput
.NumericScale = 2
.Precision = 10
.Size = 19
.Type = adNumeric
.Value = Request.Form("numNumberNeeded")
End With
MM_editCmd.Parameters.Append prmNumGoalPerformanceRating
So, the first step is to look at your table and determine the data type of your fields involved in this operation, and then supply the necessary parameter details for those fields that are not integer.
FtB
0
Featured Post
Free Tool: IP Lookup
Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.
One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.
Question has a verified solution.
If you are experiencing a similar issue, please ask a related question
Suggested Solutions
Hello, all! I just recently started using Microsoft's IIS 7.5 within Windows 7, as I just downloaded and installed the 90 day trial of Windows 7. (Got to love Microsoft for allowing 90 days) The main reason for downloading and testing Windows 7 is t…
I was asked about the differences between classic ASP and ASP.NET, so let me put them down here, for reference: Let's make the introductions... Classic ASP was launched by Microsoft in 1998 and dynamically generate web pages upon user interact…
Finds all prime numbers in a range requested and places them in a public primes() array. I've demostrated a template size of 30 (2 * 3 * 5) but larger templates can be built such 210 (2 * 3 * 5 * 7) or 2310 (2 * 3 * 5 * 7 * 11). The larger templa…
I've attached the XLSM Excel spreadsheet I used in the video and also text files containing the macros used below. https://filedb.experts-exchange.com/incoming/2017/03_w12/1151775/Permutations.txt https://filedb.experts-exchange.com/incoming/201…
808 members asked questions and received personalized solutions in the past 7 days.
Join the community of 500,000 technology professionals and ask your questions.
Join & Ask a Question
|
__label__pos
| 0.863853 |
Contoh Soal SBMPTN Logaritma yang Bikin Pintar dan Percaya Diri
Di era globalisasi ini, tantangan pendidikan semakin kompleks, terutama dalam persiapan menghadapi ujian seleksi seperti SBMPTN (Seleksi Bersama Masuk Perguruan Tinggi Negeri). Salah satu mata pelajaran yang sering menjadi batu ujian adalah logaritma. Pemahaman mendalam terhadap konsep ini menjadi kunci keberhasilan dalam menjawab soal ujian. Dalam artikel ini, kita akan menjelajahi contoh soal SBMPTN logaritma sebagai sarana untuk memperdalam pemahaman terhadap materi ini.
Mengurai Konsep Logaritma: Dasar Pemahaman
Sebelum memasuki contoh soal SBMPTN logaritma, kita perlu memahami dasar konsep logaritma itu sendiri. Logaritma adalah kebalikan dari operasi eksponen. Artinya, jika =, maka logaritma basis dari adalah , atau dapat dituliskan sebagai log=. Konsep ini dapat diilustrasikan dengan menyederhanakan ekspresi seperti log28 yang berarti kita mencari eksponen yang, jika pangkatkan 2, akan menghasilkan 8. Dalam hal ini, jawabannya adalah 3 karena 23=8.
Signifikansi Logaritma dalam Pembelajaran
Pentingnya logaritma tidak hanya terletak pada keterampilan manipulasi matematika semata, melainkan juga pada aplikasinya dalam berbagai bidang ilmu. Dalam fisika, logaritma digunakan untuk menggambarkan perubahan eksponensial, sedangkan dalam ekonomi, logaritma dapat merinci pertumbuhan dan penurunan dalam bentuk yang lebih terukur. Oleh karena itu, memahami logaritma tidak hanya membantu siswa dalam ujian, tetapi juga membuka pintu pemahaman terhadap berbagai konsep di luar dunia matematika.
Strategi Penyelesaian Soal Logaritma pada SBMPTN
Memahami strategi penyelesaian soal logaritma dapat menjadi kunci sukses dalam menghadapi ujian SBMPTN. Salah satu contoh soal yang sering muncul adalah menyelesaikan persamaan logaritma. Sebagai contoh, pertimbangkan persamaan log3(2−1)+log34=2. Untuk menyelesaikan ini, kita dapat menggabungkan logaritma dengan hukum logaritma, dan pada akhirnya, kita akan mendapatkan =2. Penting untuk memahami langkah-langkah seperti ini untuk menjawab dengan cepat dan akurat pada ujian.
Mendekati Contoh Soal SBMPTN Logaritma: Menyelesaikan Tantangan Matematis
Untuk membantu calon mahasiswa dalam memahami logaritma, mari kita dekati beberapa contoh soal SBMPTN yang menekankan pada topik ini. Contoh soal ini tidak hanya mengevaluasi pengetahuan mendasar, tetapi juga kemampuan kritis dan pemecahan masalah. Pemahaman yang mendalam terhadap logaritma akan membantu menjawab soal-soal ini dengan lebih percaya diri.
Contoh Soal SBMPTN Logaritma dan Solusinya
Mari kita terapkan konsep yang telah kita pelajari dengan melihat beberapa soal SBMPTN logaritma dan solusinya:
Contoh Soal 1:
log2(3+1)+log2(−2)=3
Solusi:
Langkah pertama adalah menggabungkan logaritma dengan menggunakan hukum logaritma. Sehingga kita dapat menuliskan persamaan di atas sebagai:
log2(3+1)(−2)=3
Kemudian, kita konversikan persamaan logaritma menjadi bentuk eksponensial:
23=(+1)(−2)
8=32−5−2
Selanjutnya, kita faktorkan persamaan kuadrat di atas:
(3+1)(−2)=0
Maka, kita dapatkan dua solusi:
3+1=0→=−13
−2=0→=2
Namun, karena logaritma hanya dapat diaplikasikan pada bilangan positif, kita hanya mempertimbangkan solusi =2.
Contoh Soal 2:
log5+log5(+4)=2
Solusi:
Gabungkan logaritma dengan hukum logaritma:
log5(+4)=2
Konversikan menjadi bentuk eksponensial:
52=(+4)
25=2+4
Faktorkan persamaan kuadrat:
(+1)(+4)=0
Diperoleh dua solusi:
+1=0→=−1
+4=0→=−4
Namun, karena logaritma hanya dapat diaplikasikan pada bilangan positif, kita tidak mempertimbangkan solusi negatif. Jadi, solusi yang diterima adalah =−1.
Pentingnya Latihan dan Pemahaman Konsep
Dalam menghadapi soal SBMPTN logaritma, latihan dan pemahaman konsep sangat penting. Tidak hanya cukup mengetahui langkah-langkah penyelesaian, tetapi juga memahami alasan di balik setiap langkah. Seiring dengan memahami konsep dasar, latihan secara berkala dengan beragam soal dapat membantu meningkatkan kemampuan analisis dan pemecahan masalah siswa.
Kesimpulan
Dalam persiapan menghadapi ujian SBMPTN, pemahaman yang mendalam terhadap konsep logaritma sangat penting. Artikel ini telah menguraikan dasar-dasar logaritma, strategi penyelesaian soal, serta memberikan soal SBMPTN logaritma beserta solusinya. Pentingnya latihan dan pemahaman konsep tidak hanya mempersiapkan siswa untuk ujian, tetapi juga membantu mereka mengembangkan keterampilan analisis dan pemecahan masalah yang berguna dalam berbagai bidang ilmu. Dengan demikian, melalui pemahaman yang kuat terhadap logaritma, siswa dapat menghadapi ujian dengan percaya diri dan sukses.*
|
__label__pos
| 0.995328 |
pumping lemma
Definition from Wiktionary, the free dictionary
Jump to: navigation, search
English[edit]
Noun[edit]
pumping lemma (plural pumping lemmas or pumping lemmata)
Wikipedia has an article on:
Wikipedia
1. (computer science) A lemma which states that for a language to be a member of a language class any sufficiently long string in the language contains a section that can be removed or repeated any number of times with the resulting string remaining in the language, used to determine if a particular language is in a given language class (e.g. not regular).
• 1997, Dexter Kozen, Automata and computability (page 148)
There is a pumping lemma for CFLs similar to the one for regular sets. It can be used in the same way to show that certain sets are not context-free.
• 2002, Alejandro Maass, Servet Martínez, Jaime San Martín, Dynamics and randomness (page 174)
In the literature one finds many pumping lemmas which describe the ability to repeat (pump) certain words repeatedly in some languages, under different circumstances.
• 2010, Marco Kuhlmann, Dependency Structures and Lexicalized Grammars: An Algebraic Approach (page 107)
String-language hierarchies are usually proven using formalism-specific pumping lemmata.
Translations[edit]
See also[edit]
|
__label__pos
| 0.727599 |
Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
PerlMonks
Comment on
( #3333=superdoc: print w/ replies, xml ) Need Help??
Closure on Closures
Before we get into this tutorial we need to define what a closure is. The Camel (3rd edition) states that a closure is
when you define an anonymous function in a particular lexical scope at any particular moment
However, I believe this isn't entirely accurate as a closure in perl can be any subroutine referring to lexical variables in the surrounding lexical scopes.[0]
Now with that (simple?) definition out of the way, we can get on with the show!
Before we get started ...
For one to truely understand closures a solid understanding of the principles of lexical scoping is needed, as closures are implemented through the means of lexical scoping interacting with subroutines. For an introduction to lexical scoping in perl see Lexical scoping like a fox, and once you're done with that, head on back.
Right, are we all here now? Bueller ... Bueller .. Bueller? Good.
Now that we have our basic elements, let's weave them together with a stitch of explanation and a thread of code.
Hanging around
Now as we all know, lexical variables are only active for the length of the surrounding lexical scope, but can be kept around in an indirect manner if something else references them e.g
1: sub DESTROY { print "stick a fork in '$_[0]' it's done\n" } 2: 3: my $foo = bless []; 4: { 5: my $bar = bless {}; 6: ## keep $bar around 7: push @$foo => \$bar; 8: 9: print "in \$bar's [$bar] lexical scope\n"; 10: } 11: 12: print "we've left \$bar's lexical scope\n"; __output__ in $bar's [main=HASH(0x80fbbf0)] lexical scope we've left $bar's lexical scope stick a fork in 'main=ARRAY(0x80fbb0c)' it's done stick a fork in 'main=HASH(0x80fbbf0)' it's done
The above example illustrates that $bar isn't cleaned up until $foo, which references it, leaves the surrounding lexical scope (the file-level scope in this case). So from that we can see lexical variables only stick around for the length of the surrounding scope or until they're no longer referenced.
But what if we were to re-enter a scope where a variable is still visible, but the scope has already exited - will the variable still exist?
1: { 2: my $foo = "a string"; 3: INNER: { 4: print "\$foo: [$foo]\n"; 5: } 6: } 7: goto INNER unless $i++; __output__ $foo: [a string] $foo: []
As we can see the answer is categorically 'No'. In retrospect this is quite obvious as $foo has gone out of scope and there is no longer a reference to it.
A bit of closure
However, the last example just used a simple bareblock, now let's try it with a subroutine as the inner block
1: { 2: my $foo = "a string"; 3: sub inner { 4: print "\$foo: [$foo]\n"; 5: } 6: } 7: inner(); 8: inner(); __output__ $foo: [a string] $foo: [a string]
"Hold on there cowboy - $foo has already gone out of scope at the time of the first call to inner() let alone the second, what's going on there?!?", or so one might say. Now hold your horses, there is a very good reason for this behaviour - the subroutine in the example is a closure. "Ok, so it's a closure, but why?", would be a good question at this point. The reason is that subroutines in perl have what's called a scratchpad which holds references to any lexical variables referred to within the subroutine. This means that you can directly access lexical variables within subroutines even though the given variables' scope has exited.
Hmmm, that was quite a lot of raw info, so let's break it down somewhat. Firstly subroutines can hold onto variables from higher lexical scopes. Here's a neat little counter example (not counter-example ;)
1: { 2: my $cnt = 5; 3: sub counter { 4: return $cnt--; 5: } 6: } 7: 8: while(my $i = counter()) { 9: print "$i\n"; 10: } 11: print "BOOM!\n"; __output__ 5 4 3 2 1 BOOM!
While not immediately useful, the above example does demonstrate a subroutine counter() (line 3) holding onto a variable $cnt (line 2) after it has gone out of scope. Because of this behaviour of capturing lexical state the counter() subroutine acts as a closure.
Now if we look at the above example a little closer we might notice that it looks like the beginnings of a basic iterator. If we just tweak counter() and have it return an anonymous sub we'll have ourselves a very simple iterator
1: sub counter { 2: my $cnt = shift; 3: return sub { $cnt-- }; 4: } 5: 6: my $cd = counter(5); 7: while(my $i = $cd->()) { 8: print "$i\n"; 9: } 10: 11: print "BOOM!\n"; __output__ 5 4 3 2 1 BOOM!
Now instead of counter() being the closure we return an anonymous subroutine (line 3) which becomes a closure as it holds onto $cnt (line 2). Every time the newly created closure is executed the $cnt passed into counter() is returned and decremented (this post-return modification behaviour is due to the nature of the post-decrement operator, not the closure).
So if we further apply the concepts of closures we can write ourselves a very basic directory iterator
1: use IO::Dir; 2: 3: sub dir_iter { 4: my $dir = IO::Dir->new(shift) or die("ack: $!"); 5: 6: return sub { 7: my $fl = $dir->read(); 8: $dir->rewind() unless defined $fl; 9: return $fl; 10: }; 11: } 12: 13: my $di = dir_iter( "." ); 14: while(defined(my $f = $di->())) { 15: print "$f\n"; 16: } __output__ . .. .closuretut.html.swp closuretut.html example5.pl example6.pl example2.pl example1.pl example3.pl example4.pl example7.pl
In the code above dir_iter() (line 3) is returning an anonymous subroutine (line 6) which is holding $dir (line 4) from a higher scope and therefore acts as a closure. So we've created a very basic directory iterator using a simple closure and a little bit of help from IO::Dir.
Wrapping it up
This method of creating closures using anonymous subroutines can be very powerful[1]. With the help of Richard Clamp's marvellous File::Find::Rule we can build ourselves a handy little grep like tool for XML files
1: use strict; 2: use warnings; 3: 4: use XML::Simple; 5: use Getopt::Std; 6: use File::Basename; 7: use File::Find::Rule; 8: use Data::Dumper; 9: 10: $::PROGRAM = basename $0; 11: 12: getopts('n:t:hr', my $opts = {}); 13: 14: usage() if $opts->{h} or @ARGV == 0; 15: 16: my @dirs = $opts->{r} ? @ARGV : map dirname($_), @ARGV; 17: my @files = $opts->{r} ? '*.xml' : map basename($_), @ARGV; 18: my $callback = gensub($opts); 19: 20: my @found = find( 21: file => 22: name => \@files, 23: ## handy callback which wraps around the callback created above 24: exec => sub { $callback->( XMLin $_[-1] ) }, 25: in => [ @dirs ] 26: ); 27: 28: print "$::PROGRAM: no files matched the search criteria\n" and exi +t(0) 29: if @found == 0; 30: 31: print "$::PROGRAM: the following files matched the search criteria +\n", 32: map "\t$_\n", @found; 33: 34: exit(0); 35: 36: sub usage { 37: print "Usage: $::PROGRAM -t TEXT [-n NODE -h -r] FILES\n"; 38: exit(0); 39: } 40: 41: sub gensub { 42: my $opts = shift; 43: 44: ## basic matcher wraps around the program options 45: return sub { Dumper($_[0]) =~ /\Q$opts->{t}/sm } 46: unless exists $opts->{n}; 47: 48: ## node based matcher wraps around options and itself! 49: my $self; $self = sub { 50: my($tree, $seennode) = @_; 51: 52: for(keys %$tree) { 53: $seennode = 1 if $_ eq $opts->{n}; 54: 55: if( ref $tree->{$_} eq 'HASH') { 56: return $self->($tree->{$_}, $seennode); 57: } elsif( ref $tree->{$_} eq 'ARRAY') { 58: return !!grep $self->($_, $seennode), @{ $tree->{$_} }; 59: } else { 60: next unless $seennode; 61: return !!1 62: if $tree->{$_} =~ /\Q$opts->{t}/; 63: } 64: } 65: return; 66: }; 67: 68: return $self; 69: }
Disclaimer: the above isn't thoroughly tested and isn't nearly perfect so think twice before using in the real world
The code above contains 3 simple examples of closures using anonymous subroutines (in this case acting as callbacks). The first closure can be found on in the exec parameter (line 24) of the find call. This is wrapping around the $callback variable generated by the gensub() function. Then within the gensub() (line 41) there are 2 closures which wrap around the $opts lexical, the second of which also wraps around $self which is a reference to the callback which is returned.
Altogether now
So let's bring it altogether now - a closure is a subroutine which wraps around lexical variables that it references from the surrounding lexical scope which subsequently means that the lexical variables that are referenced are not garbage collected when their immediate scope is exited.
There ya go, closure on closures! Hopefully this tutorial has conveyed the meaning and purpose of closures in perl and hasn't been too confounding along the way.
Thanks to virtualsue, castaway, Corion, xmath, demerphq, Petruchio, tye for help during the construction of this tutorial
[0] see. chip's Re: Toggling between two values for a more technical definition (and discussion) of closures within perl
[1] see. tilly's Re (tilly) 9: Why are closures cool?, on the pitfalls of nested package level subroutines vs. anonymous subroutines when dealing with closures
_________
broquaint
Disclaimer: Not everyone will agree with the terminology (I imagine) so as long as you don't find the descriptions wildly off the mark or generally misleading then they're likely to stay as they are.
Update - revised the second and third sections by dropping any references to 'reference counting'
In reply to Closure on Closures by broquaint
Title:
Use: <p> text here (a paragraph) </p>
and: <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":
• Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
• Read Where should I post X? if you're not absolutely sure you're posting in the right place.
• Please read these before you post! —
• Posts may use any of the Perl Monks Approved HTML tags:
a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
• You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
For: Use:
& &
< <
> >
[ [
] ]
• Link using PerlMonks shortcuts! What shortcuts can I use for linking?
• See Writeup Formatting Tips and other pages linked from there for more info.
• Log In?
Username:
Password:
What's my password?
Create A New User
Chatterbox?
and the web crawler heard nothing...
How do I use this? | Other CB clients
Other Users?
Others rifling through the Monastery: (9)
As of 2015-10-09 14:44 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
Does Humor Belong in Programming?
Results (242 votes), past polls
|
__label__pos
| 0.94376 |
Have a question? Connect with the community at the TensorFlow Forum Visit Forum
text.find_source_offsets
Maps the input post-normalized string offsets to pre-normalized offsets.
Returns the source (i.e. pre-normalized) string offsets mapped from the input post-normalized string offsets using the input offsets_map, which is an output from the normalize_utf8_with_offsets_map op. offsets_map can be indexed or sliced along with the input_offsets.
Examples:
# input: <string>[num_strings]
post_normalized_str, offsets_map = normalize_utf8_with_offsets_map(
["株式会社", "KADOKAWA"])
# input: <variant>[num_strings], <int64>[num_strings, num_offsets]
find_source_offsets(offsets_map, [[0, 1, 2], [0, 1, 2]])
# output: <int64>[num_strings, num_offsets]
<tf.Tensor: shape=(2, 3), dtype=int64, numpy=array([[0, 1, 2], [0, 3, 6]])>
# Offsets map can be indexed.
find_source_offsets(offsets_map[1], [[0, 1, 2]])
<tf.Tensor: shape=(1, 3), dtype=int64, numpy=array([[0, 3, 6]])>
offsets_map A Tensor or RaggedTensor of type variant, used to map the post-normalized string offsets to pre-normalized string offsets. offsets_map is an output from normalize_utf8_with_offsets_map function.
input_offsets A Tensor or RaggedTensor of type int64 representing the the post-normalized string offsets,
name The name for this op (optional).
results A Tensor or RaggedTensor of type int64, with pre-normalized string offsets.
|
__label__pos
| 0.98253 |
[{"label":"Latest (v1.0)","version":"latest"}]
nsx-vmc-policy
SIMacLearningCounters
Properties
integer as int64
mac_not_learned_packets_allowed Optional
The number of packets with unknown source MAC address that are dispatched without learning the source MAC address. Applicable only when the MAC limit is reached and MAC Limit policy is MAC_LEARNING_LIMIT_POLICY_ALLOW.
integer as int64
mac_not_learned_packets_dropped Optional
The number of packets with unknown source MAC address that are dropped without learning the source MAC address. Applicable only when the MAC limit is reached and MAC Limit policy is MAC_LEARNING_LIMIT_POLICY_DROP.
integer as int64
macs_learned Optional
Number of MACs learned
JSON Example
{
"mac_not_learned_packets_allowed": 0,
"mac_not_learned_packets_dropped": 0,
"macs_learned": 0
}
Vendor Extensions
This class contains the following vendor extensions defined in the spec:
x-vmw-nsx-module: ServiceInsertionVMDeployment
[{"label":"Latest (v1.0)","version":"latest"}]
nsx-vmc-policy
Property Of
InlineSIAggregatedDataCounterEx1
Feedback
Was this page helpful?
|
__label__pos
| 0.767438 |
Rust 编程视频教程对应讲解内容-枚举类型与匹配
视频地址
头条地址:https://www.ixigua.com/i676544267458235648...
B站地址:https://www.bilibili.com/video/av78062009?...
网易云课堂地址:https://study.163.com/course/introduction....
讲解内容
1、类似于c语言的方式
enum IpAddrKind {
V4,
V6,
}
struct IpAddr {
kind: IpAddrKind,
address: String,
}
let home = IpAddr {
kind: IpAddrKind::V4,
address: String::from("127.0.0.1"),
};
let loopback = IpAddr {
kind: IpAddrKind::V6,
address: String::from("::1"),
};
2、rust提倡的方式
enum IpAddr {
V4(String),
V6(String),
}
let home = IpAddr::V4(String::from("127.0.0.1"));
let loopback = IpAddr::V6(String::from("::1"));
3、可以是不同类型
enum IpAddr {
V4(u8, u8, u8, u8),
V6(String),
}
let home = IpAddr::V4(127, 0, 0, 1);
let loopback = IpAddr::V6(String::from("::1"));
4、经典用法
enum Message {
Quit,
Move { x: i32, y: i32 },
Write(String),
ChangeColor(i32, i32, i32),
}
解释:
• Quit 没有关联任何数据。
• Move 包含一个匿名结构体。
• Write 包含单独一个 String。
• ChangeColor 包含三个 i32。
等同于(用结构体的话):
struct QuitMessage; // 类单元结构体
struct MoveMessage {
x: i32,
y: i32,
}
struct WriteMessage(String); // 元组结构体
struct ChangeColorMessage(i32, i32, i32); // 元组结构体
5、枚举类型的方法,以及match
enum Message<> {
Quit,
Move { x: i32, y: i32 },
Write(String),
ChangColor(i32, i32, i32),
}
impl Message{
fn prin(&self) {
match *self {
Message::Quit => println!("Quit"),
Message::Move{x, y} => println!("Move x = {}, y = {}", x, y),
Message::ChangColor(a, b, c) => println!("a = {}, b = {}, c = {}", a, b, c),
//Message::Write(&s) => println!("Write s = {}", s.to_string())
_ => println!("string!")
}
}
}
fn main() {
let quit = Message::Quit;
quit.prin();
let mov = Message::Move{x: 10, y: 20};
mov.prin();
let wri = Message::Write(String::from("Write some thing!"));
wri.prin();
let change = Message::ChangColor(1, 2, 3);
change.prin();
println!("Hello, world!");
}
本作品采用《CC 协议》,转载必须注明作者和本文链接
令狐一冲
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!
请勿发布不友善或者负能量的内容。与人为善,比聪明更重要!
|
__label__pos
| 0.999158 |
SonarCloud | Advanced setup | CI-based analysis | Github Actions for SonarCloud
Was this page helpful?
On this page
Start FreeLog in
Analyze your repository with GitHub Actions
To configure an analysis of your project using GitHub Actions, you should follow the in-product tutorial when creating a new project. When it's time to Choose your Analysis Method during setup, simply select With GitHub Actions. You can also access the tutorials for an existing project by going to Your Project > Administration > Analysis Method.
The tutorial will walk you through the precise steps to set up the analysis but the basic steps are these:
1. Define the SONAR_TOKEN environment variable in your repository by setting up a GitHub Secret. The SONAR_TOKEN identifies and authenticates you to SonarCloud. The tutorial will provide the precise value for your specific account.
2. Set the essential analysis parameters, sonar.projectKeysonar.organization, and sonar.host.url. The tutorial will be populated with the correct values for your specific account. These parameters are set differently depending on your project type:
• In the pom.xml for Java Maven projects.
• In the build.gradle file for Java Gradle projects.
• In the SonarScanner command line for .NET projects.
• In the sonar-project.properties file for other types of projects. You can also add additional analysis parameters to further specify your analysis details (See Analysis Parameters).
3. Create the .github/workflows/build.yml file that defines the steps of your build. In addition to the usual steps that build your project, you need to invoke the SonarScanner to perform the analysis of your code. This is done differently depending on your project type:
• A Maven plugin for Java Maven projects.
• A Gradle plugin for Java Gradle projects.
• A dedicated .NET scanner for .NET projects.
• The SonarCloud GitHub Action for C and C++.
• The SonarCloud GitHub Action for other projects. The tutorial will provide the specific details for your project type.
The example below shows how you could set up a yml file for a single project.
GitHub Actions for Sonarcloud
The workflow, usually declared in .github/workflows/build.yml, looks something like this:
name: My Test Single Project
on:
push:
branches:
- main
pull_request:
types: [opened, synchronize, reopened]
jobs:
sonarcloud:
name: SonarCloud
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 0
- name: SonarCloud Scan
uses: SonarSource/sonarcloud-github-action@master
env:
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
Users have reported that when working with GitHub Actions reusable workflows, your SONAR_TOKEN is not intrinsically passed to the reusable workflow. Even though your SONAR_TOKEN is defined in the source repository, GitHub Actions will output the SONAR_TOKEN value with asterisks (which make it look like it is working as expected), when in fact it is not reusing the value.
When setting up your GitHub reusable workflow, we recommend using the GitHub feature secret: inherit to completely remove the intrinsic sending of your SONAR_TOKEN.
GitHub Actions for C and C++
This GitHub Action installs the latest versions of sonar-scanner and build-wrapperrequired for C/C++ SonarCloud analysis making the workflow simpler.
See the GitHub Action readme for more information.
Analyzing Monorepo Projects: Build Configuration
The example below shows how you could set up a yml file for multiple projects in a monorepo. If you want to analyze a monorepo that contains more than one project ensure that you specify the paths to each sub-project for analysis in your build file.
To ensure that your monorepo works as expected, you need to build each project in the monorepo separately with a unique project key for each one.
GitHub Actions .yml file
name: My Test Monorepo Project
on:
push:
branches:
- main
paths:
- 'lambdas/test/**'
pull_request:
types: [opened, synchronize, reopened]
jobs:
sonarcloudScan1:
name: SonarCloudScan1
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 0
- name: SonarCloud Scan
uses: SonarSource/sonarcloud-github-action@master
env:
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
with:
projectBaseDir: repo1/
sonarcloudScan2:
name: SonarCloudScan2
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 0
- name: SonarCloud Scan
uses: SonarSource/sonarcloud-github-action@master
env:
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
with:
projectBaseDir: repo2/
© 2008-2024 SonarSource SA. All rights reserved. SONAR, SONARSOURCE, SONARLINT, SONARQUBE, SONARCLOUD, and CLEAN AS YOU CODE are trademarks of SonarSource SA.
Creative Commons License
|
__label__pos
| 0.834541 |
Create a gist now
Instantly share code, notes, and snippets.
What would you like to do?
This is a very basic representation of internationalized documentation support in ruby.
# This is a very basic representation of internationalized documentation
# support in ruby.
#
# To use this demo try the following commands:
#
# ruby rdoc_i18n.rb Class#allocate
# ruby rdoc_i18n.rb -h Class#allocate > output.html
# # then open output.html in your browser
# ruby rdoc_i18n.rb --lang ja Class#allocate
#
# For more resources, and ideas, see:
#
# https://github.com/svenfuchs/i18n
# http://guides.rubyonrails.org/i18n.html
#
require 'rdoc'
require 'psych'
require 'optparse'
require 'ostruct'
doc = Psych.load(DATA.read)
options = OpenStruct.new
# Defaults
options.html = false
options.lang = "en"
OptionParser.new do |opts|
opts.on("-h", "--html", "Output HTML") { options.html = true }
opts.on("--lang LANGUAGE", "Language to use for translation of documents") do |v|
options.lang = v
end
end.parse!
query = ARGV.first.dup
tokens = RDoc::RubyLex.tokenize query, RDoc::Options.new
begin
if options.html
renderer = RDoc::Markup
formatter = RDoc::Markup::ToHtml.new(RDoc::Options.new, nil)
puts renderer.parse(doc[options.lang][tokens[0].text][tokens[1].text]).accept(formatter)
else
puts doc[options.lang][tokens[0].text][tokens[1].text]
end
rescue
raise "Nothing known about #{tokens[0].text}#{tokens[1].text}"
end
__END__
en:
"Class":
"#allocate": |
call-seq:
class.allocate() -> obj
Allocates space for a new object of <i>class</i>'s class and does not
call initialize on the new instance. The returned object must be an
instance of <i>class</i>.
klass = Class.new do
def initialize(*args)
@initialized = true
end
def initialized?
@initialized || false
end
end
klass.allocate.initialized? #=> false
"::new": |
call-seq:
Class.new(super_class=Object) -> a_class
Class.new(super_class=Object) { |mod| ... } -> a_class
Creates a new anonymous (unnamed) class with the given superclass
(or <code>Object</code> if no parameter is given). You can give a
class a name by assigning the class object to a constant.
If a block is given, it is passed the class object, and the block
is evaluated in the context of this class using
<code>class_eval</code>.
fred = Class.new do
def meth1
"hello"
end
def meth2
"bye"
end
end
a = fred.new #=> #<#<Class:0x100381890>:0x100376b98>
a.meth1 #=> "hello"
a.meth2 #=> "bye"
Assign the class to a constant (name starting uppercase) if you
want to treat it like a regular class.
ja:
"Class":
"#allocate": |
自身のインスタンスを生成して返します。生成したオブジェクトは 自身のインスタンスであること以外には何も特性を持ちません。
"::new": |
新しく名前の付いていない superclass のサブクラスを生成します。
名前のないクラスは、最初に名前を求める際に代入されている定数名を検 索し、見つかった定数名をクラス名とします。
p foo = Class.new # => #<Class:0x401b90f8>
p foo.name # => ""
Foo = foo # ここで p foo すれば "Foo" 固定
Bar = foo
p foo.name # => "Bar" ("Foo" になるか "Bar" になるかは不定)
ブロックが与えられた場合、生成したクラスを引数として クラスのコンテキストでブロックを実行します。以下のコードと同じです。
klass = Class.new(superclass)
klass.module_eval {|m| ... }
klass
この場合も生成したクラスを返します。 ブロックの実行は Class#initialize が行います。
[PARAM] superclass:
生成するクラスのスーパークラスを指定します。
例:
k = Class.new{|c|
def initialize
p "in initialize"
end
def hoge
p "hoge hoge hoge"
end
}
o = k.new #=> "in initialize"
o.hoge #=> "hoge hoge hoge"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
|
__label__pos
| 0.637021 |
Creating An Ammolet
This tutorial will use code and terms explained in passives, so it is advised to check that out before making an Ammolet.
First, you will need this class somewhere in your project :
using System;
using MonoMod.RuntimeDetour;
using System.Reflection;
using UnityEngine;
namespace YourNameSpace
{
class SpecialBlankModificationItem : BlankModificationItem
{
public static void InitHooks()
{
Hook hook = new Hook(
typeof(SilencerInstance).GetMethod("ProcessBlankModificationItemAdditionalEffects", BindingFlags.NonPublic | BindingFlags.Instance),
typeof(SpecialBlankModificationItem).GetMethod("BlankModificationHook")
);
}
public static void BlankModificationHook(Action<SilencerInstance, BlankModificationItem, Vector2, PlayerController> orig, SilencerInstance self, BlankModificationItem bmi, Vector2 centerPoint, PlayerController user)
{
orig(self, bmi, centerPoint, user);
if (bmi is SpecialBlankModificationItem)
{
(bmi as SpecialBlankModificationItem).OnBlank(self, centerPoint, user);
}
}
protected virtual void OnBlank(SilencerInstance silencerInstance, Vector2 centerPoint, PlayerController user)
{
}
}
}
Put this in your ETGModule class.
SpecialBlankModificationItem.InitHooks();
Then, you want to create a new item and make it inherit from SpecialBlankModificationItem. Then, you want to be using ItemAPI and UnityEngine.
using System;
using ItemAPI;
using UnityEngine;
namespace YourNameSpace
{
class YourClassName : SpecialBlankModificationItem
{
public static void Init()
{
//Same set up as passive items
//...
//you'll need this to make your ammolet give an aditionnal like vanilla ammolets
ItemBuilder.AddPassiveStatModifier(item, PlayerStats.StatType.AdditionalBlanksPerFloor, 1, StatModifier.ModifyMethod.ADDITIVE);
}
}
}
Finally, put a method OnBlank in your item class and put your effect inside it so it's triggered when the user create a blank effect with an item or a blank :
protected override void OnBlank(SilencerInstance silencerInstance, Vector2 centerPoint, PlayerController user)
{
//put your effect in here
//for example, make blanks deal no dmg
silencerInstance.ForceNoDamage = true;
}
[TODO]
Last updated
|
__label__pos
| 0.972561 |
Perimeter
From Wikipedia, the free encyclopedia
Jump to: navigation, search
For other uses, see Perimeter (disambiguation).
Perimeter is the distance around a two dimensional shape, or the measurement of the distance around something; the length of the boundary.
A perimeter is a path that surrounds a two-dimensional shape. The word comes from the Greek peri (around) and meter (measure). The term may be used either for the path or its length - it can be thought of as the length of the outline of a shape. The perimeter of a circle or ellipse is called its circumference.
Calculating the perimeter has considerable practical applications. The perimeter can be used to calculate the length of fence required to surround a yard or garden. The perimeter of a wheel (its circumference) describes how far it will roll in one revolution. Similarly, the amount of string wound around a spool is related to the spool's perimeter.
Formulae[edit]
shape formula variables
circle 2 \pi r = \pi d where r is the radius of the circle and d is the diameter.
triangle a + b + c\, where a, b and c are the lengths of the sides of the triangle.
square/rhombus 4a where a is the side length.
rectangle 2(l+w) where l is the length and w is the width.
equilateral polygon n \times a\, where n is the number of sides and a is the length of one of the sides.
regular polygon 2nb \sin\left(\frac{\pi}{n}\right) where n is the number of sides and b is the distance between center of the polygon and one of the vertices of the polygon.
general polygon a_1 + a_2 + a_3 + \cdots + a_n = \sum_{i=1}^n a_i where a_{i} is the length of the i-th (1st, 2nd, 3rd ... nth) side of an n-sided polygon.
The perimeter is the distance around a shape. Perimeters for more general shapes can be calculated as any path with \int_0^L \mathrm{d}s where L is the length of the path and ds is an infinitesimal line element. Both of these must be replaced with other algebraic forms in order to be solved: an advanced notion of perimeter, which includes hypersurfaces bounding volumes in n-dimensional Euclidean spaces can be found in the theory of Caccioppoli sets.
Polygons[edit]
Perimeter of a rectangle.
Polygons are fundamental to determining perimeters, not only because they are the simplest shapes but also because the perimeters of many shapes are calculated by approximating them with sequences of polygons tending to these shapes. The first mathematician known to have used this kind of reasoning is Archimedes, who approximated the perimeter of a circle by surrounding it with regular polygons.
The perimeter of a polygon equals the sum of the lengths of its edges. In particular, the perimeter of a rectangle which width is w and length \ell is equal to 2w + 2\ell.
An equilateral polygon is a polygon which has all sides of the same length (for example, a rhombus is a 4-sided equilateral polygon). To calculate the perimeter of an equilateral polygon, one must multiply the common length of the sides by the number of sides.
A regular polygon may be defined by the number of its sides and by its radius, that is to say, the constant distance between its centre and each of its vertices. One can calculate the length of its sides using trigonometry. If R is a regular polygon's radius and n is the number of its sides, then its perimeter is
2nR \sin\left(\frac{180^{\circ}}{n}\right).
A splitter of a triangle is a cevian (a segment from a vertex to the opposite side) that divides the perimeter into two equal lengths, this common length being called the semiperimeter of the triangle. A cleaver is a segment from the midpoint of a side of a triangle to the opposite side such that the perimeter is divided into two equal lengths.
Circumference of a circle[edit]
If the diameter of a circle is 1, its circumference equals π.
Main article: Circumference
The perimeter of a circle, often called the circumference, is proportional to its diameter and its radius. That is to say, there exists a constant number pi, π (the Greek p for perimeter), such that if P is the circle's perimeter and D its diameter then:
P = \pi\cdot{D}.\!
In terms of the radius r of the circle, this formula becomes:
{P}={2}\pi\cdot{r}.\!
To calculate a circle's perimeter, knowledge of its radius or diameter and of the number π is sufficient. The problem is that π is not rational (it cannot be expressed as the quotient of two integers), nor is it algebraic (it is not a root of a polynomial equation with rational coefficients). So, obtaining an accurate approximation of π is important for the calculation. The search for the digits of π is relevant to many fields, such as mathematical analysis, algorithmics and computer science.
Perception of perimeter[edit]
The more one cuts this shape, the lesser the area and the greater the perimeter. The convex hull remains the same.
The Neuf-Brisach fortification perimeter is complicated. The shortest path around it is along its convex hull.
Main articles: Area (geometry) and convex hull
The perimeter and the area are the main two measures of geometric figures. Confusing them is frequent, as well as believing that the greater one of them is, the greater is the other. Indeed, an enlargement (or a reduction) of a shape make its area grow (or decrease) as well as its perimeter. For example, if a field is drawn on a 1/10,000 scale map, the actual field perimeter can be calculated multiplying the drawing perimeter by 10,000. The real area is 10,0002 times the area of the shape on the map.
Nevertheless there is no relation between the area and the perimeter of an ordinary shape. For example, the perimeter of a rectangle of width 0.001 and length 1000 is slightly above 2000, while the perimeter of a rectangle of width 0.5 and length 2 is 5. Both areas equal to 1.
Proclus (5th century) reported that Greek peasants "fairly" parted fields relying on their perimeters.[1] But a field's production is proportional to its area, not to its perimeter: many naive peasants may have got fields with long perimeters but low areas (thus, low crops).
If one removes a piece from a figure, its area decreases but its perimeter may not. In the case of very irregular shapes, some people may confuse perimeter with convex hull. The convex hull of a figure may be visualized as the shape formed by a rubber band stretched around it. On the animated picture on the left, all the figures have the same convex hull: the big, first hexagon.
Isoperimetry[edit]
Further information: Isoperimetric inequality
The isoperimetric problem is to determine a figure with the largest area, amongst those having a given perimeter. The solution is intuitive: it is the circle. In particular, that is why drops of fat on a broth surface are circular.
This problem may seem simple, but its mathematical proof needs sophisticated theorems. The isoperimetric problem is sometimes simplified: to find the quadrilateral, or the triangle or another particular figure, with the largest area amongst those having a given perimeter. The solution to the quadrilateral isoperimetric problem is the square, and the solution to the triangle problem is the equilateral triangle. In general, the polygon with n sides having the largest area and a given perimeter is the regular polygon, which is closer to being a circle than is an irregular polygon.
See also[edit]
References[edit]
1. ^ Heath, T. (1981). A History of Greek Mathematics 2. Dover Publications. p. 206. ISBN 0-486-24074-6.
External links[edit]
This article incorporates information from this version of the equivalent article on the French Wikipedia.
|
__label__pos
| 0.989047 |
DEV Community
Cover image for Remove background from images with Python
Stokry
Stokry
Posted on
Remove background from images with Python
Today I will show you how you can remove background from your images.
I'll use numpy, cv2, matplotlib,
NumPy is the fundamental package for scientific computing in Python. It is a Python library that provides a multidimensional array object, various derived objects (such as masked arrays and matrices), and an assortment of routines for fast operations on arrays, including mathematical, logical, shape manipulation, sorting, selecting, I/O, discrete Fourier transforms, basic linear algebra, basic statistical operations, random simulation and much more.
OpenCV-Python is a library of Python bindings designed to solve computer vision problems.
cv2.imread() method loads an image from the specified file. If the image cannot be read (because of missing file, improper permissions, unsupported or invalid format) then this method returns an empty matrix.
Matplotlib is a comprehensive library for creating static, animated, and interactive visualizations in Python.
This is our test image:
enter image description here
Let's jump to the code
import numpy as np
import cv2 as cv
from matplotlib import pyplot as plt
import sys
from PIL import Image
img = cv.imread('images/test.jpg', cv.IMREAD_UNCHANGED)
original = img.copy()
l = int(max(5, 6))
u = int(min(6, 6))
ed = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
edges = cv.GaussianBlur(img, (21, 51), 3)
edges = cv.cvtColor(edges, cv.COLOR_BGR2GRAY)
edges = cv.Canny(edges, l, u)
_, thresh = cv.threshold(edges, 0, 255, cv.THRESH_BINARY + cv.THRESH_OTSU)
kernel = cv.getStructuringElement(cv.MORPH_ELLIPSE, (5, 5))
mask = cv.morphologyEx(thresh, cv.MORPH_CLOSE, kernel, iterations=4)
data = mask.tolist()
sys.setrecursionlimit(10**8)
for i in range(len(data)):
for j in range(len(data[i])):
if data[i][j] != 255:
data[i][j] = -1
else:
break
for j in range(len(data[i])-1, -1, -1):
if data[i][j] != 255:
data[i][j] = -1
else:
break
image = np.array(data)
image[image != -1] = 255
image[image == -1] = 0
mask = np.array(image, np.uint8)
result = cv.bitwise_and(original, original, mask=mask)
result[mask == 0] = 255
cv.imwrite('bg.png', result)
img = Image.open('bg.png')
img.convert("RGBA")
datas = img.getdata()
newData = []
for item in datas:
if item[0] == 255 and item[1] == 255 and item[2] == 255:
newData.append((255, 255, 255, 0))
else:
newData.append(item)
img.putdata(newData)
img.save("img.png", "PNG")
Enter fullscreen mode Exit fullscreen mode
This our result, it's not perfect, but the code did a good job.
enter image description here
That's all. Keep coding.
Top comments (2)
Collapse
codeperfectplus profile image
Deepak Raj
Great Article with Lot of information.
Try PixelLib, a Deep learning library for segmentation tasks to remove background.
Collapse
stokry profile image
Stokry
Thank you. I will try this library, looks pretty good. Thanks for the info.
|
__label__pos
| 0.852569 |
Introduction
Jinja2 is a templating language built in python and loosely based on the Django templating language. Jinja2 is used in many projects as a templating engine with some notable examples: Ansible, Salt and Flask.
Jinja2 aims to implement some of the most common features of python right into the templating system allowing for the programatic creation of static file contents.
Installation
Jinja2 is hosted on PyPi so can be installed with pip. I prefer to use virtual environments to manage python projects.
cmd
# create virtual environment
python3.6 -m venv ~/envs/jinja2-env/
# activate virtual environment
source ~/envs/jinja2-env/bin/activate
# install jinja2
pip install jinja2
For reference the following software versions are used in this blog.
• Jinja2 - 2.9.6
• Python - 3.6.1
Delimiters
Jinja2 templates have the following delimiters which define functionality to be executed by the templating engine.
• {{ ... }} variables and expressions
• {% ... %} statements eg: for, if and include
• {# ... #} comments
Variables
Variables are defined with the {{ some_variable }} syntax.
jinja
{{ some_variable }}
Loop Controls
A for loop makes it possible for blocks of text to be repeated without having to copy and paste them manually.
jinja
# example
{% for stuff in things %}
{{ stuff }}
{% endfor %} # note: for loops need to be ended
Conditionals
Conditionals render content based on when a condition is either True for False
jinja
# cisco
{% if stuff in things %}
{{ stuff }}
{% endif %} # note: if statements need to be ended
{% if stuff not in things %}
no stuff here
{% endif %} # note: if statements need to be ended
Usage
The Jinja2 workflow has 3 main steps
• Define variables
• Define a template
• Render the template with the defined varibales
Lets start with a simple example. Define some interface variables as a python dictionary.
python
# cisco
interface = {
'name': 'gigabitethernet0/0',
'description': 'Uplink to WAN',
'ip_address': '10.10.10.1 255.255.255.0',
}
Create an interface_template defining variables that will be replaced with values from the interface variable.
jinja
# cisco interface template
interface_template = '''
interface {{ interface.name }}
description {{ interface.description }}
ip address {{ interface.ip_address }}
no shutdown
!
'''
Note: Jinja2 uses the '.' syntax to access a dictionaries keys. For example interface.name refers to the interface variable and the name key. It is also possible to use python syntax to access the dictionary keys IE: interface['name']. More info can be found in the docs.
If we go ahead and render the interface_template you wil get the following result.
python
from jinja2 import Template
template = Template(interface_template)
template.render(interface=interface)
# output
interface gigabitethernet0/0
description Uplink to WAN
ip address 10.10.10.1 255.255.255.0
no shutdown
!
We managed to render a single interface configuration, not terribly exciting. Lets add more interfaces and expand out our template with a for loop.
Because we are adding multiple interfaces create a list of dictionaries for each interface to be configured.
python
interfaces = [
{'description': 'Uplink to WAN',
'ip_address': '10.10.10.1 255.255.255.0',
'name': 'gigabitethernet0/0'},
{'description': 'Crosslink to R2',
'ip_address': '10.10.20.1 255.255.255.0',
'name': 'gigabitethernet0/1'}
]
Add a for loop to the previously configured template.
python
# cisco interface template
interfaces_template = '''
{% for interface in interfaces %}
interface {{ interface.name }}
description {{ interface.description }}
ip address {{ interface.ip_address }}
no shutdown
!
{% endfor %}
Lets render the template now and see how that looks.
python
template = Template(interfaces_template)
template.render(interfaces=interfaces)
# output
interface gigabitethernet0/0
description Uplink to WAN
ip address 10.10.10.1 255.255.255.0
no shutdown
!
interface gigabitethernet0/1
description Crosslink to R2
ip address 10.10.20.1 255.255.255.0
no shutdown
!
Lets say we swap the device out with a Juniper router. This is where the advantages of configuration templating really show their value.
python
# juniper interface template
interfaces_template = '''
interfaces {
{% for interface in interfaces %}
{{ interface.name }} {
description {{ interface.description }};
unit 0 {
family inet {
address {{ interface.ip_address }};
}
}
}
{% endfor %}
}
'''
Juniper and Cisco have different interface naming standards so change the name and the ip_address values.
python
interfaces = [
{'description': 'Uplink to WAN',
'ip_address': '10.10.10.1/24',
'name': 'ge-0/0/0'},
{'description': 'Crosslink to R2',
'ip_address': '10.10.20.1/24',
'name': 'ge-0/0/1'}
]
Now render the interface template.
python
template = Template(interfaces_template)
template.render(interfaces=interfaces)
# output
interfaces {
ge-0/0/0 {
description Uplink to WAN;
unit 0 {
family inet {
address 10.10.10.1/24;
}
}
}
ge-0/0/1 {
description Crosslink to R2;
unit 0 {
family inet {
address 10.10.20.1/24;
}
}
}
}
Summary
Jinja2 is a powerful tool that allows you to build repeatable configuration templates. I have just scratched the surface in this post, Jinja2 has many features that make it an excellent tool for creating device configuration templates.
python jinja2
|
__label__pos
| 0.524274 |
ChadD ChadD - 1 year ago 72
SQL Question
CHAR vs. VARCHAR and the ramifications when joining
As this previous posting which discussed when would want to use CHAR over VARCHAR pointed out, one can gain performance advantages when the values stored are approximately the same length. Certainly I would selected CHAR as the datatype for storing a 2-character State code data.
I would just like to confirm as a sanity check that this means that when one performs a SQL that filters on this column that the filtered value must be padded with enough blanks to equal the defined length of the char field.
For example, assume a table "CODE_TABLE" where column 10_CHAR_CODE is defined as a CHAR(10):
SELECT * FROM CODE_TABLE WHERE 10_CHAR_CODE = 'ABCDE '
and that if 10_CHAR_CODE is a "logical" foreign key to another table but no specific relation integrity constraint exists, that the values stored in the 10_CHAR_CODE Lookup table should ideally be of the same datatype (Char(10) to avoid having to perform aan inefficient RTRIM function when joining.
(We have a baby size data warehouse and DBAs argue that Referential Integrity constraints are inefficient and so we end up having inconsistant datatype definitions of data across tables.)
Are my impressions accurate?
Answer Source
Trailing space is ignored in string comparisons in SQL Server. There is no need to RTRIM it yourself (which would make the condition unsargable)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download
|
__label__pos
| 0.941971 |
欢迎来到 jackNEss'窝窝
I like simple mind
手风琴式图片展示窗
2011年10月16日
手风琴式图片展示窗
图片展示窗各种各样,五花百门,今天为大家介绍的是手风琴式的图片展示窗。
工作原理:
通过改变 margin 负边距数值来实现手风琴特效
核心代码:
瀑布式算法( 数组中数值之和不变,其中一个增加的时候,那么在确保数值大于0的前提下,其他的就要减去相应的值.)
/*
* 瀑布式算法( 数组中数值之和不变,其中一个增加的时候,那么在确保数值大于0的前提下,其他的就要减去相应的值.)
* - array:int int数组集合
* - index 要发生变化的 数组下标
* - num 要发生变化的 数组 的数值
* - sum 数组内int的总和
*/
function accordionAccount(array,index,num,sum){
num = parseInt(num);
account = num - array[index];
var total = 0;
//alert(account);
for(var i = 0; i < array.length; i++){
i == index?(
array[i] = num
):(
array[i] - account >= 0?(
array[i] -= account,
account = 0
):(
array[i] = 0,
account -= array[i]
)
);
total += array[i];
//确保 数组加起来总和一致...
if(i == array.length -1 && total != sum){
array[i] = array[i] + sum - total;
}
}
return array
}
演示地址:http://www.jackness.org/lab/object/accordion_slide/demo.html
JS源码部分:
/*
* 手风琴式 slide box(注意的是,这个函数对使用环境有点要求,html部分手风琴特效通过改变 margin 负边距数值来实现)
* accordion_slide(option)
* -option{
target:目标对象,里面的内容即为要进行 手风琴特效的对象
insertWidth:手风琴中图像显示的宽度
direction:手风琴方向 left|top|right|bottom
effectType:手风琴特效的触发方式
transition:动画缓动时间
autoInterval:自动播放时间间隔
isAuto:是否自动播放
interval:每帧动画时间间隔
}
* accordion_slide.setOption(op)属性设置
* accordion_slide.beforeEffectEvent(func) 设置触发事件时调用的函数,其中函数中的 this 指向 触发事件的对象
* accordion_slide.afterEffectEvent(func) 设置触发事件后调用的函数,其中函数中的 this 指向 触发事件的对象
* accordion_slide.init() 函数执行
* ----------------------------------------------
* example:
accordion_slide({target:"#accord_list",insertWidth:600,direction:"left"}).init();
* ----------------------------------------------
* power by jackNEss
* date: 2011-10-16
* ver: 1.0
*/
var accordion_slide = function(){
//默认属性
var option = {
//目标对象,里面的内容即为要进行 手风琴特效的对象
target:null,
//手风琴中图像显示的宽度
insertWidth:0,
//手风琴方向 left|top|right|bottom
direction:"Left",
//手风琴特效的触发方式
effectType:"mouseover",
//动画缓动时间
transition:200,
//自动播放时间间隔
autoInterval:3000,
//是否自动播放
isAuto:true,
//每帧动画时间间隔
interval:20
}
var _op;
arguments[0]? _op = arguments[0]:"";
var _cells,_outset;
var _key,_nowIndex,_autoKey;
var _beforeEvent,_afterEvent;
function easy_switch(elm){
if(typeof elm == "string"){
var strs = elm.split(" ");
var targetElements = [document.body];
for(var i = 0; i < strs.length; i++){
if(!targetElements){return false;}
var flagGroups = new Array();
for(var j = 0; j < targetElements.length; j++ ){
var datasource = typeSwitcher(targetElements[j],strs[i]);
if(!datasource){return false;}
if(!datasource.length){
if(datasource){
flagGroups.push(datasource);
}
}
else{
for(var k = 0; k < datasource.length; k++){
if(datasource[k]){
flagGroups.push(datasource[k])
}
}
}
}
targetElements = flagGroups;
}
if(targetElements.length ==1){return targetElements[0]}
else {return targetElements;}
}
else{
return elm;
}
function typeSwitcher(elm,str){
if(str.substring(0,1) == "#"){
return document.getElementById( str.substring(1,str.length) )
}
else if(str.substring(0,1) == "."){
var flag = elm.getElementsByTagName("*");
var results = [];
var classStr = str.substring(1,str.length);
var classNames;
for(var i = 0; i < flag.length; i++ ){
classNames = flag[i].className.split(" ");
for( var j = 0; j < classNames.length; j++ ){
if( classStr == classNames[j] ){
results.push(flag[i]);
}
}
}
return results;
}
else{
var result = elm.getElementsByTagName(str)
if(result.length >0){
return result;
}
else{
return false;
}
}
}
}
function getCssValue(elm,attribute){
try{
return elm.currentStyle?elm.currentStyle[attribute]:document.defaultView.getComputedStyle(elm,false)[attribute];
}
catch(e){
return false;
}
}
//惯性运动
function inertia_Motion(So,St,T){
var S = Math.abs(St - So);
var a = S/Math.pow(T/2,2);
var Vt = a*T/4;
return{
Sn:function(Tn){
var _Sn;
Tn < T/2?(
_Sn = So + a*Math.pow(Tn,2)/2 * ( parseInt( (St - So)/Math.abs(St - So) )||0 )
):(
Tn < T?(
_Sn = So + ( a*Math.pow(T/2,2) - a*Math.pow(T - Tn,2)/2 )*( parseInt( (St - So)/Math.abs(St - So) )||0 )
):(
_Sn = St
)
);
return _Sn;
},
Vn:function(Tn){
var _Vn;
Tn < T/2?(
_Vn = a*Tn/2
):(
Tn < T?(
_Vn = Vt - a*(Tn - T/2)/2
):(
_Vn = 0
)
);
return _Vn;
}
}
}
function areaReset(){
//外框初始化
_outset = document.createElement("outset");
_outset.style.cssText = "position:relative;display:block;width:100%; height:" + getCssValue(option.target,"height") + ";overflow:hidden;";
var frag = document.createDocumentFragment();
var array = [];
for(; option.target.children.length > 0; ){
frag.appendChild( option.target.children[0] );
}
option.target.appendChild(_outset);
_outset.appendChild(frag);
frag = null;
//手风琴元素初始化
_cells = _outset.children;
for( var i = 0; i < _cells.length; i++ ){
_cells[i].style.position = "relative";
_cells[i].style.zIndex = _cells.length - i;
i == 0 ?_cells[i].insertWidth = option.insertWidth:_cells[i].insertWidth = 0;
array[i] = _cells[i].insertWidth;
//添加事件
_cells[i]["on" + option.effectType] = function(){
effectEvent.call(this);
}
}
_nowIndex = 0;
//元素插入深度初始化
elementInsertWidthInit(array);
}
//元素插入深度初始化
function elementInsertWidthInit(array){
for( var i = 0; i < _cells.length; i++){
_cells[i].insertWidth = array[i];
_cells[i].style["margin" + option.direction] = -option.insertWidth + _cells[i].insertWidth + "px";
}
}
/*
* 瀑布式算法( 数组中数值之和不变,其中一个增加的时候,那么在确保数值大于0的前提下,其他的就要减去相应的值.)
* - array:int int数组集合
* - index 要发生变化的 数组下标
* - num 要发生变化的 数组 的数值
* - sum 数组内int的总和
*/
function accordionAccount(array,index,num,sum){
num = parseInt(num);
account = num - array[index];
var total = 0;
//alert(account);
for(var i = 0; i < array.length; i++){
i == index?(
array[i] = num
):(
array[i] - account >= 0?(
array[i] -= account,
account = 0
):(
array[i] = 0,
account -= array[i]
)
);
total += array[i];
//确保 数组加起来总和一致...
if(i == array.length -1 && total != sum){
array[i] = array[i] + sum - total;
}
}
return array
}
//触发的事件
function effectEvent(){
var index;
var array = [];
for( var i = 0; i < _cells.length;i++ ){
array[i] = _cells[i].insertWidth;
_cells[i] == this? index = i:"";
}
if( index == _nowIndex){return;}
_beforeEvent?_beforeEvent.call(this):"";
var Tn = 0;
var T = option.transition/option.interval||0;
var St = option.insertWidth;
var So =_cells[index].insertWidth;
if(_key){ clearTimeout(_key); }
if(_autoKey){ clearTimeout(_autoKey);}
_effectEvent();
function _effectEvent(){
Tn < T?(
elementInsertWidthInit( accordionAccount(array,index,inertia_Motion(So,St,T).Sn(Tn),option.insertWidth) ),
Tn++,
_key = setTimeout(_effectEvent,option.interval)
):(
elementInsertWidthInit( accordionAccount(array,index,inertia_Motion(So,St,T).Sn(T),option.insertWidth) ),
_nowIndex = index,
_afterEvent?_afterEvent.call(this):"",
option.isAuto? _autoKey = setTimeout(autoRunEvent,option.autoInterval):""
);
}
}
//自动播放
function autoRunEvent(){
var index = _nowIndex;
index < _cells.length - 1?index+=1:index =0;
effectEvent.call(_cells[index])
}
return{
setOption:function(op){
op.target? option.target = easy_switch(op.target):"";
op.insertWidth? option.insertWidth = parseInt(op.insertWidth):"";
op.direction? option.direction = op.direction.substring(0,1).toUpperCase() + op.direction.substring(1,op.direction.length):"";
op.effectType? option.effectType = op.effectType:"";
op.transition? option.transition = parseInt(op.transition):"";
op.autoInterval? option.autoInterval = parseInt(op.autoInterval):"";
op.interval? option.interval = parseInt(op.interval):"";
typeof op.isAuto == "bool"? option.isAuto = op.isAuto:"";
return this;
},
beforeEffectEvent:function(func){
_beforeEvent = func;
return this;
},
afterEffectEvent:function(func){
_afterEvent = func;
return this;
},
init:function(){
if(_op){ this.setOption(_op);}
if( !option.target ){return;}
areaReset();
if(option.isAuto){autoRunEvent();}
}
}
}
分类javascript
阅读 1,166
• 评论加载中...
标签云
分类目录
最新留言
• 评论加载中...
与我联系
如有疑问or建议可通过以下方式跟我取得联系.
Q Q:373435871
Email:[email protected]
© Copyright 2011 - 2014 jackNEss.org All Rights Reserved 粤ICP备14065612号
首页 | 关于我 | 网站地图 | RSS
|
__label__pos
| 0.872657 |
Menu
Online UPC validation tool
UPCZilla’s tool for validating UPCs which also gives you a handy explanation of how the validation was performed.
000051008246 is a valid UPC-A (though that doesn't mean it's assigned to any products, click here to see if it is: 000051008246 - if you haven't already).
How do we check if a UPC is valid?
To check if a UPC is valid, we need to perform some calculations on its digits, as follows:
1. We take the six odd numbered digits (counting from the left, not including the final digit - more about that at the end) and we add them together:0 0 0 0 5 1 0 0 8 2 4 (6) - last digit ignored for now
0 (digit 1) + 0 (digit 3) + 5 (digit 5) + 0 (digit 7) + 8 (digit 9) + 4 (digit 11) = 17
2. Then we multiply that number (17) by 3:17 X 3 = 51 (we'll be using this number in a minute)
3. Then, similar to the first step, we take the FIVE (not six) EVEN numbered digits and we add them together as well:0 0 0 0 5 1 0 0 8 2 4 (6) - last digit still ignored
0 (digit 2) + 0 (digit 4) + 1 (digit 6) + 0 (digit 8) + 2 (digit 10) = 3
4. We get the number we got in step 3 (3) and we ADD it to the number we got in step 2 (51):3 + 51 = 54
5. Now we take the number we got in step 4 (54) and work out how much we have to add to round it up to the nearest 10. In order to round 54 up to the nearest 10 (60) we have to add... 6
6. Is this value of 6 the same as the last (rightmost) digit in our code - the one we ignored in steps 1 and 3 (that's our checksum)?
YES, the checksum in our UPC was also 6 so the UPC is valid!
The rightmost digit in a UPC is a checksum, because it provides some insurance that all the other numbers are right by performing the above calculation on them. The system is not foolproof, but if any number is wrong then you will typically get a wrong checksum.
|
__label__pos
| 0.961457 |
Python实现算法:树遍历
遍历是访问树的所有节点的过程,也可以打印它们的值。 因为所有节点都通过边(链接)连接,所以始终从根(头)节点开始。 也就是说,我们不能随机访问树中的一个节点。 这里介绍三种方式来遍历一棵树 -
• 顺序遍历
• 前序遍历
• 后序遍历
按顺序遍历
在这种遍历方法中,首先访问左侧子树,然后访问根,然后访问右侧子树。 我们应该永远记住每个节点本身可能代表一个子树。
在下面的python程序中,使用Node类为根节点以及左右节点创建占位符。 然后创建一个insert()函数来将数据添加到树中。 最后,Inorder遍历逻辑通过创建一个空列表,并首先添加添加根节点或父节点,然后左节点来实现。 最后添加左节点以完成Inorder遍历。 请注意,对于每个子树重复此过程,直到遍历所有节点。
class Node:
def __init__(self, data):
self.left = None
self.right = None
self.data = data
# Insert Node
def insert(self, data):
if self.data:
if data < self.data:
if self.left is None:
self.left = Node(data)
else:
self.left.insert(data)
elif data > self.data:
if self.right is None:
self.right = Node(data)
else:
self.right.insert(data)
else:
self.data = data
# Print the Tree
def PrintTree(self):
if self.left:
self.left.PrintTree()
print( self.data),
if self.right:
self.right.PrintTree()
# Inorder traversal
# Left -> Root -> Right
def inorderTraversal(self, root):
res = []
if root:
res = self.inorderTraversal(root.left)
res.append(root.data)
res = res + self.inorderTraversal(root.right)
return res
root = Node(27)
root.insert(14)
root.insert(35)
root.insert(10)
root.insert(19)
root.insert(31)
root.insert(42)
print(root.inorderTraversal(root))
前序遍历
在这种遍历方法中,首先访问根节点,然后访问左边的子树,最后访问右边的子树。
在下面的python程序中,使用Node类为根节点以及左右节点创建占位符。 然后创建一个insert()函数来将数据添加到树中。 最后,前序遍历遍历逻辑通过创建一个空列表并首先添加根节点,然后添加左节点来实现。 最后添加右节点以完成前序遍历。 请注意,对于每个子树重复此过程,直到遍历所有节点。
class Node:
def __init__(self, data):
self.left = None
self.right = None
self.data = data
# Insert Node
def insert(self, data):
if self.data:
if data < self.data:
if self.left is None:
self.left = Node(data)
else:
self.left.insert(data)
elif data > self.data:
if self.right is None:
self.right = Node(data)
else:
self.right.insert(data)
else:
self.data = data
# Print the Tree
def PrintTree(self):
if self.left:
self.left.PrintTree()
print( self.data),
if self.right:
self.right.PrintTree()
# Preorder traversal
# Root -> Left ->Right
def PreorderTraversal(self, root):
res = []
if root:
res.append(root.data)
res = res + self.PreorderTraversal(root.left)
res = res + self.PreorderTraversal(root.right)
return res
root = Node(27)
root.insert(14)
root.insert(35)
root.insert(10)
root.insert(19)
root.insert(31)
root.insert(42)
print(root.PreorderTraversal(root))
后序遍历
在这个遍历方法中,最后访问根节点。 首先遍历左子树,然后遍历右子树,最后遍历根节点。
在下面的python程序中,使用Node类为根节点以及左右节点创建占位符。 然后创建一个insert()函数来将数据添加到树中。 最后,通过创建一个空列表并添加左节点,然后添加右节点来实现后序遍历逻辑。 最后,添加根或父节点以完成后序遍历。 请注意,对于每个子树重复此过程,直到遍历所有节点。参考以下代码实现 -
class Node:
def __init__(self, data):
self.left = None
self.right = None
self.data = data
# Insert Node
def insert(self, data):
if self.data:
if data < self.data:
if self.left is None:
self.left = Node(data)
else:
self.left.insert(data)
elif data > self.data:
if self.right is None:
self.right = Node(data)
else:
self.right.insert(data)
else:
self.data = data
# Print the Tree
def PrintTree(self):
if self.left:
self.left.PrintTree()
print( self.data),
if self.right:
self.right.PrintTree()
# Postorder traversal
# Left ->Right -> Root
def PostorderTraversal(self, root):
res = []
if root:
res = self.PostorderTraversal(root.left)
res = res + self.PostorderTraversal(root.right)
res.append(root.data)
return res
root = Node(27)
root.insert(14)
root.insert(35)
root.insert(10)
root.insert(19)
root.insert(31)
root.insert(42)
print(root.PostorderTraversal(root))
移动端设备除iPad Pro外,其它移动设备仅能阅读基础的文本文字。
建议使用PC或笔记本电脑,浏览器使用Chrome或FireFox进行浏览,以开启左侧互动实验区来提升学习效率,推荐使用的分辨率为1920x1080或更高。
我们坚信最好的学习是参与其中这一理念,并致力成为中文互联网上体验更好的学练一体的IT技术学习交流平台。
您可加QQ群:575806994,一起学习交流技术,反馈网站使用中遇到问题。
内容、课程、广告等相关合作请扫描右侧二维码添加好友。
狐狸教程 Copyright 2021
进入全屏
|
__label__pos
| 0.994342 |
Active and Passive Data Store
Posted by Stephan Mueller on September 14, 2011
More by this author
/wp-content/uploads/2011/09/active-passive-store_t.pngBy default, all data is stored in-memory to achieve high-speed data access. However, not all data is accessed or updated frequently and needs to reside in-memory, as this increases the required amount of main memory unnecessarily. This so-called historic or passive data can be stored in a specific passive data storage based on less expensive storage media, such as SSDs or hard disks, still providing sufficient performance for possible accesses at lower cost. The dynamic transition from active to passive data is supported by the database, based on custom rules defined as per customer needs.
We define two categories of data stores: active and passive: We refer to active data when it is accessed frequently and updates are expected (e.g., access rules). In contrast, we refer to passive data when this data either is not used frequently and neither updated nor read. Passive data is purely used for analytical and statistical purposes or in exceptional situations where specific investigations require this data. For example, tracking events of a certain pharmaceutical product that was sold five years ago can be considered as passive data. Why is this feasible? Firstly, from the business perspective, the pharmaceutical is equipped with a best-before data of two years after its manufacturing date, i.e. even when the product is handled now, it is no longer allowed to sell it. Secondly, the product was sold to a customer four years ago, i.e. it left the supply chain and is typically already used within this timespan. Therefore, the probability that details about this certain pharmaceutical are queried is very low. Nonetheless, the tracking history needs to be conserved by law regulation, for example, to prove the used path within the supply chain or when sales numbers are analyzed for building a new long-term forecast based on historical data.
Furthermore, introducing the concept of passive data comes with the advantage to reduce the amount of data, which needs to be accessed in real-time, and to enable archiving. As a result, when data is moved to a passive data store it consumes no longer fast accessible main memory and frees hardware resources. Dealing with passive data stores involves the need for a memory hierarchy from fast, but expensive to slow and cheap. A possible storage hierarchy is given by memory registers, cache memory, main memory, flash storages, solid state disks, SAS hard disk drives, SATA hard disk drives, tapes, etc. As a result, rules for migrating data from one store to another need to be defined, we refer to it as aging strategy or aging rules. The process of aging data, i.e. migrating it from a faster store to a slower one, is considered as background tasks, which occurs on regularly basis, e.g. weekly or daily. Since this process involves reorganization of the entire data set, it should be processed during times with low data access, e.g. during nights or weekends. Please also see our podcast on this technology concept.
VN:F [1.9.22_1171]
Average User Rating
Rating: 2.5/5 (2 votes cast)
Active and Passive Data Store, 2.5 out of 5 based on 2 ratings
12653 Views
|
__label__pos
| 0.861151 |
Cara Membuat link warna warni pada ssaat disentuh mouse pada bloger
Cara Membuat link warna warni pada ssaat disentuh mouse pada bloger
1. Anda Login ke akun Blogger anda.
2. Kemudian anda Klik Template --> Edit HTML --> Lanjutkan (jangan lupa centang Expand Template Widget).
3. Kemudian anda cari keode </head> ( supaya pencarian lebih mudah tekan Ctrl + F ).
4. Jika sudah ketemu kode </head> Letakkan kode berikut ini tepat di atas kode </head> tadi
<script type='text/javascript'>
//<![CDATA[
var rate = 20;
if (document.getElementById)
window.onerror=new Function("return true")
var objActive; // The object which event occured in
var act = 0; // Flag during the action
var elmH = 0; // Hue
var elmS = 128; // Saturation
var elmV = 255; // Value
var clrOrg; // A color before the change
var TimerID; // Timer ID
if (document.all) {
document.onmouseover = doRainbowAnchor;
document.onmouseout = stopRainbowAnchor;
}
else if (document.getElementById) {
document.captureEvents(Event.MOUSEOVER | Event.MOUSEOUT);
document.onmouseover = Mozilla_doRainbowAnchor;
document.onmouseout = Mozilla_stopRainbowAnchor;
}
function doRainbow(obj)
{
if (act == 0) {
act = 1;
if (obj)
objActive = obj;
else
objActive = event.srcElement;
clrOrg = objActive.style.color;
TimerID = setInterval("ChangeColor()",100);
}
}
function stopRainbow()
{
if (act) {
objActive.style.color = clrOrg;
clearInterval(TimerID);
act = 0;
}
}
function doRainbowAnchor()
{
if (act == 0) {
var obj = event.srcElement;
while (obj.tagName != 'A' && obj.tagName != 'BODY') {
obj = obj.parentElement;
if (obj.tagName == 'A' || obj.tagName == 'BODY')
break;
}
if (obj.tagName == 'A' && obj.href != '') {
objActive = obj;
act = 1;
clrOrg = objActive.style.color;
TimerID = setInterval("ChangeColor()",100);
}
}
}
function stopRainbowAnchor()
{
if (act) {
if (objActive.tagName == 'A') {
objActive.style.color = clrOrg;
clearInterval(TimerID);
act = 0;
}
}
}
function Mozilla_doRainbowAnchor(e)
{
if (act == 0) {
obj = e.target;
while (obj.nodeName != 'A' && obj.nodeName != 'BODY') {
obj = obj.parentNode;
if (obj.nodeName == 'A' || obj.nodeName == 'BODY')
break;
}
if (obj.nodeName == 'A' && obj.href != '') {
objActive = obj;
act = 1;
clrOrg = obj.style.color;
TimerID = setInterval("ChangeColor()",100);
}
}
}
function Mozilla_stopRainbowAnchor(e)
{
if (act) {
if (objActive.nodeName == 'A') {
objActive.style.color = clrOrg;
clearInterval(TimerID);
act = 0;
}
}
}
function ChangeColor()
{
objActive.style.color = makeColor();
}
function makeColor()
{
// Don't you think Color Gamut to look like Rainbow?
// HSVtoRGB
if (elmS == 0) {
elmR = elmV; elmG = elmV; elmB = elmV;
}
else {
t1 = elmV;
t2 = (255 - elmS) * elmV / 255;
t3 = elmH % 60;
t3 = (t1 - t2) * t3 / 60;
if (elmH < 60) {
elmR = t1; elmB = t2; elmG = t2 + t3;
}
else if (elmH < 120) {
elmG = t1; elmB = t2; elmR = t1 - t3;
}
else if (elmH < 180) {
elmG = t1; elmR = t2; elmB = t2 + t3;
}
else if (elmH < 240) {
elmB = t1; elmR = t2; elmG = t1 - t3;
}
else if (elmH < 300) {
elmB = t1; elmG = t2; elmR = t2 + t3;
}
else if (elmH < 360) {
elmR = t1; elmG = t2; elmB = t1 - t3;
}
else {
elmR = 0; elmG = 0; elmB = 0;
}
}
elmR = Math.floor(elmR).toString(16);
elmG = Math.floor(elmG).toString(16);
elmB = Math.floor(elmB).toString(16);
if (elmR.length == 1) elmR = "0" + elmR;
if (elmG.length == 1) elmG = "0" + elmG;
if (elmB.length == 1) elmB = "0" + elmB;
elmH = elmH + rate;
if (elmH >= 360)
elmH = 0;
return '#' + elmR + elmG + elmB;
}
//]]>
</script>
5. Yang terakhir simpan template anda dan lihatlah hasilnya
6. selamat mencoba.......!!!!
Buka Komentar
|
__label__pos
| 0.999991 |
Golang program to implement a weighted interval scheduling algorithm
The Weighted Interval Scheduling Problem revolves around a set of intervals, each having an associated weight. In this article, we will implement the Weighted Interval Scheduling algorithm in go, using two methods: Recursive and Dynamic Programming. This classic optimization problem involves selecting non-overlapping intervals with maximum total weight.
Explanation
Recursive Method
The Recursive Method takes a straightforward yet elegant approach. It examines each interval one by one and considers two scenarios − whether to include the current interval or skip it. This method utilises recursion to explore all possible combinations of intervals, calculating the maximum weight. While conceptually clear, it might not be the most efficient approach for larger inputs due to overlapping subproblems.
Dynamic Programming Method
The Dynamic Programming Method is an optimization over the recursive approach. It capitalizes on the principle of memoization, storing previously computed results to avoid redundant calculations. This method builds a table of maximum weights for various interval sizes and utilizes these precomputed values to efficiently compute the solution. It's more efficient than the recursive method, especially for larger datasets.
Syntax
func recursiveWeightedIntervalScheduling(intervals []Interval) int
The Syntax takes a slice of intervals as input and returns an integer. It uses a recursive approach to find the maximum total weight of non-overlapping intervals. This method recursively explores all possible combinations of intervals and selects the one with the highest total weight. However, it can be less efficient for a large number of intervals due to redundant calculations.
Algorithm
• Sort the intervals based on their finish times in ascending order.
• Initialize a dynamic programming table DP of size len(intervals)+1, where DP[i] represents the maximum total weight of non-overlapping intervals up to the ith interval.
• Set DP[0] to 0, as there are no intervals to consider.
• Iterate over each interval i in intervals (starting from 1) −
• Find the last compatible interval j (where the finish time of j is less than or equal to the start time of i) using binary search or linear search.
• Calculate the total weight of including the current interval i along with DP[j] and assign it to DP[i].
• Update DP[i] to the maximum value between DP[i] and DP[i-1] to consider the possibility of excluding the current interval.
• The maximum total weight of non-overlapping intervals will be stored in DP[len(intervals)].
Example 1
In this example, we have six weighted intervals represented as a collection of start times, finish times, and corresponding weights. The goal is to find the maximum total weight of non-overlapping intervals, i.e., to select a subset of intervals such that no two intervals overlap in time, and the sum of their weights is maximized. The Recursive Weighted Interval Scheduling algorithm in go efficiently solves this problem by recursively exploring all possible combinations of intervals and selecting the one with the highest total weight.
package main
import "fmt"
type Interval struct {
start, finish, weight int
}
func schedule(intervals []Interval, currentIndex, prevFinish int) int {
if currentIndex == len(intervals) {
return 0
}
if intervals[currentIndex].start < prevFinish {
return schedule(intervals, currentIndex+1, prevFinish)
}
includeCurrent := intervals[currentIndex].weight + schedule(intervals, currentIndex+1, intervals[currentIndex].finish)
skipCurrent := schedule(intervals, currentIndex+1, prevFinish)
return max(includeCurrent, skipCurrent)
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
func main() {
intervals := []Interval{
{1, 4, 3},
{3, 7, 5},
{0, 6, 8},
{5, 9, 2},
{8, 12, 6},
{10, 15, 4},
}
maxWeight := schedule(intervals, 0, 0)
fmt.Println("Maximum total weight of non-overlapping intervals:", maxWeight)
}
func sortByFinish(intervals []Interval) {
n := len(intervals)
for i := 0; i < n-1; i++ {
for j := 0; j < n-i-1; j++ {
if intervals[j].finish > intervals[j+1].finish {
intervals[j], intervals[j+1] = intervals[j+1], intervals[j]
}
}
}
}
Output
Maximum total weight of non-overlapping intervals: 14
Example 2
In this example, we have six weighted intervals: [1, 4, 3], [3, 5, 2], [0, 6, 4], [5, 7, 1], [8, 9, 3], and [5, 9, 5]. The Dynamic Programming Weighted Interval Scheduling algorithm in go is employed to find the maximum total weight of non-overlapping intervals. For the given input intervals, the maximum total weight of non-overlapping intervals is found to be 14.
package main
import (
"fmt"
"sort"
)
type Interval struct {
start, end, weight int
}
func latestNonOverlapping(intervals []Interval, i int) int {
for j := i - 1; j >= 0; j-- {
if intervals[j].end <= intervals[i].start {
return j
}
}
return -1
}
func findMaxWeight(intervals []Interval) int {
sort.Slice(intervals, func(i, j int) bool {
return intervals[i].end < intervals[j].end
})
n := len(intervals)
dp := make([]int, n)
dp[0] = intervals[0].weight
for i := 1; i < n; i++ {
nonOverlap := latestNonOverlapping(intervals, i)
if nonOverlap != -1 {
dp[i] = max(dp[i-1], dp[nonOverlap]+intervals[i].weight)
} else {
dp[i] = max(dp[i-1], intervals[i].weight)
}
}
return dp[n-1]
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
func main() {
intervals := []Interval{
{1, 4, 3},
{3, 5, 2},
{0, 6, 4},
{5, 7, 1},
{8, 9, 3},
{5, 9, 5},
}
maxWeight := findMaxWeight(intervals)
fmt.Println("Maximum total weight of non-overlapping intervals:", maxWeight)
}
Output
Maximum total weight of non-overlapping intervals: 8
Real life implementations
Project Management
Weighted Interval Scheduling finds use in project scheduling, where tasks have varying importance and timeframes. By selecting a sequence of tasks with maximum combined importance and no overlap, this algorithm aids project managers in optimizing task execution for better project outcomes.
Conference Room Booking
In corporate environments, scheduling events like meetings or workshops is crucial. Weighted Interval Scheduling helps prioritize and schedule events efficiently, ensuring important activities are accommodated, optimizing resource use in conference rooms.
Conclusion
In this article, we have looked at the Weighted Interval Scheduling algorithm using two methods: Recursive and Dynamic Programming. The Recursive Method uses recursion to explore all possible combinations of intervals, while the Dynamic Programming Method stores intermediate results for efficiency.
Updated on: 05-Sep-2023
83 Views
Kickstart Your Career
Get certified by completing the course
Get Started
Advertisements
|
__label__pos
| 0.997995 |
5 Under the graph 1st write the roman numeral for the prob.pdf
Nächste SlideShare
6 Add records to the database a This query will add a new.pdf6 Add records to the database a This query will add a new.pdf
Wird geladen in ... 3
1 von 1
Más contenido relacionado
Más de ruckfulesnishu(20)
5 Under the graph 1st write the roman numeral for the prob.pdf
1. 5. Under the graph 1st write the roman numeral for the probability statement that represents it the best and then write the letter for the general calculator input that fits best in the 2nd space. Here a <b. i.) P(a<x<b) a.) normalcdf (b,1099,,) ii.) P(a<x) b.) 1-normalcdf (a,b,,) iii.) P(b>x) c.) normalcdf ( a,b,,) iv.) P(x>a) d.) normalcdf (1099,a,,) e.) 2 normalcdf (b,1099,,) 1 6. What percent of a standard normal distribution, ZN(0,1). Draw a graph for each probability and write the probability statement. a) Z>1.13 b) Z<0.18 c) Z>8 d) Z<0.5
|
__label__pos
| 0.97781 |
8
I am trying to create a custom Tree Grid component in that based on my business use case I'm in need to create every row as a component, and every column as a component. Below is the structure of my component
table container component
<template>
<table>
<thead>
</thead>
<tbody>
<template for:each={datas} for:item="d">
<c-child key={d.Id} data={d}></c-child>
</template>
</tbody>
</table>
</template>
Child component
<template>
<td>{data.Name}</td>
<td>{data.age}</td>
<td>{data.num}</td>
<td>{data.Email}</td>
<template for:each={data.childrens} for:item="d">
<c-child key={d.Id} data={d}></c-child>
</template>
</template>
Child.css
:host {
display: table-row;
}
Here My Question is when I try to build a row component recursively for the tree structure . Since My row component doesn't contain <tr> I cannot able to render recursively because every custom element(LWC component) includes a tag with the component name in HTML Lightning Web Component for table rows and cellsbased on this link every row component behaves like a row when applying display: table-row;
So My nested tree structure looks like when I try to build the row component recursively, So my host component behaves like single tr
<c-row>
<td></td>
<td></td>
<c-row>
<c-row>
</c-row>
Here is a Playground link that I described my issue with a simple example.
UPDATE :
Below is the screenshot of UI I am trying to build
Example Tree Grid
• Any reason not using lightning-tree or lightning-tree-grid? – Atlas Can Dec 27 '19 at 6:54
• We need inline edit feature in tree grid and some other business use cases which cannot be covered in tree grid so we planned to build custom grid component – vignesh Dec 27 '19 at 9:06
• can you explain exactly what UI you are trying to render? any screenshot of that? – rahul gawale Dec 27 '19 at 10:15
• I just want to render like slds tree grid lightningdesignsystem.com/components/tree-grid and I provided the playground URL above it describes the issue which I am facing' – vignesh Dec 27 '19 at 12:26
• @rahulgawale Here is the screenshot of UI Iam trying to build drive.google.com/file/d/1r7Wh_vADwBbD11BI4NaZwz1N95DQ0tMI/… – vignesh Dec 27 '19 at 13:17
4
+50
When I want to rebuild/extend some of the functionality for LWC I usually get styling from SLDS. You can check markup here for tree-grid.
Salesforce flattens data and uses aria-expanded, aria-level for styling. I would suggest the same. Here is the script to flatten data. I also updated playground with simple styling for Id
UPDATE: Created separate playground to not override changes.
UPDATE Added expand/hide.
Here is sample row markup with some code.
// rendered.js
let data = [
{ Name:'st1', Id:1, age:'2', num:'342222222', Email:'[email protected]' },
{ Name:'st1', age:'2', Id:2, num:'342222222', Email:'[email protected]', children:[
{ Name:'st1child', Id:6, age:'2', num:'342222222', Email:'[email protected]' },
{ Name:'st1child', Id:7, age:'2', num:'342222222', Email:'[email protected]' }, ]
},
{ Name:'st1', age:'2', Id:3, num:'342222222', Email:'[email protected]' },
{ Name:'st1', age:'2', Id:4, num:'342222222', Email:'[email protected]' },
{ Name:'st1', age:'2', Id:5, num:'342222222', Email:'[email protected]' },
];
const isExpandedDefault = false;
const flatIt = (data, level) => data.reduce((acc, row) => [...acc, Object.assign(row, {
level,
expanded: isExpandedDefault,
}), ...flatIt(row.children || [], level + 1)], []);
data = flatIt(data, 1);
<!-- parent.html -->
<template>
<table class="slds-tree">
<thead>
<th>Name</th>
<th>Age</th>
<th>Num</th>
<th>Email</th>
</thead>
<tbody>
<template for:each={datas} for:item="d">
<c-child key={d.Id} data={d}></c-child>
</template>
</tbody>
</table>
</template>
// Child.js
export default class Child extends LightningElement {
@track _data;
renderedCallback() {
}
@api
set data(value) {
this._data = value;
this.ariaExpanded = false;
this.ariaLevel = value.level;
}
get data() {
return this._data;
}
}
1
I think there are are two ways to achieve what you want:
1. Don't change underlying data structure but change UI markup handle data structure.
2. Change underlying data structure but keep UI markup simple.
I chose option 2 and was able to get this output:
Link to playground: https://developer.salesforce.com/docs/component-library/tools/playground/KG-dO5AL/2/edit
enter image description here
app.html:
<template>
<table>
<thead>
<th>Name</th>
</thead>
<tbody>
<template for:each={tableData} for:item="rowData">
<tr key={rowData.Id} class={rowData.rowStyle}>
<td>
<span style={rowData.nameStyle}>
<lightning-icon icon-name={rowData.iconName}
size=x-small
onclick={showOrHideChildrenRows}
data-rowid={rowData.Id}
data-expanded="false">
</lightning-icon>
{rowData.Name}
</span>
</td>
</tr>
</template>
</tbody>
</table>
</template>
app.js:
import { LightningElement, track } from "lwc";
export default class App extends LightningElement {
@track
tableData =[
{
Name: "United States",
Id: 1,
iconName: "utility:chevronright",
parentId : null,
rowStyle : "",
nameStyle : ""
},
{
Name: "Massachusetts",
Id: 2,
iconName: "utility:chevronright",
parentId: 1,
rowStyle : "hide",
nameStyle : "margin-left:10px;"
},
{
Name: "Boston",
Id: 3,
iconName: "",
parentId: 2,
rowStyle : "hide",
nameStyle : "margin-left:20px;"
},
{
Name: "New York",
Id: 4,
iconName: "",
parentId : 1,
rowStyle : "hide",
nameStyle : "margin-left:10px;"
},
{
Name: "Vatican City",
Id : 5,
iconName: "",
parentId : null,
rowStyle : "",
nameStyle : ""
},
{
Name: "Canada",
Id : 6,
iconName: "utility:chevronright",
parentId : null,
rowStyle : "",
nameStyle : ""
},
{
Name: "Ontario",
Id : 7,
iconName: "",
parentId : 6,
rowStyle : "hide",
nameStyle : "margin-left:10px;"
},
{
Name: "Alberta",
Id : 8,
iconName: "",
parentId : 6,
rowStyle : "hide",
nameStyle : "margin-left:10px;"
}
];
showOrHideChildrenRows(event){
let rowId = event.target.dataset.rowid;
let isExpanded = event.target.dataset.expanded;
event.target.iconName = JSON.parse(isExpanded) ? "utility:chevronright": "utility:chevrondown";
event.target.dataset.expanded = JSON.stringify(!JSON.parse(isExpanded));
this.tableData = this.tableData.map((obj) => {
if(obj.parentId == rowId && !JSON.parse(isExpanded)){
obj.rowStyle = "";
}
if(obj.parentId == rowId && JSON.parse(isExpanded)){
obj.rowStyle = "hide";
}
return obj;
});
console.log(this.tableData);
}
}
Each element in the data structure has these special attributes:
• parentId - to relate each element to its parent element.
• rowStyle - to hide or show children elements.
• nameStyle - to apply proper indentation to parent elements.
EDIT:
As per ytiq's comment I added the logic on how to flatten the data given in the question. here is the updated playground
Note that the logic to flatten the original data structure may need to be changed based on factors like:
1. how many levels deep the original data structure is going to be
2. Is Id going to be unique across entire hierarchy.
• You hard-coded styling, so you didn't solve the issue for properly displaying the underlying data – ytiq Dec 29 '19 at 17:41
• @ytiq we can solve that while flattening the data. My point was to show that we don’t need to work with the same data structure that we are getting from server. I will try to update logic on how to flatten the data structure. – javanoob Dec 29 '19 at 18:12
• @ytiq check my upddated playground. I think this is what you referring to in your previous comment. – javanoob Dec 29 '19 at 22:33
Your Answer
By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy
Not the answer you're looking for? Browse other questions tagged or ask your own question.
|
__label__pos
| 0.950814 |
09 spark连接mysql数据库
spark连接mysql数据库
1.安装启动检查Mysql服务。
netstat -tunlp (3306)
2.spark 连接mysql驱动程序。
–cp /usr/local/hive/lib/mysql-connector-java-5.1.40-bin.jar /usr/local/spark/jars
pyspark \
--jars /usr/local/spark/jars/mysql-connector-java-8.0.25.jar \
--driver-class-path /usr/local/spark/jars/mysql-connector-java-8.0.25.jar
3.启动 Mysql shell,新建数据库spark,表student。
select * from student;
createdatabase spark; use spark; createtable student (idint(4), namechar(20), gender char(4), age int(4)); altertable student changeididint auto_increment primary key; insertinto student values(1,'Xueqian','F',23); insertinto student values(2,'Weiliang','M',24); select * from student;
4.spark读取MySQL数据库中的数据
spark.read.format("jdbc").option("url", "jdbc:mysql://localhost:3306/spark?useSSL=false") ... .load()
jdbcDF = spark.read.format("jdbc").option("url", "jdbc:mysql://localhost:3306/spark").option("driver","com.mysql.jdbc.Driver").option("dbtable", "student").option("user", "root").option("password", "123456").load() jdbcDF.show()
5.spark向MySQL数据库写入数据
studentDF.write.format(‘jdbc’).option(…).mode(‘append’).save()
from pyspark.sql.types import Row from pyspark.sql.types import StructType from pyspark.sql.types import StructField from pyspark.sql.types import StringType from pyspark.sql.types import IntegerType studentRDD = spark.sparkContext.parallelize(["3 Rongcheng M 26","4 Guanhua M 27"]).map(lambda line : line.split(" ")) //下面要设置模式信息 schema = StructType([StructField("name", StringType(), True),StructField("gender", StringType(), True),StructField("age",IntegerType(), True)]) rowRDD = studentRDD.map(lambda p : Row(p[1].strip(), p[2].strip(),int(p[3]))) //建立起Row对象和模式之间的对应关系,也就是把数据和模式对应起来 studentDF = spark.createDataFrame(rowRDD, schema) prop = {} prop['user'] = 'root' prop['password'] = 'hadoop' prop['driver'] = "com.mysql.jdbc.Driver" studentDF.write.jdbc("jdbc:mysql://localhost:3306/spark",'student','append', prop)
select * from student;
createdatabase spark; use spark; createtable student (idint(4), namechar(20), gender char(4), age int(4)); altertable student changeididint auto_increment primary key; insertinto student values(1,'Xueqian','F',23); insertinto student values(2,'Weiliang','M',24); select * from student;
posted @ 2021-05-31 17:00 亮皓的小老舔狗 阅读(123) 评论(0编辑 收藏 举报
|
__label__pos
| 0.646473 |
Presentation is loading. Please wait.
Presentation is loading. Please wait.
Simple Graph Warmup. Cycles in Simple Graphs A cycle in a simple graph is a sequence of vertices v 0, …, v n for some n>0, where v 0, ….v n-1 are distinct,
Similar presentations
Presentation on theme: "Simple Graph Warmup. Cycles in Simple Graphs A cycle in a simple graph is a sequence of vertices v 0, …, v n for some n>0, where v 0, ….v n-1 are distinct,"— Presentation transcript:
1 Simple Graph Warmup
2 Cycles in Simple Graphs A cycle in a simple graph is a sequence of vertices v 0, …, v n for some n>0, where v 0, ….v n-1 are distinct, v 0 =v n, and {v i,v i+1 } is an edge for 0≤i { "@context": "http://schema.org", "@type": "ImageObject", "contentUrl": "http://images.slideplayer.com/11/3191103/slides/slide_2.jpg", "name": "Cycles in Simple Graphs A cycle in a simple graph is a sequence of vertices v 0, …, v n for some n>0, where v 0, ….v n-1 are distinct, v 0 =v n, and {v i,v i+1 } is an edge for 0≤i
3 Trees A tree is a connected acyclic graph. (These are a kind of undirected graph, so the definition is different from the directed trees we talked about earlier.)
4 In a tree there is a unique path between any pair of vertices Proof. If there were two vertices with no path between them, the graph would not be connected. Suppose there were two vertices with two distinct paths between them. By the WOP there would be a shortest possible path in the graph for which there is a distinct path between the same pair of endpoints. The second path must have no vertices in common with the first except the endpoints (otherwise first path would not be the shortest). Then following one path forward and the other back creates a cycle, contradiction. So there cannot be more or less than one path between any pair of vertices. QED.
5 Finis
Download ppt "Simple Graph Warmup. Cycles in Simple Graphs A cycle in a simple graph is a sequence of vertices v 0, …, v n for some n>0, where v 0, ….v n-1 are distinct,"
Similar presentations
Ads by Google
|
__label__pos
| 0.971344 |
1. Limited time only! Sign up for a free 30min personal tutor trial with Chegg Tutors
Dismiss Notice
Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!
Homework Help: Linear Algebra - Two questions
1. Sep 14, 2011 #1
1. The problem statement, all variables and given/known data
Q1: Find the value(s) of h for which the vectors are linearly dependent. Justify your answer.
Q2: The linear transformation T is defined by T(x)=Ax. Find a vector x whose image under T is b and determine whether x is unique.
2. Relevant equations
Q1: I'm going to write the vectors as linear equations instead, since it should be easier to input:
1(x1) -2(x2) + 3(x3)
5(x1) -9(x2) + h(x3)
-3(x1) +6(x2) -9(x3)
Q2: I will write Matrix A with vector b in linear equation form as well.
1(x1) -5(x2) -7(x3) = -2
-3(x1) +7(x2) +5(x3) = -2
3. The attempt at a solution
I feel like I'm mostly right on these, but I would like some confirmation before I have to turn them in.
For Q1: I noticed that row 3 is a scalar multiple of row 1, so I performed the necessary row operation to make it a zero row. Then I replaced row 2 with the sum of row 2 and (-5) row 1. This left me with:
1(x1) - 2(x2) + 3(x3)
0(x1) + 1(x2) +h-15(x3)
0 0 0
I'm a little fuzzy on linear dependency, but I thought that if I could make x3 a free variable, then I'd have it. But then I noticed that x3 is always going to be a free variable, so it seems to me that the solution should be all real numbers.
For Q2 - I'll just say the row operations I did, and the solution that I came up with:
(3)row 1 + row 2 replace row 2.
Scale row 2 by -(1/8)
(5)row 2 + row 1 replace row 1.
This left me with:
(x3) free
(x1) = 3 - 3(x3)
(x2) = 1 - 2(x3)
And my answer is: Since (x3) is free, the solution is not unique.
Thanks for any help.
Last edited: Sep 14, 2011
2. jcsd
3. Sep 14, 2011 #2
Take the determinant of the matrix and set it to 0
4. Sep 14, 2011 #3
Mark44
Staff: Mentor
These are NOT equations. If they were, each row would have an = in it.
What are x1, x2, and x3? Are they vectors? Are they components of a single vector?
Since you don't have a system of equations, what you're doing here doesn't seem valid to me.
What is the exact wording of these problems?
5. Sep 15, 2011 #4
The exact wording of the problems is what I wrote.
For Q1, just imagine a coeffecient matrix, now imagine them listed as column vectors V1-V3 instead.
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook
|
__label__pos
| 0.985106 |
Take the 2-minute tour ×
MathOverflow is a question and answer site for professional mathematicians. It's 100% free, no registration required.
Elie Cartan made fundamental contributions to the theory of Lie groups and their geometrical applications. Among those, we can list the introduction of the remarkable family of Riemannian symmetric spaces, and his four papers that revolutionized the theory of isoparametric hypersurfaces.
How come Cartan did not notice the close relationship between symmetric spaces and isoparametric hypersurfaces?
Starting in 1926, Cartan developed his theory of symmetric spaces and published papers between 1927 and 1935. He first introduced them as Riemannian manifolds with parallel curvature tensor, under the name "espaces $\mathcal E$". Then he noticed that an equivalent, more geometric definition is to require that the geodesic symmetric around any point is an isometry and, around 1929, changed their name to "espaces symetriques'". The second definition implies that a symmetric space is a homogeneous space $G/K$ and there is a decompositon $\mathfrak g=\mathfrak k+\mathfrak p$ into the eigenspaces of an involution induced by conjugation by the geodesic symmetry at the basepoint. The adjoint action of $K$ on $\mathfrak p$ is equivalent to the linear isotropy representation of the symmetric space. The rank of $G/K$ is the dimension of a maximal flat, and coincides with the codimension of the principal orbits of this representation.
Isoparametric hypersurfaces in space forms are hypersurfaces with the simplest local invariants, namely, they have constant principal curvatures. They existed before Cartan, but between 1937 and 1940 he published four papers that completely revolutionized the field. Among other things, he showed that isoparametric hypersurfaces in spheres is a much more interesting subject than in Euclidean or hyperbolic spaces. Denote by $g$ the (constant) number of principal curvatures. The initial cases are not very interesting; in a sphere $S^{n+1}$, an isoparametric hypersurface with $g=1$ is an umbilic sphere, and with $g=2$ is the standard product of two spheres. Cartan showed that in case $g=3$ there are exactly four examples, of dimension $n=3d$ where $d=1$, $2$, $4$ or $8$ is the uniform multiplicity of the principal curvatures, each related to an embedding of a projective plane over one the normed division algebras $\mathbb R$, $\mathbb C$, $\mathbb H$, $\mathbb O$. He notes that those examples are all homogeneous and determines their isometry groups; in particular, he is pleased with the appearance of the exceptional group $F_4$ the case $n=24$, "(...) the first appearance of the simple $52$-dimensional group in a geometric problem (...)"; this group had already appeared in his classification of symmetric spaces. Later Cartan discusses the case $g=4$ and shows there are only two examples where the multiplicities of principal curvatures are all equal, namely, one in $S^5$ and one in $S^9$.
Cartan ends his third paper on the subject (Sur quelques familles remarquables d'hypersurfaces, C. R. Congres Math. Liege (1939), 30-41. Also in: Oeuvres Completes, Partie I11, Vol. 2, 1481-1492.) with three questions, one of which asking whether there exist isoparametric hypersurfaces in spheres with $g>3$ such that not all principal curvatures are equal. In 1971, Hsiang and Lawson published a paper (Minimal submanifolds of low cohomogeneity, J. Differential Geom. 5 (1971), 1-38.) including a classification of (maximal) subgroups of $SO(n+2)$ whose principal orbits have cohomogeneity $1$ in $S^{n+1}$, and remarked that they precisely coincide with the linear isotropy representations of symmetric spaces of rank two. In 1972, Takagi and Takahashi (On the principle curvatures of homogeneous hypersurfaces in a sphere, Differential Geometry, in Honor of K. Yano, Kinokuniya, Tokyo (1972), 469--481.) remarked that Hsiang-Lawson's result yields a classification of homogeneous isoparametric hypersurfaces in spheres and computed their invariants; in particular, they found examples with $g=4$ and unequal multiplicities.
The relation is that the principal orbits of the linear isotropy representations of symmetric spaces rank two (resp. arbitrary rank) yield beautiful examples of isoparametric hypersurfaces (resp. submanifolds) in spheres.
This relation is relatively easy to explain today. Cartan was the master of both subjects in the late 1930's. Is there anything interesting that can be said about the situation of differential geometry and Lie group theory at that time that prevented him to grasp this connection?
share|improve this question
4
This question reminds me of the many times I've seen something done by someone else and thought "Why didn't I think of that?" (because it seemed so obvious once it was pointed out); usually, I couldn't come up with any better answer than that I was thinking along different lines or about different examples. I imagine that even Cartan had this experience from time to time, and maybe he didn't have a better answer either. You can't think of everything, and some things are only 'obvious' in hindsight. – Robert Bryant Feb 9 at 23:13
Your Answer
discard
By posting your answer, you agree to the privacy policy and terms of service.
Browse other questions tagged or ask your own question.
|
__label__pos
| 0.958265 |
Redirect link is not available.
Back
How to create 3D assets for Metaverse
• The Ultimate Guide to Creating 3D Assets for Metaverse Applications
• How to Create High-Quality 3D Assets for Metaverse: A Comprehensive Guide
• From Concept to Creation: A Technical Guide to 3D Asset Creation for Metaverse
• Optimizing 3D Assets for Metaverse Applications: Best Practices and Techniques
• Creating 3D Assets for Metaverse: Techniques and Tips for Optimal Performance
The Metaverse has become a buzzword in recent years, and it is not hard to see why. The term has gained popularity recently, especially among young, tech-savvy individuals. It refers to a virtual world that is entirely immersive and interactive, where people can create, explore, and socialize in a digital environment that feels as real as the physical world. Moreover, it represents a future where we will be able to interact with digital worlds in ways that we can only dream of today. The Metaverse is still in its early stages, but it has the potential to change the way we interact with technology forever.
One essential component of the Metaverse is 3D assets. These digital objects are the building blocks of the virtual world, and they play a crucial role in creating immersive experiences for users. 3D assets are digital objects that can be used to create anything from buildings to characters, furniture to vehicles, and much more. These assets play a crucial role in creating immersive experiences for users. In the Metaverse, these assets will be used to create a vast, interconnected world where users can interact with each other and the environment. Without 3D assets, the Metaverse would not exist, and the experience would not be as immersive as it is intended to be.
Creating 3D assets for use in the Metaverse is a complex process that requires a deep understanding of 3D modeling, animation, and optimization. Today, we will explore the importance of 3D assets in Metaverse applications, the process of creating them, and best practices for optimizing their performance. We will cover the basics of 3D modeling, software options, rigging, animating, optimizing, and uploading 3D assets into Metaverse platforms. By the end of this, you will have a better understanding of the importance of 3D assets in the Metaverse and the best practices for creating them. So, let’s get started.
Understanding 3D Modeling
Before we dive into the creation process, it’s essential to understand the basics of 3D modelling. 3D modelling is the process of creating a digital representation of an object or scene in three dimensions. This means creating a wireframe structure of the object, adding surfaces and textures to it, and rendering it into an image or animation.
There are several software options available for 3D modelling, with Blender, Autodesk Maya, and Cinema 4D being the popular options. Each software has its strengths and weaknesses, and choosing the right one depends on the type of project and personal preferences. Choosing the right software depends on the type of project and personal preferences. It’s also important to choose the software that is suitable for Metaverse applications and can export 3D assets in a format that can be uploaded into Metaverse platforms.
When modelling 3D assets for the Metaverse, it’s crucial to maintain proper scale and proportions. In the virtual world, objects should be consistent with the physical world to create a sense of realism. For example, a door should be the same height as a standard door in the physical world. Maintaining proportions is also essential for ensuring that the 3D asset fits seamlessly into the virtual environment and interacts realistically with other objects. A 3D asset that is too large or too small will not look natural and can negatively impact the user’s experience.
In addition to proper scale and proportions, it’s important to consider the overall design and look of the 3D asset. The asset should be visually appealing and consistent with the theme or style of the virtual environment. It’s also important to consider how the asset will be used in the Metaverse. Will it be stationary, or will it have interactive elements? These factors can influence the design and functionality of the asset.
Creating 3D assets for the Metaverse can be a complex process, but following best practices can help ensure success. It’s important to start with a clear concept and reference images to guide the design process. Once the concept is established, the 3D model can be created using the chosen software. Proper scale and proportions should be maintained throughout the modelling process.
Creating 3D Models for Metaverse
When creating 3D models for the Metaverse, there are several considerations to keep in mind. Firstly, it’s essential to choose the right software for the job. As mentioned earlier, The software must have the ability to export 3D assets in a format that can be uploaded to Metaverse platforms. Some popular software options for 3D modelling include Autodesk 3ds Max, Blender, and SketchUp.
In addition to software choice, optimization is another essential consideration. 3D assets that are too complex or have too many polygons can cause performance issues in the Metaverse, leading to lag and other problems. Therefore, it is necessary to create optimized 3D assets that balance visual quality and performance.
To achieve optimized 3D assets, there are several tips that creators can follow. One such tip is to reduce the number of polygons in the model. Polygons are the small flat shapes that make up a 3D model, and reducing their number can significantly improve performance without sacrificing visual quality. Another useful technique is to create LODs (levels of detail) for the 3D model. This technique involves creating several versions of the same 3D asset with varying levels of complexity, each designed to be displayed at different viewing distances. This helps to improve performance by reducing the number of polygons and the amount of detail rendered on the user’s screen.
Optimizing textures and materials is also crucial for creating optimized 3D assets for the Metaverse. Textures and materials are what give 3D assets their appearance and can significantly impact performance if not optimized correctly. Creators can use tools such as Photoshop or Substance Painter to optimize textures and materials by reducing file sizes, creating UV maps, and adjusting lighting and shadows.
Overall, creating optimized 3D assets for the Metaverse is essential for ensuring smooth performance and an enjoyable user experience. By carefully considering software choice, optimizing 3D models, and textures and materials, creators can create high-quality assets that enhance the Metaverse experience.
Concept Development
Concept development is a critical part of the 3D asset creation process. It is the initial stage of 3D asset creation, where the designer or artist starts brainstorming and refining ideas for the asset. At this stage, they consider several factors that will influence the final design, including the purpose of the asset, the intended use, and the target audience. The designer also considers the overall aesthetic of the asset, ensuring that it aligns with the visual style of the application or platform where it will be used.
The first step in concept development is to generate ideas, which can be done using several techniques such as sketching, digital painting, or 3D modelling software. Sketching ideas on paper or a tablet allows the artist to iterate through multiple concepts and refine them quickly over time. Digital painting software, such as Procreate or Adobe Photoshop, is also useful for generating rough sketches or more detailed renderings of the asset.
It’s essential to use reference images and other resources during the concept development phase. Reference images help to ensure that the 3D asset is accurate and realistic, as they provide information on the shape, size, and details of the asset. References can be sourced from various places, such as photos, other 3D models, or real-life objects.
Moreover, concept development is also essential to ensure that the asset aligns with the vision of the project or platform. This phase involves reviewing the initial concepts with stakeholders, getting feedback, and refining the design further based on their inputs. It’s essential to keep the target audience in mind during this phase, as it influences the design elements such as colour schemes, textures, and details that will appeal to them.
Overall, concept development is an integral part of the 3D asset creation process. It helps to generate ideas and refine them based on feedback and reference images. A well-executed concept can ensure that the asset aligns with the project’s vision and meets the needs of the target audience.
Texturing and Materials
Texturing and materials are crucial for creating realistic and visually appealing 3D assets. Textures are 2D images that are applied to the surface of the 3D model to give it colour, detail, and texture. Materials refer to the physical properties of the object, such as its reflectivity, roughness, and transparency.
There are several tools available for creating textures and materials, including Substance Painter, Quixel Mixer, and Adobe Dimension. When creating textures and materials for the Metaverse, it is important to consider the performance impact of high-resolution textures and materials. High-resolution textures can cause longer loading times, reduced performance, and increased memory usage.
To optimize the textures and materials for Metaverse applications, it is important to follow a few best practices. Firstly, use efficient file formats such as PNG or JPEG. These formats have a smaller file size compared to other formats, which reduces the loading time and memory usage. Secondly, use texture compression techniques such as DXT, BC7, or ETC2, which further reduce the file size without affecting the image quality.
Another important consideration is the use of LODs (levels of detail) for textures and materials. LODs allow the system to use different versions of the same texture depending on the distance from the camera. For instance, a high-resolution texture may be used when the object is up close, while a low-resolution texture is used when the object is far away. This technique saves memory and reduces loading times, which is essential for optimal performance in the Metaverse.
When creating textures and materials, it is important to ensure that they are compatible with the 3D model’s UV mapping. UV mapping is the process of unwrapping the 3D model’s surface onto a 2D plane, allowing the texture to be applied accurately to the 3D model. If the UV mapping is incorrect, the texture may appear distorted or stretched.
In addition to UV mapping, it is important to consider the lighting in the Metaverse environment. The lighting can affect the appearance of the texture, and it is essential to test the texture and material under different lighting conditions to ensure that they appear as intended.
To create high-quality textures and materials, it is also important to use reference images and other resources to inform the design process. This can include photographs, sketches, or physical samples of the material being recreated. By using references, the artist can ensure that the texture and material appear realistic and accurate to the real-world counterpart.
One great example of the importance of textures and materials in the Metaverse can be seen in the video game industry. Video games have been utilizing 3D assets for decades and have continuously improved the quality of their textures and materials. Games such as Grand Theft Auto V, The Last of Us Part II, and Red Dead Redemption 2 have all received critical acclaim for their stunning visuals and attention to detail in their 3D assets. These games use high-resolution textures and materials to create a realistic and immersive environment that enhances the player’s experience.
Textures and materials are essential components of 3D asset creation for the Metaverse. By following best practices and utilizing the right tools, artists can create visually stunning and optimized textures and materials that enhance the overall experience of the Metaverse environment. As the Metaverse continues to grow and evolve, the demand for high-quality 3D assets will only increase, making it essential for artists to stay up to date with the latest techniques and technologies.
Animation for 3D Assets in Metaverse
Animation is a critical aspect of 3D asset creation for the Metaverse, allowing for assets to come to life and move in response to user interactions. To create animations for 3D assets, it’s essential to understand the rigging and animation processes.
Rigging is the process of adding a digital skeleton to a 3D model. The rigging process enables animators to create movements in a 3D model, much like the movements of a puppet. The rig is made up of a series of interconnected bones that are placed inside the 3D model, allowing the model to move in a similar way to a real-life creature. With the rig in place, the 3D asset can be animated using various tools such as Blender or Maya.
It’s important to optimize rigging and animation for performance in Metaverse applications to ensure that the 3D asset runs smoothly and efficiently in real-time environments. Rigging and animation can be optimized in several ways, including minimizing the number of bones in the rig, using efficient animation techniques, and using software that is optimized for real-time rendering.
In addition to optimizing the rigging and animation, it’s also important to follow best practices when creating 3D assets for the Metaverse. Some of the best practices include keeping the number of polygons in the 3D asset low to ensure smooth performance, using LODs (levels of detail) to reduce the complexity of the asset at different distances, and optimizing textures and materials for real-time rendering.
Ultimately, creating optimized animations for 3D assets in the Metaverse requires a solid understanding of the rigging and animation process, as well as a focus on performance optimization. By using the right tools and techniques, developers can create engaging and interactive 3D assets that perform efficiently and smoothly in the Metaverse.
Optimization
Optimization is a crucial aspect of creating 3D assets for use in Metaverse applications. When creating 3D assets, it’s essential to keep in mind that these assets will be used in a virtual world where the users’ experiences are dependent on the performance of the device they are using. Therefore, the 3D assets should be optimized to perform efficiently on a wide range of devices, including smartphones, tablets, laptops, and desktops.
One of the techniques for optimization is reducing the number of polygons in 3D assets. The more complex a 3D model is, the more polygons it has. While more polygons mean more details and smoother curves, it also means more computational power is needed to render the model, which can significantly impact the performance of the device. By reducing the number of polygons, the 3D asset can perform better while maintaining an acceptable level of detail.
Another technique for optimization is using LODs (levels of detail). LODs are used to reduce the complexity of 3D assets by creating several versions of the same model with varying levels of detail. For example, a 3D asset viewed from a distance doesn’t need as much detail as when viewed up close. Therefore, by having several versions of the same model with varying levels of detail, the 3D asset can perform better while maintaining the necessary level of detail based on the user’s viewing distance.
Textures and materials also play a significant role in the optimization of 3D assets for Metaverse applications. Textures and materials can significantly impact the performance of the device, especially if they are too large or too complex. To optimize textures and materials, it’s essential to use compression techniques to reduce the file size without compromising the quality. Additionally, the use of tiling textures can also help reduce the overall file size while maintaining the necessary level of detail.
Above all, optimization is a crucial aspect of creating 3D assets for use in Metaverse applications. By reducing the number of polygons, using LODs, and optimizing textures and materials, the 3D asset can perform better while maintaining the necessary level of detail. The ultimate goal of optimization is to ensure that the 3D asset can perform efficiently on a wide range of devices while providing an engaging and immersive experience for the user.
Uploading and Integrating 3D Assets into Metaverse
Uploading and integrating 3D assets into Metaverse platforms is the final step in the creation process. Once the 3D assets have been created, optimized, and tested, they need to be uploaded to the Metaverse platform of choice. This can be done through various means, such as directly uploading the asset to the platform or using third-party software.
Uploading 3D assets into Metaverse platforms requires knowledge of the specific platform’s requirements and restrictions. Each platform has its own file format, size limitations, and quality standards that need to be adhered to. For example, some platforms may require that the asset is in FBX format, while others may accept OBJ or glTF formats. Additionally, some platforms may have a file size limit, and exceeding this limit may result in the asset not being accepted.
Integrating 3D assets into Metaverse platforms involves placing the asset in the desired location and setting it up to interact with the environment and other assets. This can include adding physics properties to the asset, such as collision detection and setting up animations or interactive elements. The process of integration can vary depending on the platform and the complexity of the asset.
Common issues when uploading and integrating 3D assets into Metaverse platforms include compatibility issues, such as file format and size limitations, as well as issues with the asset’s performance, such as poor optimization or high polygon count. Other issues can include issues with texture mapping, incorrect scale or proportions, and errors in the rigging or animation.
To avoid these issues, it’s important to follow best practices when creating and optimizing 3D assets for use in the Metaverse. This includes testing the asset in various environments to ensure compatibility and performance, as well as adhering to the platform’s requirements and guidelines. Additionally, having a thorough understanding of the integration process and the platform’s tools and features can help to streamline the process and minimize issues.
Takeaway
Creating 3D assets for use in the Metaverse requires a comprehensive understanding of the entire creation process, from modeling to rigging and animating to optimizing for performance. We have covered the basics of 3D modeling and the importance of maintaining proper scale and proportions. We have also discussed the concept development process, the importance of texturing and materials, and the basics of rigging and animating 3D assets.
It’s important to remember that optimizing 3D assets for use in Metaverse applications is crucial for performance. This includes reducing the number of polygons, using LODs (levels of detail), and optimizing textures and materials. By following best practices for optimization, you can ensure that your 3D assets perform efficiently in the Metaverse.
As we look to the future of Metaverse 3D assets, we can expect to see an even greater demand for high-quality 3D assets that are optimized for use in the Metaverse. With advancements in technology and the increasing popularity of the Metaverse, 3D asset creators will need to stay up to date with the latest tools and techniques to create assets that meet the growing demand.
In conclusion, the creation of 3D assets for use in the Metaverse is a complex and challenging process, but it is also incredibly rewarding. By following best practices for 3D asset creation, you can create engaging and optimized assets that enhance the user experience in the Metaverse. As the Metaverse continues to grow, we can expect 3D asset creation to become an even more important aspect of digital content creation.
Comments
Leave a Reply
Your email address will not be published. Required fields are marked *
|
__label__pos
| 0.997261 |
Decision trees as expressions
if 0 {Richard Suchenwirth 2003-08-01 - Decision trees allow classification of an input in few steps. One can represent trees as nested lists, but it is also possible to use expr's peculiar x?y:z operator ("if x then y else z"), which can be nested, to represent a decision tree in such a way that it can be traversed in a single call to expr, and hence presumably more efficient than recursive Tcl code traversal of a nested list.
Assume we want to classify an integer between 0 and 3 with the two "Boolean" features
• even: divisible by 2 with zero remainder
• prime: >1 and divisible only by 1 and itself
The decision tree as nested list looks like this ("yes" branches come first):
{even {prime 2 0} {prime 3 1}}
which might be evaluated boringly as
if {$even} {
if {$prime} {
return 2
} else {
return 0
}
} else {
if {$prime} {
return 3
} else {
return 1
}
}
Now the following recursive procedure converts it into an expression in expr language, which looks like this:
$even? $prime? "2": "0": $prime? "3": "1"
The conditions (features) have been prefixed with a dollar sign for variable substitution; the result strings have been quoted so they can have other than numeric values. }
proc dtree2expr dtree {
if {[llength $dtree]==3} {
foreach {a b c} $dtree break
return "\$$a? [dtree2expr $b]: [dtree2expr $c]"
} else {
return \"$dtree\"
}
}
if 0 {Testing the thing goes with this silly framework, where the prime test was done very cheaply, but sufficient for the task at hand. If all went well, it should report its input back if called with 0..3, and make errors on other input... }
proc classifyNumber x {
#-- "feature extraction"
set even [expr {$x%2==0}]
set prime [expr {[lsearch {2 3 5 7 11 13 ..} $x]>=0}]
#-- "classification"
set dtree {even {prime 2 0} {prime 3 1}}
expr [dtree2expr $dtree]
}
Arts and crafts of Tcl-Tk programming
|
__label__pos
| 0.999625 |
Skip to content
Permalink
Branch: master
Find file Copy path
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
31 lines (17 sloc) 2.74 KB
Running Automation Workflows with Triggers using CloudWatch Events
You can start an Automation workflow by specifying an Automation document as the target of an Amazon CloudWatch event. You can start workflows according to a schedule, or when a specific AWS system event occurs. For example, let's say you create an Automation document named BootStrapInstances that installs software on an instance when an instance starts. To specify the BootStrapInstances document (and corresponding workflow) as a target of a CloudWatch event, you first create a new CloudWatch Events rule. (Here's an example rule: Service name: EC2, Event Type: EC2 Instance State-change Notification, Specific state(s): running, Any instance.) Then you use the following procedure to specify the BootStrapInstances document as the target of the event. When a new instance starts, the system runs the workflow and installs software.
For information about creating Automation documents, see Working with Automation Documents.
Use the following procedure to configure an Automation workflow as the target of a CloudWatch event.
To configure Automation as a target of a CloudWatch event
1. Sign in to the AWS Management Console and open the CloudWatch console at https://console.aws.amazon.com/cloudwatch/.
2. In the left navigation pane, choose Events, and then choose Create rule.
3. Choose Event Pattern or Schedule. Event Pattern lets you build a rule that generates events for specific actions in AWS services. Schedule lets you build a rule that generates events according to a schedule that you specify by using the cron format.
4. Choose the remaining options for the rule you want to create, and then choose Add target.
5. In the Select target type list, choose SSM Automation.
6. In the Document list, choose an Automation document to run when your target is invoked.
7. Expand Configure document version, and choose a version. $DEFAULT was explicitly set as the default document version in Systems Manager. You can choose a specific version, or use the latest version.
8. Expand Configure automation parameter(s), and either keep the default parameter values (if available) or enter your own values. Note
Required parameters have an asterisk (*) next to the parameter name. To create a target, you must specify a value for each required parameter. If you don't, the system creates the rule, but it won't run.
9. In the permissions section, choose an option. CloudWatch uses the role to start the Automation workflow.
10. Choose Configure details and complete the wizard.
You can’t perform that action at this time.
|
__label__pos
| 0.609046 |
[Piglit] shader_runner: ignoring uniforms in [test] header when location cannot be found instead of returning PIGLIT_FAIL
Abel Briggs abelbriggs1 at hotmail.com
Mon Jul 8 18:57:16 UTC 2019
Hi,
Recently, I've been working on scripts for a GLSL fuzz testing framework that use piglit's shader_runner to render shaders. As part of the test generation process, shaders can be generated that declare uniforms without using them (which is valid GLSL according to glslangvalidator). One of my scripts turns the shader and uniform data from the framework's test format into a shader_test file and runs it via shader_runner_gles3.
However, it seems that some of these unused uniforms are optimized away when the shader is compiled, and when shader_runner tries to use the uniform data in the [test] header, it can't find the location of the given uniform and throws an error.
Relevant code (there are similar pieces of code in the file for vertex and subuniforms):
piglit/tests/shaders/shader_runner.c, line 2289:
> loc = glGetUniformLocation(prog, name);
> if (loc < 0) {
> printf("cannot get location of uniform \"%s\"\n",
> name);
> piglit_report_result(PIGLIT_FAIL);
> }
I'd like to discuss whether it'd be possible to instead just ignore a piece of uniform data if the corresponding uniform can't be found in the compiled shader (I'd be willing to submit a patch for this).
Something like:
> loc = glGetUniformLocation(prog, name);
> if (loc < 0) {
> printf("cannot get location of uniform \"%s\"\n",
> name);
> return;
> }
>From my limited grepping of the code, there doesn't seem to be anything that would fail horribly if this were to be changed (as the setting of a uniform only occurs at the end of set_uniform, after various checks like this), but please correct me if I'm wrong about any of this.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.freedesktop.org/archives/piglit/attachments/20190708/5892e06d/attachment.html>
More information about the Piglit mailing list
|
__label__pos
| 0.694335 |
Resources Contact Us Home
Browse by: INVENTOR PATENT HOLDER PATENT NUMBER DATE
Method for reducing the rendering load for high depth complexity scenes on a computer graphics display
6052125 Method for reducing the rendering load for high depth complexity scenes on a computer graphics display
Patent Drawings:Drawing: 6052125-2 Drawing: 6052125-3 Drawing: 6052125-4 Drawing: 6052125-5
« 1 »
(4 images)
Inventor: Gardiner, et al.
Date Issued: April 18, 2000
Application: 09/003,938
Filed: January 7, 1998
Inventors: Gardiner; Harold Dee (Sandy, UT)
Urry; Russell Joseph (West Jordan, UT)
Assignee: Evans & Sutherland Computer Corporation (Salt Lake City, UT)
Primary Examiner: Powell; Mark R.
Assistant Examiner: Sealey; Lance W.
Attorney Or Agent: Thorpe, North & Western, LLP
U.S. Class: 345/421; 345/422; 345/426; 345/543
Field Of Search: 345/421; 345/422; 345/426; 345/507; 345/509
International Class:
U.S Patent Documents: 4825391; 5359704; 5471567; 5604849; 5870097; 5923333
Foreign Patent Documents:
Other References:
Abstract: A method and apparatus for rendering a real-time synthetic environment on a computer display. A hidden surface removal technique is provided which combines an efficient pixel rendering architecture with a simplified modeling process. Specifically, the computer pixel graphics hardware processing load is balanced against a software geometric load to obtain optimum rendering performance by utilizing a "full" buffer in combination with adaptations of the z-Buffer and priority-list algorithms.
Claim: What is claimed is:
1. A method for increasing a rate of rendering a synthetic image on a computer display, wherein the synthetic image is generated from a database of modeled primitives, saidmethod comprising the steps of:
(1) performing a plurality of geometric sorting calculations on the database of modeled primitives in the frame buffer to thereby prepare the synthetic image for rendering;
(2) bypassing rendering operations for frame buffer regions which are completely covered;
(3) recording frame buffer regions in a fall buffer which are correctly covered;
(4) monitoring a length of time required to render the synthetic image to determine if a rendering load is excessive; and
(5) increasing a number of eometric sortings being calculated if the rendering load is excessive to thereby decrease the rendering load.
2. The method for increasing the rendering rate as defined in claim 1 wherein the method further comprises the step of increasing the total number of geometric sorting calculations if the pixel rendering load:
(1) exceeds a geometric sorting load which is a total time required to perform the geometric sorting calculations; or
(2) exceeds a specified frame rate.
3. The method for increasing the rendering rate as defined in claim 2 wherein the method further comprises the step of balancing the rendering load and the geometric sorting load.
4. The method for increasing the rendering rate as defined in claim 2 wherein the method further comprises the step of minimizing a sum of the rendering load and the geometric sorting load.
5. The method for increasing the rendering rate as defined in claim 1 wherein the method further comprises the step of performing geometric sorting calculations only when the rendering load exceeds a geometric sorting load or frame time which isa total time required to perform the geometric sorting calculations.
6. The method for increasing the rendering rate as defined in claim 1 wherein the method further comprises the steps of:
(1) determining a relative size or closeness of the modeled primitives in the database;
(2) sorting the modeled primitives and selecting those primitives which meet a specified criteria defined as being equal to or greater than a selected size or closeness; and
(3) performing geometric sorting calculations on only the primitives selected in step (2).
7. The method for increasing a rendering rate as defined in claim 1 wherein the method further comprises the steps of:
(1) performing the plurality of geometric transformations in software; and
(2) simultaneously performing the rendering of the synthetic image in hardware.
8. The method for increasing the rendering rate as defined in claim 1 wherein the method further comprises the steps of:
(1) providing a reconfigurable memory structure or full buffer which contains a depth value associated with each pixel array in the frame buffer; and
(2) balancing the precision of the depth value against a total number of the pixel arrays.
9. The method for increasing the rendering rate as defined in claim 8 wherein the method further comprises the steps of decreasing a total number of bits allocated to the depth value when more pixel arrays are needed when the computer displayresolution increases, and increasing a total number of bits allocated to the depth value when less pixel arrays are needed when the computer display resolution decreases, or when only a subset of the computer display needs to be covered by the fullbuffer.
10. The method for increasing the rendering rate as defined in claim 1 wherein the method further comprises the steps of:
(1) providing a reconfigurable memory structure or full buffer which contains a depth value associated with each pixel array in the frame buffer; and
(2) initializing the full buffer using the scanning hardware also used for rendering pixels.
11. The method for increasing the rendering rate as defined in claim 10 wherein the method further comprises the step of initializing the depth values of the full buffer to any arbitrary values.
12. The method for increasing the rendering rate as defined in claim 1 wherein the method further comprises the step of bypassing shading calculations for pixels which will not be rendered.
13. A system for increasing a rate of rendering a synthetic image on a computer display, wherein the synthetic image is generated from a database of modeled primitives, said system comprising:
a reconfigurable full buffer memory which allocates memory space between pixel arrays and associated depth bits;
means for reallocating the memory space between the pixel arrays and the depth bits to thereby obtain either greater screen resolution or greater precision in a depth comparison;
means for sorting the modeled primitives such that the modeled primitives can be ordered relative to distance from an observation point; and
means for rendering pixels on the computer display such that the modeled primitives which are not obscured by other modeled primitives are visible within the synthetic image.
14. The system as defined in claim 13 wherein the means for reallocating the memory space between the pixel arrays and the depth bits further comprises a means for reallocating the full buffer memory such that any rectangular portion of theframe buffer memory can be represented.
15. The system as defined in claim 13 wherein the means for reallocating the memory space between the pixel arrays and the depth bits further comprises a means for preventing different software applications from interfering with each other ifthe software applications both want to utilize pixels stored in a same pixel array.
16. The system as defined in claim 13 wherein the system further comprises a means for initializing the reconfigurable full buffer memory with any arbitrarily selected value.
17. The system as defined in claim 16 wherein the means for initializing the reconfigurable frame buffer memory further comprises pixel scanning hardware which is also utilized to render pixels on the display, thereby efficiently utilizing acomputer resource.
18. The system as defined in claim 17 wherein the pixel scanning hardware is modified so as to be able to selectively input values into the full buffer or pixels into the frame buffer.
19. A method for increasing the rate of rendering three-dimensional synthetic images on a computer graphics display, wherein the synthetic images are generated by at least two applications which both want to utilize pixels stored in a same pixelarray of a frame buffer, said method comprising the steps of:
(1) rendering the synthetic images in a full buffer by utilizing pixels stored in at least one pixel array; and
(2) defining a status of the at least one pixel array in the full buffer which is shared by the applications as not being full, to thereby prevent interference by either application with the other.
20. A method for increasing a rate of rendering a synthetic image on a computer display, wherein the synthetic image is generated from a database of modeled primitives, said method comprising the steps of:
(1) determining which pixels require processing for each of the plurality of primitives;
(2) determining a closest pixel depth to each of the plurality of primitives being rendered, further comprising the steps of:
(i) determining a closest vertex of each of the primitives being rendered relative to the observer; and
(ii) determining a closest depth value for the primitive within a given pixel array; and
(3) comparing the closest depth value of the primitives requiring processing against depth values in a fall buffer to thereby determine if the pixels in the given pixel array do not require further processing, wherein shading calculations areconsequently terminated.
21. The method as defined in claim 20 wherein the step of determining a closest vertex of each of the primitives being rendered relative to the observer further comprises the step of comparing depth values at each vertex of the primitive tothereby locate a closest depth value.
22. The method as defined in claim 20 wherein the step of determining a closest value for the primitive within a given pixel array further comprises the steps of:
(1) determining if a closest point within the pixel array has a further depth value than a closest vertex; and
(2) utilizing the depth value of the closest array corner for the full buffer test if the closest array corner is further than the closest vertex, otherwise, utilizing the depth value of the closest vertex.
23. The method as defined in claim 22 wherein the step of determining whether the closest value for the primitive within a given pixel array has a further depth value than a closest vertex further comprises the step of utilizing a depth slopecomparison.
24. The method as defined in claim 23 wherein the method further comprises the step of making, a sign bit comparison to determine at which corner the depth value is to be calculated.
25. The method as defined in claim 24 wherein the method further comprises the steps of;
(1) comparing the closest depth value with a depth value already stored in the full buffer for each pixel array requiring processing for the primitive; and
(2) bypassing the array when the depth value is further than the recorded depth in the full buffer, otherwise, processing the pixel array to determine a shading value for each pixel and executing z-Buffer testing.
26. The method as defined in claim 25 wherein the method further comprises the steps of:
(1) monitoring a rendering process to determine if the primitives which are being recorded in the frame buffer completely fill any pixel arrays of the full buffer being processed;
(2) loading a maximum depth value of a primitive into the full buffer if the pixel array is completely filled; and
(3) overwriting an old full buffer depth value if the primitive completely fills the array, and the maximum depth value is closer than the depth value already in the buffer.
27. A method for recording values in a full buffer when accumulating a full status of a plurality of pixels processed in a pixel array, said method comprising:
(1) determining which pixels of the plurality of pixels require processing for each of the plurality of primitives;
(2) serially accumulating a full status of a plurality of pixels stored in at least one pixel array as the plurality of pixels are processed; and
(3) marking the pixel array as full if the plurality of pixels in the pixel array are determined to be full.
28. The method as defined in claim 27 wherein the method further comprises the step of comparing the depth value of the primitives requiring processing against depth values in a full buffer to thereby determine if the pixels in a region do notrequire further processing, wherein shading calculations are consequently terminated.
29. The method as defined in claim 28 wherein the method further comprises the step of determining a furthest pixel depth relative to each of the plurality of primitives being rendered.
30. The method as defined in claim 29 wherein the method further comprises the steps of:
(1) determining a furthest vertex of each of the primitives being rendered relative to the observer; and
(2) determining a furthest value for the primitive within a given pixel array.
31. The method as defined in claim 30 wherein the step of determining a furthest vertex of each of the primitives being rendered relative to the observer further comprises the step of comparing depth values at each vertex of the primitive tothereby locate a furthest depth value.
32. The method as defined in claim 30 wherein the step of determining a furthest value for the primitive within a given pixel array further comprises the steps of:
(1) determining if a furthest point within the pixel array has a further depth value than a furthest vertex; and
(2) utilizing the depth value of the furthest array corner for the full buffer test if the furthest array corner is further than the further vertex, otherwise, utilizing the depth value of the further vertex.
33. The method as defined in claim 32 wherein the step of determining whether the furthest value for the primitive within a given pixel array has a further depth value than a furthest vertex further comprises the step of utilizing a depth slopecomparison.
34. The method as defined in claim 33 wherein the method further comprises the step of making sign bit comparison to determine at which corner the depth value is to be calculated.
35. The method as defined in claim 34 wherein the method further comprises the step of determining the furthest vertex to store in the full buffer when non-bypassed primitives fill an array region.
36. The method as in claim 19 further comprising the step of initializing portions of the full buffer to closest possible depth values so rendering is avoided when those portions of depth buffer are covered by two dimensional graphics.
Description: BACKGROUND
1. The Field Of The Invention
This invention relates generally to generating two and three dimensional synthetic or virtual reality environments. More specifically, the present invention provides a new method for improving rendering performance by a computer's graphics ordisplay circuitry. By balancing the tasks of geometric computations and pixel rendering, the present invention combines the advantages of two distinct surface-removal strategies to obtain substantially faster graphics rendering.
2. The State Of The Art
Creating and manipulating a computer-generated synthetic or virtual environment in real-time can require substantial computing resources. Many factors influence the success of the synthetic environment to duplicate a desired reality. Forexample, one factor is the level of scene complexity of the desired synthetic environment. Another factor is the speed at which the synthetic environment must be rendered.
Techniques have been developed for the purpose of enhancing the synthetic environment experience. Enhancement of the synthetic environment is desirable for such purposes as generating a more complex and thus more realistic synthetic environment,or increasing the speed of the computer system to obtain a better real-time experience. However, these techniques for synthetic environment enhancement can be applied regardless of an application's requirements. Accordingly, these techniques mightgenerate the same synthetic environment while demanding less computer resources, or they might generate a more complex synthetic environment utilizing the same computer resources.
Of particular interest is the generation of a synthetic environment in a general purpose computer. As computer technology becomes more powerful, many performance problems that were once solved with dedicated hardware are now being solvedutilizing general purpose computers. However, one aspect of displaying a synthetic environment that still often requires dedicated hardware acceleration is that of rendering two and three dimensional computer graphics. Many computer programs havegraphics demands which require extremely high image rendering rates. Some applications, such as simulation in a synthetic environment even demands real-time rendering at 30 or even 60 frames per second. Nevertheless, even applications which can performadequately utilizing a software solution will always perform better with faster image rendering.
As processing power of computers increases, so do the expectations of the user. With respect to computer generated synthetic environments, the user's expectations are that scene complexity and hence realism, continue to increase. It is alsoexpected that these more complex scenes will still be rendered at 30 to 60 frames per second (fps). The advantages of a more realistic environment combined with consistent real-time performance thus extend far beyond the entertainment of a mere game. For example, the military applications of being able to train and test soldiers without the expense of using actual equipment and live ammunition reap substantial benefits.
Before a synthetic image can be rendered on a computer display, the scene must first be modeled in a format that the computer can utilize. Modeling techniques and tools describe the synthetic environment with primitives which can be rendered bythe graphics hardware. Renderable primitives often include such things a dots, lines and triangles. Sometimes, higher order surfaces such as polygons, meshes, strips, and surface patches are also supported. These are the lowest order of buildingblocks or primitives which can be put together to create a synthetic object or scene. Regardless of the method used to model the synthetic environment, the graphics hardware (or software) must convert those primitives into an array of pixels which canbe drawn on a display device. The process of converting modeled primitives into visible pixels on the computer display is the rendering process.
As the complexity of the synthetic environment increases, the demand on the rendering process likewise increases. As mentioned, dedicated hardware known as graphics accelerators are often used to improve the rendering performance for the morecomplex synthetic environments. However, this rendering hardware can become quite expensive because of the vast number of mathematical calculations that must be performed for each pixel. For software based solutions, the process can still be"expensive" in the sense that rendering time can become intolerably slow. This "expense" will be referred to often, and should be assumed to include that actual cost in money of accelerating hardware, or the cost in time when the solution is purelyaccomplished in software.
Another useful term which will also be referred to is a frame buffer. To render flicker-free synthetic images on a computer display, a double buffered frame buffer is typically used. Once the image has been rendered into one of the buffers, thebuffers can be swapped, allowing the image to be displayed on the screen while the next frame image is being rendered into the other buffer.
For a given computer display size, the number of frame buffer pixels which must be displayed remains constant. However, the number of pixels which must be processed in order to fill the frame buffer is highly dependent upon the complexity of thesynthetic scene. The ratio of the number of rendered pixels relative to the number of displaced pixels is known as the average pixel depth complexity. This ratio is an indication, on average, of how many primitives cover each pixel on the screen. Thepeak depth complexity would indicated the number of primitives which cover the pixel which is "touched" the most. These depth complexity values indicate how much effort goes into creating each synthetic image, and the values vary greatly depending onthe modeled environment and the current viewer's position within that environment.
For example, when rendering a region of mountainous terrain covered with trees as viewed from above, the average depth complexity will typically lie somewhere between one and two. The peak depth complexity may be two. Pixels only displaying theterrain require touching just once, whereas pixels covered by a tree require two touches, one for the tree and one for the terrain. If the viewer's position is now moved down within the trees with a line of sight towards the horizon, the depthcomplexity numbers will increase dramatically. This is because in the line of sight, any single pixel might have a hundred trees all lined up with the user's point of view. Thus, if the forest is quite dense, the average depth complexity may go up intothe tens, or even higher. Also, the complexity of the synthetic model affects depth complexity. The more complex the environment, the greater the average depth complexity.
In order to reduce the amount of hardware (or time) required to render a synthetic scene, or to enable more complex rendering with the same hardware (or within the same amount of time), a technique is needed which optimizes this synthetic scenerendering process. It would be an advantage if this technique were independent of the modeling process and primitive objects, and instead focused directly on the pixel rendering process.
Many computer graphics rendering systems in use today utilize a brute-force approach to convert modeled primitives into pixels. In other words, each primitive is taken, one at a time, and projected from three dimensional model coordinates (whenthe synthetic environment is three dimensional) into a two dimensional frame buffer memory. Part of this projection process includes calculating which pixels within the frame buffer are potentially touched by the primitive. Computing which pixels aretouched is a process known as scanning. As each pixel is selected by this scanning process, the color of the pixel must be computed. Computing the color can be very complex if sophisticated lighting algorithms and textures are being used. Typicalfactors contributing to the pixel's color include the following: the modeled color, light sources shining on the primitive, texture, anti-aliasing, and visibility conditions.
In addition to computing the color of the pixel, a means must be provided for determining which primitive in the synthetic scene should be visible for any given pixel (or sub-pixel if anti-aliasing techniques are employed). This process is oftenreferred to as hidden surface removal (i.e. removing all of the surfaces or primitives which are hidden by other surfaces which are closer to the observer). There are some common hidden surface removal techniques. These techniques include the painter'salgorithm, list-priority algorithms, scan-line algorithms, and the z-Buffering (or depth buffering) algorithm. Each of these techniques has distinct advantages and disadvantages. Some of these techniques require the database to be rendered in aparticular order, while others are order independent.
Unfortunately, rendering synthetic objects in a correct order on a computer display is not a trivial task. Determining which synthetic objects are in the foreground and which are in the background, and then displaying them in the proper orderrequires numerous calculations.
The painter's algorithm derives it's name from a common method of painting a picture. First, the background is painted, then objects which are less distant are painted, covering the more distant background, until finally the last objects paintedare those which are closest in the foreground. Likewise, the painter's algorithm for hidden surface removal uses a similar approach. First, the distance of each object from the viewer is determined, then each object is drawn, beginning with thefurthest and working toward the object which is closest in the foreground. While this method solves the problem of hidden surface removal, it raises several problems. First, sorting the primitives into the proper order in which the polygons must bedrawn is not a trivial matter. Second, a lot of time is wasted drawing objects which may be largely obscured when the foreground objects are rendered. Third, objects which are inter-penetrating cannot be properly rendered.
An alternative state of the art method for rendering objects on a display is the z-Buffer algorithm. This algorithm determines which points on which polygon primitives are closest to the viewer for every pixel (or sub-pixel) on the computerdisplay. It requires that the programmer set aside extra frame buffer memory to store the z (or depth) value for each pixel (or sub-pixel). Every time a point on the surface of the polygon is drawn into the frame buffer, the z coordinate of that pointis placed into this array. If the z coordinate in the buffer is closer than that of the new point, the new pixel is not drawn because that point would be farther away than the old point and is therefore part of a hidden surface. If the z coordinate inthe buffer is further than that of the new point, the new pixel is drawn over the old one and the z coordinate of the new point is put in the buffer, replacing the old one.
The z-Buffer algorithm has at least two drawbacks: time and memory. To implement the z-Buffer algorithm, it is necessary to keep track of a z coordinate for each pixel, and then do a comparison and a branch operation for every pixel. A loopingprocedure that uses so many branching operations is difficult to pipeline by a microprocessor, leaving it much slower than a simple and tight rendering loop.
Nevertheless, the z-Buffer algorithm, has a rather large advantage over just about all other known methods of hidden surface removal. As new polygon primitives are added to the synthetic scene, the amount of time consumed by the algorithm,increase linearly, not exponentially. Therefore, doubling the number of polygon primitives in the polygon list results in the time required to perform the z-Buffer algorithm also doubling (on the average). With other algorithms, the time may quadruple.
Other algorithms also typically require special modeling strategies and unique support structures in order to render the image properly. The z-Buffer approach eliminates most of these constraints, thereby simplifying the modeling process. Furthermore, complex situations such as inter-penetrating objects are correctly handled. Using the z-Buffer algorithm, the visible surface at each pixel is simply the primitive with the closest z value. As each primitive is rendered, this z parametercan be computed for each pixel touched. Along with storing the color of the pixel, the frame buffer is expanded to also store the z depth. As each new primitive is processed, the new z depth can be compared with the one already in the frame buffer. The frame buffer then simply keeps whichever primitive is closest to the observer. FIG. 1 shows a basic flowchart of a z-Buffered system.
One of the major disadvantages of the z buffer is that all of the color shading calculations are performed before the depth test is done, and the pixel may then be discarded by the frame buffer circuit. This required a lot of expensive (or timeconsuming) calculations to be performed with no final contribution to the image on the screen.
FIG. 1 shows that the relevant steps are as follows. In step 10, a database structure is evaluated. In step 12 geometric transformations are carried out. The next steps 14 and 16 are to accomplish pixel scanning and then pixel shading. Steps18 and 20 are repeated in a loop to accomplish hidden surface removal while each pixel of the frame buffer is analyzed. When the scene is completely rendered to the frame buffer, it is then moved to an output side of the frame buffer memory where thecompleted synthetic image appears on the computer display in step 22.
Some of the other state of the art hidden surface removal techniques have enabled more cost effective architectures to be developed. For example, with the list-priority approach, the primitives are rendered in a front-to-back order. Byrecording which pixels (or array of pixels) are filled up by the primitives as they are rendered, later primitives can be tested against this record in order to not waste time processing the primitive against pixels which are already full. Consequently,fairly simple structures can be built to maintain and test against this full record, thus throwing out pixels before the expensive color shading calculations are performed. Thus, even though the depth complexity of the synthetic scene may be quite high,many of the pixels which would otherwise be thrown away after processing are simply skipped. This list-priory approach is shown in FIG. 2.
In FIG. 2, the first two steps 24 and 26 are the same as steps 10 and 12 of the z-Buffer algorithm. However, step 28 is the step of pixel scanning. Then a loop begins with steps 30, 32 and 34 where the technique carries out hidden surfaceremoval, pixel shading and drawing to the frame buffer, respectively. As regions of the frame buffer are filled, data is fed back to the hidden surface removal section to prevent more distant primitives from being processed further. Finally, step 36transfers the frame buffer to display memory.
One major disadvantage of the list-priority approach shown in FIG. 2 is that primitives must be modeled in such a way as to guarantee that they can be sorted into priority order. In some cases, this can be extremely difficult to do. Thistechnique, like the painter's algorithm, does not support the notion of inter-penetrating primitives. Accordingly, the synthetic environments for which this technique can be used might be limited.
In general, the various hidden surface removal techniques provide either an efficient rendering architecture at the expense of complex modeling (e.g. the list-priority approach), or they simplify the modeling process at the expense of renderingefficiency (e.g. the z-Buffer algorithm).
Some recent systems have combined the "sort and record" schemes used previously by list-priority machines with the distinct modeling advantages of z-Buffered systems. This approach works well, but it is extremely expensive. First, largedatabase sorting mechanisms are utilized to get the primitives in approximately a front-to-back order. The z-Buffer then performs the final sorting of primitives that may have been too close for the earlier sorting process. The simple full buffer usedby the list-priority architectures is replaced with a more complex depth based record. As each array of pixels becomes full (i.e. fully covered by one or more fully opaque primitives), the furthest depth within the array is stored in the full record. Then, as new primitives are about to be rendered, their closest depth is compared with the record for all pixel regions that might need processing. If the new primitive's depth is further than that recorded in the full buffer, then that particular arrayof pixels need not be rendered.
The database sorting memories and controllers, the minimum and maximum depth calculations, and the depth based full buffer all add substantially to the cost of the system. The advantages gained by such an approach are particularly of value forapplications requiring true real-time performance since the rendering load will be much more level than on a system without such capabilities. Without a means to skip filled regions, the rendering load will be directly proportional to the depthcomplexity of the synthetic scene. By employing these "full schemes," the rendering load is more directly tied to the display's resolution and not so much to the orientation of the database. Unfortunately, this approach to combining a z-Buffer and afull buffer are far too costly for mainstream computer graphics systems.
Consequently, it would be an advantage over the prior art to provide a technique which eliminates the need for large and costly memories and control structures. It would be a further advantage to be able to build the full buffer and associatedcontrol logic circuits directly inside custom integrated circuits. Accordingly, it would be an advantage to greatly reduce the cost and complexity of such circuits and thereby make it more affordable for low cost, more mainstream, computer graphicshardware. Therefore, it would be an advantage to provide real-time synthetic scene rendering in computer systems costing much less than in past computer systems.
OBJECTS AND SUMMARY OF THE INVENTION
It is an object of the present invention to provide a method and apparatus for rendering a synthetic environment with minimized impact due to high scene depth complexity.
It is another object to provide a method and apparatus for hidden surface removal in a synthetic environment which combines an efficient rendering architecture with a simplified modeling process.
It is another object to provide a method and apparatus for balancing the tasks of geometric primitive sorting and pixel rendering to thereby obtain real-time synthetic image rendering.
It is another object to provide a method and apparatus for decreasing the pixel rendering load by increasing the number of geometric sorting calculations when pixel rendering becomes excessively high.
It is another object to provide a method and apparatus for optimizing a processing load on a computer system by minimizing the sum of the processing time required for pixel rendering and geometric sorting.
It is another object to provide a method and apparatus for accomplishing an adaptive sorting technique which only sorts geometric primitives when pixel rendering time becomes longer than the time to accomplish geometric sorting.
It is another object to provide a method and apparatus for adaptive sorting which does not order an entire database in a strict front-to-back order, but to instead render first the primitives that are nearest to the observer.
It is another object to provide a method and apparatus for sorting only the largest primitives by monitoring how large each primitive is on the display screen.
It is another object to provide a method and apparatus for increasing the geometric sorting as the pixel rendering load increases.
It is another object to provide a method and apparatus for utilizing a full buffer, wherein each memory location contains a depth value for an array of pixels on the display.
It is another object to provide a reconfigurable memory structure for the full buffer, such that as the frame buffer size increases (more pixels arrays to store), the fewer number of bits of depth are stored per array in the full buffer.
It is another object to provide a method and apparatus for sacrificing depth precision when a larger display must be covered.
It is another object to provide a method and apparatus for preventing different applications from interfering with each other on a display by never marking a pixel array as full which is shared by the applications.
It is another object to provide a method and apparatus for initializing a full buffer utilizing the same scanning hardware which is utilized to render pixels.
It is another object to provide a method and apparatus for initializing the full buffer to any arbitrary values.
It is another object to provide a method and apparatus for improved pixel rendering by skipping the shading calculations for pixels which will not be rendered, and by skipping large blocks of pixels at once.
The present invention is realized in a method and apparatus for rendering a real-time synthetic environment on a computer display. A hidden surface removal technique is provided which combines an efficient pixel rendering architecture with asimplified modeling process. Specifically, the computer graphics hardware pixel processing load is balanced against a software geometric primitive sorting load to obtain optimum rendering performance by utilizing a "full" buffer in combination withadaptations of the z-Buffer and list-priority algorithms.
In one aspect of the invention, an adaptive sorting method is provided which maintains a processing load balance between pixel rendering and geometric sorting of the database which stores the primitives in the synthetic environment. Maintainingthe balance enables parallel processing of the loads which results in a rapid display of the synthetic environment. Accordingly, this method only does as much optimization as is necessary, not as much as is possible.
In another aspect of the invention, a reconfigurable full buffer is provided which accommodates different screen resolutions by balancing the number of pixels which must be displayed against the bits of depth stored per pixel array.
In another aspect of the invention, a method is provided for enabling multiple applications to share the full buffer without interfering with each other.
In another aspect of the invention, a method is provided for fast full buffer initialization, where the memory can have any value stored therein using pixel scanning hardware.
These and other objects, features, advantages and alternative aspects of the present invention will become apparent to those skilled in the art from a consideration of the following detailed description taken in combination with the accompanyingdrawings.
BRIEF DESCRIPTION OF THE DRAWINGS
FIG. 1 is a flowchart of the steps of the prior art z-Buffer algorithm which are used in demonstrating the improvements of the present invention.
FIG. 2 is a flowchart of the steps of the prior art list-priority algorithm which are used in demonstrating the improvements of the present invention.
FIG. 3 is a flowchart which is provided to show greater detail of steps 10 and 12 from FIG. 1.
FIG. 4 is a flowchart of the steps of the presently preferred embodiment which is constructed in accordance with the principles of the present invention.
DETAILED DESCRIPTION OF THE INVENTION
Reference will now be made to the drawings in which the various elements of the present invention will be given numerical designations and in which the invention will be discussed so as to enable one skilled in the art to make and use theinvention. It is to be understood that the following description is only exemplary of the principles of the present invention, and should not be viewed as narrowing the claims which follow.
The object of the present invention is to render complex synthetic environments on a computer display either faster using a given amount of graphics hardware, or render more complex synthetic environments in the same amount of time that iscurrently required to render less complex synthetic scenes. As will be explained, the method above is accomplished by balancing the geometry calculations and the pixel rendering process of synthetic scenes with high depth complexity.
The process of generating a computer image consists of two primary tasks: geometric transformations and pixel rendering. FIG. 3 is provided to show greater detail of steps 10 and 12 from FIG. 1. FIG. 3 shows in a flowchart that the geometricoperations consists of 1) traversing the modeled database structure in step 40, 2) transforming the database primitives from model coordinates into screen coordinates in step 42, 3) clipping primitives which lie partially or totally outside the visibledomain in step 44, and 4) transferring the results to the pixel rendering hardware (or software) in step 46. The pixel operations, as discussed above, include scanning, lighting or shading, texturing, visibility, hidden surface removal, etc.
The time required to perform the geometric operations is primarily a function of the number of primitives being rendered, while the time to render the pixels is a function of the number of pixels needing to be rendered which is a function of thesize of the primitives as viewed on screen. When utilizing graphics acceleration hardware, these t-two processes can be performed in parallel. Consequently, the overall time required to render a synthetic scene will be limited by the worst case ofthese geometric and pixel rendering operations. Without the use of dedicated graphics hardware, the rendering time would be the sum of the time required to accomplish both tasks. It is important to note that the balance between a geometric processingload and pixel rendering load will vary depending upon the database structure and the viewer's position within that database. Therefore, a significant point of novelty of the present invention was the realization that if the processes are performed inparallel, and a balance is reached between the geometric processing load with respect to a pixel rendering load, the rendering process is significantly improved.
It is therefore made apparent that the present invention achieves its objective by providing a means for balancing the geometric processing and the pixel processing load via the full buffer. The full buffer represents the maximum depth value ofan array of pixels stored in the frame buffer. Thus, one item in the full buffer represents many items in the frame buffer; the full buffer is much smaller. Therefore, an "array" of pixels maps to one full buffer location. It is also noted thatlevel-of-detail management, perspective size culling, etc. are all techniques which can be utilized to help provide load balancing. However, none of these techniques provide direct control of the full buffer's effectiveness.
While it is true that with a full buffer, a synthetic scene will be rendered correctly regardless of the rendering order, that does not mean that the process is optimized. It is the case that the best efficiency is obtained when the order of theprimitives presented to the full buffer is front-to-back.
Another important implementation aspect of the present invention is that with the new technique, the amount of geometric sorting will vary depending upon the pixel rendering load. If the pixel rendering time becomes excessively high, thegeometric sorting calculations will increase, thus presenting more of the database in a front-to-back order. While this might seem counterproductive because the overall processing load is being increased even further, the end result is that the pixelrendering load will decrease. Accordingly, by devoting resources to carrying out special geometric sorting calculations, the pixel rendering process can be optimized until the geometric sorting and the pixel rendering processes reach an equilibrium. Inequilibrium, the sum is also said to be minimized. This is because when the processes are out of balance, it is not a linear change. In other words, there is not an equal give and take of time between the processes when there is an imbalance. Theprocess which is increasing in time actually increases an amount which is greater than the amount of time by which the other process might decrease.
FIG. 4 is presented to show in a flowchart the presently preferred embodiment of the present invention. The technique as outlined therein will be explained hereinafter as a series of processes (steps). However, by way of introduction, it isuseful to understand from the outset that in a cost-effective manner, the present invention provides the advantages of at least two distinct hidden surface removal strategies, that of the z-Buffer (FIG. 1) and the list-priority (FIG. 2) algorithms. There are four principle processes which are involved. They are geometric database sorting, initializing the full buffer, bypassing regions which are already full, and updating the record as regions are filled by primitives. Furthermore, there areseveral implementation techniques which have been developed to optimize the present invention's effectiveness at pixel rendering.
While reading the explanations to follow, it is useful to remember that the presently preferred embodiment fundamentally deviates from the state of the art through the use of: 1) adaptive geometric sorting which is used as required to maintainprocess load balance, 2) a reconfigurable full buffer memory structure to accommodate different display resolutions, 3) a method for allowing multiple applications to share the full buffer without interfering with each other, 4) fast full bufferinitialization to any value using pixel scanning hardware, 5) a method for computing depth at one region corner, and 6) sequential accumulation of full status.
Current state of the art techniques rely on more straight-forward, brute force approaches that cost significantly more to implement. The present invention relies on insights about the underlying processes. Rather than trying to solve allproblems all of the time, it advantageously solves only the most important problems, and only when they arise.
The means for obtaining a balanced processing load can be broken up into several processes, beginning with the geometric sorting process of the database. Because the pixel rendering architecture is based on a z-Buffer, it is not necessary tosort the database in order to render the correct image. However, with the use of a full buffer, the geometric sorting will allow the synthetic image to be rendered faster. This synthetic image can be rendered faster because the full buffer will rejectregions of the synthetic scene that do not require processing for any given primitive. Consequently, the pixel rendering performance can be very high if the primitives are processed in a front-to-back order. However, if the primitives are listed in areverse order, there will be no performance gain at all.
The above explanation would make it appear that one of the improvements provided by the present invention is to make it a combination of z-Buffer and list-priority technique. However, the present invention advantageously improves upon thecombination in that rather than being constrained by list-priority data structures or large and expensive sorting mechanisms, this new approach utilizes a sort-as-much-as-is-needed, or adaptive-sorting, technique.
Accordingly, if the pixel rendering time is acceptable (i.e. is shorter than the time to do the geometric sorting calculations or shorter than a desired frame time), no sorting is required. On average, without any sorting, about one half of thedatabase will already have a front-to-back order, with the other half in the reverse order. The accelerated graphics hardware will optimize the pixel rendering process as much as possible at all times. However, if the pixel rendering time starts toexceed the time required for geometric sorting (or frame time), the geometric sorting software can then turn to devoting time to sorting the database to thereby reduce the pixel rendering time.
It has been proven through experimentation that a small amount of geometric sorting can have a tremendous impact on the pixel rendering performance. In general, it is not necessary to render the entire database in a front-to-back order as in theprior art. Instead, it is better to first render only the first primitives that are at the front. In general, due to perspective, the up-front primitives will be quite large on the screen. Therefore, they will mark large portions of the screen asbeing full. Once a pixel array is marked full, it does not matter in what order the more distant primitives are processed because they will all be quickly rejected as being behind the nearer primitives.
It has also been discovered that by monitoring how large each primitive is on the display, it is possible to sort only the really large primitives. These are the primitives which when geometrically ordered will result in a large improvement inpixel rendering performance. For static imagery, or for slowly changing synthetic images, it is quite acceptable to use data from the previous synthetic image to determine which primitives to render first for the next synthetic image.
One of the advantages of this adaptive-sorting is that the computer system is free to completely balance geometric sort and pixel rendering loads. The higher the pixel rendering load, the more time can be spent on sorting the geometry. Accordingly, the computer system always runs at an optimum level.
A next improvement over the prior art is simplification in the full memory buffer itself. Each memory location in a "full" buffer contains a depth value for an array of pixels on the display. The exact size of the pixel array is not relevant tothe invention, but it does impact the computer system's overall performance. While small arrays are easily filled (or covered) by primitives, they require larger memories to cover the entire display, and they provide less of an advantage when aprimitive determines that it can skip those pixels. The larger the array, the larger the primitive must be to cover it, but more pixels can be skipped after each test, and better potential speed improvements are possible. As a practical matter,determining an optimum balance between how fast the arrays fill and how many pixels are skipped is dependent upon the database structure being displayed. Generally, making some compromise between how fast the arrays fill and the number of pixels whichare skipped is appropriate.
Storage to record the maximum depth value would require a full 32 bits (for floating point data) within each pixel array. For large screen sizes, and/or small array sizes, this can lead to a vast quantity of memory. However, the presentinvention was intended to fit inside an integrated circuit. Therefore, the memory had to be much smaller than the approach above would otherwise indicate. Furthermore, the memory had to be capable of operating with a vast number of frame buffer sizes. This is only logical because each application would be optimized differently depending upon the complexity of the synthetic environment to be displayed.
The present invention's solution to the problem of memory size is to advantageously provide a reconfigurable memory structure. As the frame buffer size increases (i.e. there are more pixel arrays to store), the fewer number of bits of depth arestored per array. Thus, based on the system's frame buffer configuration, the full buffer is configured to cover as much of the frame buffer as desired with as many bits of depth as will fit. In other words, to cover larger displays, precision in thedepth is sacrificed. Advantageously, by using appropriate depth metrics, this reduction in precision never causes a visual error, but may reduce the effectiveness of the circuit in skipping unneeded pixel rendering. Losing precision means thatprimitives which may reside very close together may not benefit from the full buffer. However, actual results have shown that, in general, the loss of performance is negligible.
In addition to providing configurable size and depth, the memory can be configured to cover any rectangular portion of the frame buffer as desired. Thus, if there are regions of the frame buffer that are not being utilized for high-speed pixelrendering, the memory can be allocated more effectively where it will contribute the most to improving performance.
Another advantage of the full buffer as described is that it inherently has the ability to prevent different applications from interfering with each other if they both touch pixels in the same pixel array. For example, on a standard PC orWorkstation, it is quite common to have multiple windows open with a different application running in each window. If two (or more) windows share a pixel full region, neither application should mark the array as full because this would falsely interferewith the other applications.
The discussion above related generally to the advantages of the full buffer. However, before the full buffer can be used, it must be properly initialized. The full buffer initialization process both clears out old data and sets up new data toinsure that the synthetic image will render properly. Without proper initialization, the full buffer may reject portions of primitives which should not be skipped, and an erroneous image will result.
In general, the full buffer is initialized to the furthest possible depth value. However, it is sometimes of value to initialize portions of the buffer to other depth values. For example, if an overlay image (i.e. pull down menus) coversportions of the synthetic image window, these areas can be initialized with the closest possible depth value so that no time is wasted rendering data which is hidden from view by the overlay image.
The present invention also makes possible the rapid initialization of the full buffer, regardless of its size and depth configuration. The full buffer can be initialized to any desired value, including a disable marker for regions which containmultiple windows.
To provide high-speed initialization, and to minimize the required support circuitry, the pixel scanning circuit can be set into a mode which scans pixel arrays rather than pixels. Advantageously, the same scanning hardware can be utilized toboth render the pixels and to initialize the full buffer.
In contrast, systems in the prior art have utilized a single valid flag per pixel array to indicate whether the data in the buffer is current. This single bit memory could quickly be cleared prior to rendering the synthetic image in order toinitialize the system. While this initialization scheme is fast, disadvantageously it requires special memory, and it cannot be initialized to any arbitrary value. The present invention allows each memory location in the full buffer to be initializedto any desired value, and it reuses existing circuitry to do this.
Once the full buffer has been initialized, the pixel rendering process can begin. The first step in rendering is to determine which pixels need processing for a given primitive. As these pixels are identified, they are tested against the fullbuffer to see if they can be skipped. The speed improvement comes from 1) skipping the shading and z buffer calculations for pixels which can be skipped, and 2) by skipping large blocks of pixels at once.
In order to carry out the full test described above, the closest depth to the primitive being rendered must be known. This is calculated in two steps. The first step is to find the closest vertex. The second step is to find the closest depthvalue within the array.
The first step, because the depth value is related to the z coordinate, makes it possible to find the closest point on the primitive by comparing the z values at each of the primitive vertices. It is not important to identify which vertex isclosest, but just to find its depth value.
The second step may refine this depth value to provide improved performance if the primitive is large, and covers many pixel arrays, it is extremely helpful to find the closest depth value within each array. Since all primitives are generallyplanar, it is possible to find the closest depth at only one of the array corners. If the closest array corner is further than the closest vertex, the corner's depth value can be used for the full buffer test. If the vertex depth value is further, thenthe vertex depth must be used.
Rather than calculate the depth value at each of the array corners and compare them to determine which is nearest (as is done in the prior art), the primitive's depth slope data can be used to point to the corner that will be the closest. Therefore, some simple sign bit comparisons can be utilized to determine at which corner the depth should be calculated.
Once the closest depth value of the primitive is determined, it can be compared with the depth value already stored in the full buffer for each array requiring pixel processing for the primitive. If the depth value is further than the recordeddepth, the array can be skipped. If not, the array must be processed to find the pixel's shading values, and then execute the entire z-buffer test.
As primitives which pass the full buffer test are rendered into the frame buffer, they are monitored to see if they completely fill any of the pixel regions being processed. If they do, their maximum depth value within the array may be loadedback into the full buffer. If the primitive completely fills the array, and its maximum depth is closer than the value already in the full buffer, the new primitive depth will overwrite the old value. Thus, the full buffer gets refined with the closerand closer primitives as needed in order to reject more of the database. This is why making primitives to be ordered in a front-to-back order can greatly impact performance. If the closest primitives are rendered first, they will record close-in depthvalues and thereby cause many of the more distant primitives to be quickly rejected. It should be apparent that partially transparent primitives must rot mark the array full since more distant primitives may still be visible in the pixels.
State of the art graphics systems which have utilized a full buffer have performed a full buffer update process by examining every pixel (and should be considered to include sub-pixels) within a selected portion of the frame buffer. A comparisonis made of the depth value for every pixel to determine the maximum depth within the array. This approach is very costly (in time or hardware) since many pixels must be accessed and compared in order to determine whether the array is completely coveredand at what maximum depth. Once the region is completely covered, it can be marked full, regardless of how many primitives it took to cover it.
In order to reduce size and cost of the full buffer, the present invention only marks a pixel array full if a single primitive completely covers the array, rather than a composite of multiple primitives. Furthermore, rather than compare depthvalues (often with 32 bit floating point data) at each pixel, a covered flag bit is accumulated as each pixel within the array is scanned. If the primitive completely covers every pixel in the array, the flag will indicate this, and the full buffer canbe updated with a new depth value. This sequential comparison of a single "covered" flag is substantially smaller and cheaper than the older approach of doing parallel comparisons of depth values.
Furthermore, rather than compare all of the z-Buffer depth values, we simply compute the depth at the appropriate corner of the array. As in the situation of determining the minimum depth, the primitive's slope value can be used to identifywhich corner will yield the maximum depth value.
Returning again to FIG. 4, it is seen that by checking for full regions early in the method, the expensive pixel shading operations do not have to be performed for areas that would simply be discarded by the z-Buffer. Primitives which requirerendering are constantly monitored and fed back in the loop to thereby keep the full buffer up to date and thereby maximize the circuits effectiveness.
Another aspect of the present invention is directed to the method and apparatus used to record information in the full buffer. It has been determined that it is advantageous to serially store values in pixel arrays within the full buffer ratherthan in parallel. In other words, the full status of every pixel within a pixel array is processed and serially accumulated. If all pixels in the pixel array are full, the pixel array is marked as full.
Another aspect of the present invention is related to the finding the closest or nearest point within a pixel array stored in the full buffer. Finding the closest or nearest point is useful to test when certain pixel arrays do not requireprocessing and are thus bypassed. It is also useful to determine the furthest point within a pixel array to store back in the full buffer. The furthest point is the opposite corner of the primitive relative to the closest point. The furthest point isstored in the full buffer when non-bypassed primitives fill an array region.
It is to be understood that the above-described arrangements are only illustrative of the application of the principles of the present invention. Numerous modifications and alternative arrangements may be devised by those skilled in the artwithout departing from the spirit and scope of the present invention. The appended claims are intended to cover such modifications and arrangements.
* * * * *
Recently Added Patents
Anthranilic diamide compositions for propagle coating
Memory system with data line switching scheme
Method and apparatus for providing contention-based resource zones in a wireless network
Evolutionary clustering algorithm
Fluid-borne particle detector
Implantable medical devices including elongated conductor bodies that facilitate device and lead configuration variants
Method and apparatus for organizing segments of media assets and determining relevance of segments to a query
Randomly Featured Patents
Automatic determination process for command and control of a forced draining before pressing for batch presses
Data distribution system and method of same, data processing apparatus and method of same, and data recording medium
Rotating disk storage device and pivot bearing
Spherical object supplying apparatus
Material splitter
APC gene and nucleic acid probes derived therefrom
Immunopotentiator
Evaporation fuel control apparatus for engine
Light receiving member having a multilayered light receiving layer composed of a lower layer made of aluminum-containing inorganic material and an upper layer made of non-single-crystal silico
Air purifier
|
__label__pos
| 0.934782 |
Categories
Swift SwiftUI
Gradient text in SwiftUI
If we want to spice up the user interface, then we can make some titles in the app to use gradient colours. In WWDC’21 Apple introduced an API for making gradient text styles easy to create. The .foregroundStyle() view modifier takes in a type which conforms to ShapeStyle protocol. One of these types are gradient types in SwiftUI. Therefore, creating a fun gradient text is a matter of creating a text and applying a foregroundStyle view modifier with a gradient on it.
let gradientColors: [Color] = [.purple, .blue, .cyan, .green, .yellow, .orange, .red]
Text("Hello, world!")
.font(.system(size: 60))
.foregroundStyle(
.linearGradient(
colors: gradientColors,
startPoint: .leading,
endPoint: .trailing
)
)
Text("Hello, world!")
.font(.system(size: 60))
.foregroundStyle(
.ellipticalGradient(
colors: gradientColors
)
)
Text("Hello, world!")
.font(.system(size: 60))
.foregroundStyle(
.conicGradient(
colors: gradientColors,
center: .center
)
)
Text("Hello, world!")
.font(.system(size: 60))
.foregroundStyle(
.radialGradient(
colors: gradientColors,
center: .center,
startRadius: 50,
endRadius: 100
)
)
view raw Text.swift hosted with ❤ by GitHub
The new view modifier is great, but it is iOS 15+, macOS 12.0+. Another way for achieving this result is recreating it ourselves. This involves in overlaying the text with gradient and then masking it with the text.
Text("Hello, world!")
.font(.system(size: 60))
.myForegroundStyle(
LinearGradient(
colors: gradientColors,
startPoint: .leading,
endPoint: .trailing
)
)
.padding()
.background(.black)
extension View {
func myForegroundStyle<Content: View>(_ content: Content) -> some View {
self.overlay(content).mask(self)
}
}
view raw Mask.swift hosted with ❤ by GitHub
If this was helpful, please let me know on Twitter @toomasvahter. Feel free to subscribe to RSS feed. Thank you for reading.
|
__label__pos
| 0.97496 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.