content
stringlengths 228
999k
| pred_label
stringclasses 1
value | pred_score
float64 0.5
1
|
---|---|---|
Take the 2-minute tour ×
Mathematics Stack Exchange is a question and answer site for people studying math at any level and professionals in related fields. It's 100% free, no registration required.
I got the following question:
How many numbers between 1 and 10,000,000 don't have the sequence 12? This is an inclusion-exclusion problem. Sadly I didn't fully understand its concept, so I tried solving it logically. I would like to know if my solution is correct, and if possible, how to solve it using the inclusion-exclusion principle.
Thanks!
So I said lets first find the numbers that do include the sequence 12, and divided it into cases:
Between 1 and 99: $1\cdot 1=1$
Between 100 and 999: $1\cdot 1 \cdot 10$ + $9\cdot 1 \cdot 1=19$
Between 1000 and 9999: $1 \cdot 1 \cdot 10 \cdot 10 + 2\cdot 9 \cdot 10 \cdot 1 \cdot 1 = 280$
Between 10000 and 99999: $1 \cdot 1 \cdot 10 \cdot 10 \cdot 10 + 3\cdot 9 \cdot 10 \cdot 10\cdot 1\cdot 1=3700$
Between 100000 and 999999: $1 \cdot 1 \cdot 10 \cdot 10 \cdot 10\cdot 10 + 4\cdot 9 \cdot 10 \cdot 10\cdot 10\cdot 1\cdot 1=46000$
Between 1000000 and 9999999: $1 \cdot 1 \cdot 10 \cdot 10 \cdot 10\cdot 10\cdot 10 + 5\cdot 9 \cdot 10 \cdot 10\cdot 10\cdot 10 \cdot 1\cdot 1=550000$
So the total of numbers that don't include the number 12 is: 10000000-550000-46000-3700-280-19=9400001
I don't havea final answer so I don't know if that correct. Obviousy this solution lacks elegance, so I would like to know how solve this problem using the inclusion-exclusion principle.
Thank in advance!
share|improve this question
Not sure if I know how to solve it efficiently or completely correctly, but as advice, take the between 1000-9999 range. I see what you did there: 1-2-X-X + X-1-2-X + X-X-1-2 = 1*1*10*10 + 9*1*1*10 + 9*10*1*1 = 280. But what if you had a number like 1212? That number overlaps in the first case and the third case, and you can only count it once, so that actually leaves you with 280-1 = 279, I hope that helps. – mathguy May 11 '13 at 15:29
Yes I see now. Thank you! – ohad May 11 '13 at 15:37
+1 for a well posed question and for showing your work – JavaMan May 11 '13 at 16:40
3 Answers 3
up vote 2 down vote accepted
So you have at most a 7-digit number (since 10,000,000 isn't a possibility): X-X-X-X-X-X-X, and the 12 can be in 6 different positions, so you have 1-2-X-X-X-X-X, X-1-2-X....,X-X-X-X-X-1-2. That is a total of $6*10^5 = 600,000$ different numbers. Now the hard part like I said above is finding the overlaps.
Suppose 12 were to appear twice, that means that we have 3 open spaces otherwise. How many ways can we reorder the two 12's and the extra 3 spots? That would be ${5\choose2} = 10$. Since the open spots can be $10^3$ different numbers, we end up with $10*10^3 =10,000$ overlaps.
Suppose 12 were to appear three times, that means we have 1 open space otherwise. How many ways can we reorder the three 12's and the extra spot? ${4\choose1} = 4$. Since the open spots can be 10 different numbers, we end up with $4*10 = 40$ overlaps.
However, if 12 were to appear three times, that means 12 also appears 2 times, and so instead of have $10,000$ overlaps (from the first overlap case), we actually have $10,000 - 40 = 9960$ total overlaps.
With $10,000,000$ different numbers, we end up with (total numbers - total overlaps) = $10,000,000 - (600,000-9960) = 9,409,960$ which I verified with Java.
share|improve this answer
I see. Thank you! Very nice solution. – ohad May 11 '13 at 16:03
Regarding the number of different numbers that include 12. – ohad May 11 '13 at 16:05
@mathguy good one. – Uma kant May 11 '13 at 16:08
All right you are at the first step of the inclusion-exclusion principle. You have just counted those numbers in which 12 appears at least once but in the process have overcounted. Your solution counts $1212$ twice, $121212$ thrice and so on.
By inclusion-exclusion principle, No. of numbers w/o $12$ = Total no. of numbers - No. of numbers with $1$2 at least once + No. of numbers with $12$ twice - No. of numbers with $12$ thrice + No. of numbers with $12$ four times and so on.
Total no: $10,000,000$
• $12$ at least once: $6*10^5$
• $12$ at least twice: $(4+3+2+1)*10^3$
• $12$ at least thrice: $((2+1)+(1))*10^1$
• $12$ four times and so on $=0$
• so ans= $10000000-600000+10000-40=9409960$
share|improve this answer
Welcome to MSE! It really helps to format questions/answers using MathJax (see FAQ). Regards – Amzoti May 11 '13 at 16:36
Keep track of the amount of $n$-digit numbers ending in $1$ and not ending in $1$, starting with $n=1$
$$ v_1 = \begin{pmatrix} 1 \\ 8 \end{pmatrix} $$
so $1+8 = 9$ numbers in total. The vector for $(n+1)$-digit numbers ending in $1$ and not ending in $1$ that do not contain the sequence "$12$" can be obtained by a recursion:
$$ v_{n+1} = \begin{pmatrix} 1 & 1 \\ 8 & 9 \end{pmatrix} v_n. $$
If $M$ is the matrix in the recursion above then there are $$ \begin{pmatrix} 1 & 1 \end{pmatrix}(M^{n-1} + M^{n-2} + \dotsc + 1) \begin{pmatrix} 1 \\ 8 \end{pmatrix} $$ numbers of at most $n$ digits that do not contain the sequence "$12$". For $n=7$ this becomes
$$ \begin{pmatrix} 1 & 1 \end{pmatrix}\begin{pmatrix}96031 & 106821 \\ 854568 & 950599 \end{pmatrix} \begin{pmatrix} 1 \\ 8 \end{pmatrix} = 9409959 $$ and including the number $10^7$ the final answer is $9409960$. Based on the above one can find a simpler linear recursion for the amount $a_n$ of numbers of at most $n$ digits that do not contain the sequence "$12$", namely
$$a_0 = 0, a_1=9 \textrm{ and } a_{n+2} = 10 a_{n+1} - a_n + 8.$$
This produces the sequence
$$0, 9, 98, 979, 9700, 96029, 950598, 9409959, 93149000, 922080049, \dotsc$$
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.997128 |
6
$\begingroup$
Let $(X,d)$ be a metric space and $\mathcal{M}(X)$ be the space of regular (e.g. Radon) measures on $X$. There are two standard topologies on $\mathcal{M}(X)$: The (probabilist's) weak topology and the strong norm topology, where the norm is the total variation norm.
Surprisingly, I have found very little discussion in the literature comparing these two topologies rigourously, besides the oft-cited claim that the norm topology is much stronger than the weak topology. I am looking for a reference that discusses and compares these topologies, esp. things like convergence, boundedness, open sets, projections, etc.
I am mostly concerned with probability measures $\mathcal{P}(X)\subset\mathcal{M}(X)$, but I am not sure how much of a difference this makes wrt topological concerns.
$\endgroup$
11
• 3
$\begingroup$ I vaguely recall that Richard M. Dudley has something on this somewhere. Try his book Probabilities and metrics. Convergence of laws on metric spaces, with a view to statistical testing. ... or maybe the book Real analysis and probability $\endgroup$ Jun 17 '19 at 11:58
• 1
$\begingroup$ Have you looked at Bogachev's Measure Theory? Section 4.6 discusses the norm topology, and Chapter 8 is all about the weak topology. If it doesn't have what you want, could you be more specific about what it is that you want? $\endgroup$ Jun 17 '19 at 15:16
• 4
$\begingroup$ @user64494 Can you please stop this kind of cosmetic edit? Let us instead respect the preference of the original poster if the intended meaning is clear. (FWIW, it is "according to", not "up to".) $\endgroup$
– Yemon Choi
Jun 17 '19 at 17:54
• 1
$\begingroup$ I am not the downvoter, but I can understand the downvote. The Wikipedia page on convergence of measures is quite extensive (e.g convergence is discussed, some claims on openness follow and I don't know what you have in mind with projections). So maybe the reason to vote to close was "unclear what you are asking"... Also, it is pretty straightforward to work out many things directly when you have a specific question on weak vs strong convergence. $\endgroup$
– Dirk
Jun 17 '19 at 18:38
• 3
$\begingroup$ That said: For me, what tells weak and strong convergence apart is the fact that the total variation distance of two diracs is always two (when they do not agree), but they converge weakly towards each other when the base points do. $\endgroup$
– Dirk
Jun 17 '19 at 18:39
4
$\begingroup$
A very good treatment of the subject can be found in "Topological Vector Spaces" by Helmut H. Schaefer.
If you have no previous experience at all with functional analysis, it may be a bit harsh in the beginning though. You can also learn first some more basic functional analysis, for example from the first 3 chapters of the classical book "Functional Analysis, Sobolev Spaces and Partial Differential Equations" by Haim Brezis (this is the route I have personally followed for example).
I expand on my answer in response to the comment
Note that first that, if $X$ is compact, then all continuous functions on $X$ are bounded. Therefore in this case the "probabilist's weak" topology on the space of finite Radon measures $\mathcal{M}(X)$ is just the weak* topology (in the usual sense of functional analysis) on $C(X)^*$ via the isomorphism $\mathcal{M}(X)\cong C(X)^*$. Therefore the comparison between the two topologies is clear in this case.
This does not work anymore if $X$ is not compact, and here is where the more specific approach of the probabilist comes into play. Let $\mathcal{P}(X)$ be the space of Borel probability on $X$. Then you can define a distance on $\mathcal{P}(X)$ by $$ d_P(\mu,\nu):=\inf\{\alpha>0\,:\,\mu(A)\le \nu(A_{\alpha})+\alpha,\, \mu(A)\le \nu(A_\alpha)+\alpha\},$$ where $$ A_\alpha=\begin{cases} \{x\in X\,:\,d(x,A)<\alpha\} & A\ne \emptyset,\\ \emptyset & A=\emptyset. \end{cases} $$ This is called Prokhorov distance, and you can prove that, provided $X$ being separable, the "probabilist's weak" topology is induced by the metric $d_P$.
If fact, in order to make the comparison you are interested in, it suffices to compare this metric with the one inducing the strong topology.
What makes things more complicated from a functional analitic point of view is that the metric $d_P$ is in general not induced by norm. It follows that the functional analysis you most commonly learn in your studies does not apply. Schaefer's book is all about extending those tools to the case in which a norm to start with is not available.
$\endgroup$
2
• $\begingroup$ Can you give a more specific reference within the H.H. Schaefer book? This is one of the first books I checked, and I only found one passing reference to total variation on p. 43. (To clarify: I am not referring to the usual norm vs. weak topology in functional analysis, but the corresponding more specific notions in probability theory.) $\endgroup$
– JohnA
Jun 17 '19 at 13:31
• 3
$\begingroup$ The topology defined by the Prokhorov distance is the weak-* topology on $\mathcal{P}(X)$ considered as a subspace of $C_b(X)^*$ (the dual of the bounded continuous functions). The embedding is $\mu \mapsto \left(f \mapsto \int_X f \mathrm{d}\mu\right)$. $\endgroup$ Jun 17 '19 at 20:14
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.509138 |
Which SQL Query expression?
0 Dave . · January 21, 2015
I need to create a spread sheet from an old database and I am not sure how to do one part. The spread sheet is to have the Person's name, Notes, address and all phone numbers assigned to them.
The issue is that the type of phone number is displayed as a number and not a name.
This is an MS SQL server
Database name Contacts
Tables with relevant data: Person, PersonAddress, Address, PersonContactMethod, ContactMethod and TelephoneNumber.
This code gives me the data I want but I would like ContactMethodId to display differently.
USE Contacts;
SELECT
Person.PersonId,
LastName,
FirstName,
MiddleName,
Note,
PersonContactMethod.ContactMethodTypeId, -- Field to display as Description
--ContactMethod.TelephoneNumberId,
Extension,
ExternalNumber,
--[Address].AddressId,
AddressTypeId,
IsPrimary,
Line1,
Line2,
City,
StateId,
Zip
From Person
LEFT JOIN PersonAddress
ON Person.PersonId=PersonAddress.PersonId
LEFT JOIN [Address]
ON PersonAddress.AddressId=[Address].AddressId
LEFT JOIN PersonContactMethod
ON Person.PersonId=PersonContactMethod.PersonId
LEFT JOIN ContactMethod
ON PersonContactMethod.ContactMethodId=ContactMethod.ContactMethodId
LEFT JOIN TelephoneNumber
ON ContactMethod.TelephoneNumberId=TelephoneNumber.TelephoneNumberId
ORDER BY LastName ASC;
ContactMethodId is a value 1 - 58
I would like it to display as a name
The name is in Table ContactMethodType column "Description".
What code can I add to the above to display this data for ContactMethodId?
ContactMethodTypeIdDescription
1Home Email Address
2Home Phone Number
3Other Email Address
4Other Email Pager
5Other Work Phone Number
6Personal Homepage
7Phone Pager
8Primary Extension
9Text Messaging
10Work Email Address
Thanks for any help
Post a Reply
Replies
Oldest Newest Rating
0 Nikola Novakovic · January 22, 2015
You should be able to do something like
PersonContactMethod.ContactMethodTypeId AS Description
THis should alias the column you want. Basically it will rename the colon when its showed somewhere in the output.
Here is the link to the more info:
https://technet.microsoft.com/en-us/library/ms187455(v=sql.105).aspx
+1 Dave . · January 24, 2015
I found it
By using the CASE function I was able to add the description into the list.
PersonContactMethod.ContactMethodTypeId,
Description = CASE PersonContactMethod.ContactMethodTypeId
WHEN 1 THEN 'Home Email Address'
WHEN 2 THEN 'Home Phone Number'
WHEN 3 THEN 'Other Email Address'
WHEN 4 THEN 'Other Email Pager'
WHEN 5 THEN 'Other Work Phone Number'
WHEN 6 THEN 'Personal Homepage'
WHEN 7 THEN 'Phone Pager'
WHEN 8 THEN 'Primary Extension'
WHEN 9 THEN 'Text Messaging'
WHEN 10 THEN 'Work Email Address'
WHEN 11 THEN 'Work Email Pager'
WHEN 14 THEN 'Secondary Extension'
WHEN 43 THEN 'Tertiary Extension'
WHEN 44 THEN 'Fax'
WHEN 45 THEN 'Mobile Phone'
WHEN 46 THEN 'Alpha Pager'
WHEN 50 THEN 'External Primary Number'
WHEN 51 THEN 'External Secondary Number'
WHEN 52 THEN 'External Tertiary Number'
WHEN 53 THEN 'Wireless'
WHEN 54 THEN 'External Fax'
WHEN 55 THEN 'Assured Mobility Cell'
WHEN 56 THEN 'Assured Mobility WiFi'
WHEN 57 THEN 'Voice Mail'
WHEN 58 THEN 'Instant Messaging'
ELSE 'Not here now'
END,
This helps but I think I can refine the statement more to make the output closer to what I need to input into the new server.
+2 Dave . · January 24, 2015
This is the icing on the cake
It creates a new column (same name I need to do the import) and places the appropriate value in it.
StationNumber = CASE PersonContactMethod.ContactMethodTypeId
WHEN 8 THEN Extension
ELSE NULL
END,
StationNumber = CASE PersonContactMethod.ContactMethodTypeId
WHEN 14 THEN Extension
ELSE NULL
END,
StationNumber = CASE PersonContactMethod.ContactMethodTypeId
WHEN 43 THEN Extension
ELSE NULL
END,
WirelessNumber = CASE PersonContactMethod.ContactMethodTypeId
WHEN 53 THEN Extension
ELSE NULL
END,
MobileNumber = CASE PersonContactMethod.ContactMethodTypeId
WHEN 45 THEN E164Number
ELSE NULL
END,
HomeNumber = CASE PersonContactMethod.ContactMethodTypeId
WHEN 2 THEN E164Number
ELSE NULL
END,
ExternalFax = CASE PersonContactMethod.ContactMethodTypeId
WHEN 54 THEN E164Number
ELSE NULL
END,
ExternalPrimary = CASE PersonContactMethod.ContactMethodTypeId
WHEN 50 THEN E164Number
ELSE NULL
END,
ExternalSecondary = CASE PersonContactMethod.ContactMethodTypeId
WHEN 51 THEN E164Number
ELSE NULL
END,
AlphaPager = CASE PersonContactMethod.ContactMethodTypeId
WHEN 46 THEN E164Number
ELSE NULL
END,
• 1
SQL & Databases
126,497 followers
About
Everything SQL and Databases related in here!
Links
Moderators
Bucky Roberts Administrator | __label__pos | 0.815779 |
唯品秀前端博客
当前位置: 前端开发 > JavaScript > js时间戳完美转换成阴历农历格式
js时间戳完美转换成阴历农历格式
2019-04-28 分类:JavaScript 作者:管理员 阅读(1583)
似乎在实际项目中我们不常见需要将时间转换成阴历,但存在必有道理,下面说下怎么转换成阴历
具体代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
function showCal() {
var D = new Date();
var yy = D.getFullYear();
var mm = D.getMonth() + 1;
var dd = D.getDate();
var ww = D.getDay();
var ss = parseInt(D.getTime() / 1000);
if (yy < 100) yy = '19' + yy;
return GetLunarDay(yy, mm, dd);
}
//定义全局变量
var CalendarData = new Array(100);
var madd = new Array(12);
var tgString = '甲乙丙丁戊己庚辛壬癸';
var dzString = '子丑寅卯辰巳午未申酉戌亥';
var numString = '一二三四五六七八九十';
var monString = '正二三四五六七八九十冬腊';
var weekString = '日一二三四五六';
var sx = '鼠牛虎兔龙蛇马羊猴鸡狗猪';
var cYear, cMonth, cDay, TheDate;
CalendarData = new Array(
0xa4b,
0x5164b,
0x6a5,
0x6d4,
0x415b5,
0x2b6,
0x957,
0x2092f,
0x497,
0x60c96,
0xd4a,
0xea5,
0x50da9,
0x5ad,
0x2b6,
0x3126e,
0x92e,
0x7192d,
0xc95,
0xd4a,
0x61b4a,
0xb55,
0x56a,
0x4155b,
0x25d,
0x92d,
0x2192b,
0xa95,
0x71695,
0x6ca,
0xb55,
0x50ab5,
0x4da,
0xa5b,
0x30a57,
0x52b,
0x8152a,
0xe95,
0x6aa,
0x615aa,
0xab5,
0x4b6,
0x414ae,
0xa57,
0x526,
0x31d26,
0xd95,
0x70b55,
0x56a,
0x96d,
0x5095d,
0x4ad,
0xa4d,
0x41a4d,
0xd25,
0x81aa5,
0xb54,
0xb6a,
0x612da,
0x95b,
0x49b,
0x41497,
0xa4b,
0xa164b,
0x6a5,
0x6d4,
0x615b4,
0xab6,
0x957,
0x5092f,
0x497,
0x64b,
0x30d4a,
0xea5,
0x80d65,
0x5ac,
0xab6,
0x5126d,
0x92e,
0xc96,
0x41a95,
0xd4a,
0xda5,
0x20b55,
0x56a,
0x7155b,
0x25d,
0x92d,
0x5192b,
0xa95,
0xb4a,
0x416aa,
0xad5,
0x90ab5,
0x4ba,
0xa5b,
0x60a57,
0x52b,
0xa93,
0x40e95
);
madd[0] = 0;
madd[1] = 31;
madd[2] = 59;
madd[3] = 90;
madd[4] = 120;
madd[5] = 151;
madd[6] = 181;
madd[7] = 212;
madd[8] = 243;
madd[9] = 273;
madd[10] = 304;
madd[11] = 334;
function GetBit(m, n) {
return (m >> n) & 1;
}
//农历转换
function e2c() {
TheDate = arguments.length != 3 ? new Date() : new Date(arguments[0], arguments[1], arguments[2]);
var total, m, n, k;
var isEnd = false;
var tmp = TheDate.getYear();
if (tmp < 1900) {
tmp += 1900;
}
total = (tmp - 1921) * 365 + Math.floor((tmp - 1921) / 4) + madd[TheDate.getMonth()] + TheDate.getDate() - 38;
if (TheDate.getYear() % 4 == 0 && TheDate.getMonth() > 1) {
total++;
}
for (m = 0;; m++) {
k = CalendarData[m] < 0xfff ? 11 : 12;
for (n = k; n >= 0; n--) {
if (total <= 29 + GetBit(CalendarData[m], n)) {
isEnd = true;
break;
}
total = total - 29 - GetBit(CalendarData[m], n);
}
if (isEnd) break;
}
cYear = 1921 + m;
cMonth = k - n + 1;
cDay = total;
if (k == 12) {
if (cMonth == Math.floor(CalendarData[m] / 0x10000) + 1) {
cMonth = 1 - cMonth;
}
if (cMonth > Math.floor(CalendarData[m] / 0x10000) + 1) {
cMonth--;
}
}
}
function GetcDateString() {
var tmp = '';
/*显示农历年:( 如:甲午(马)年 )*/
/*tmp+=tgString.charAt((cYear-4));
tmp+=dzString.charAt((cYear-4));
tmp+="(";
tmp+=sx.charAt((cYear-4));
tmp+=")年 ";*/
if (cMonth < 1) {
tmp += '(闰)';
tmp += monString.charAt(-cMonth - 1);
} else {
tmp += monString.charAt(cMonth - 1);
}
tmp += '月';
tmp += cDay < 11 ? '初' : cDay < 20 ? '十' : cDay < 30 ? '廿' : '三十';
if (cDay % 10 != 0 || cDay == 10) {
tmp += numString.charAt((cDay - 1) % 10);
}
return tmp;
}
function GetLunarDay(solarYear, solarMonth, solarDay) {
//solarYear = solarYear<1900?(1900+solarYear):solarYear;
if (solarYear < 1921 || solarYear > 2020) {
return '';
} else {
solarMonth = parseInt(solarMonth) > 0 ? solarMonth - 1 : 11;
e2c(solarYear, solarMonth, solarDay);
return '阴历' + GetcDateString();
}
}
this.lunarCalendar = '农历' + showCal() + ' ';
上面代码本来是用在vue.js项目中的,直接丢到函数中,然后去调用即可,通过this.lunarCalendar就能拿到当前时间转换好的阴历格式,你也可以改成自己去传参形式得到你想转换的时间。
「三年博客,如果觉得我的文章对您有用,请帮助本站成长」
赞(4) 打赏
谢谢你请我吃鸡腿*^_^*
支付宝
微信
4
谢谢你请我吃鸡腿*^_^*
支付宝
微信
上一篇:
下一篇:
你可能感兴趣
3 条评论关于"js时间戳完美转换成阴历农历格式"
1. fuTure Windows NT Chrome 83.0.4103.97
if (solarYear 2020) {
return '';
}
这里为啥要大于2020 return ''呢
1. 管理员 Windows NT Chrome 57.0.2987.98
@fuTure时间区间问题,因为目前是2020年,你所选不可能超出这个时间吧,当然,代码是根据你的业务来,你可以去掉限制
2. Stt-699 Windows NT Chrome 75.0.3770.100
文章很不错!
博客简介
唯品秀博客: weipxiu.com,一个关注Web前端开发技术、关注用户体验、坚持更多原创实战教程的个人网站,愿景:成为宇宙中最具有代表性的前端博客,期待您的参与,主题源码
精彩评论
友情链接
他们同样是一群网虫,却不是每天泡在网上游走在淘宝和网游之间、刷着本来就快要透支的信用卡。他们或许没有踏出国门一步,但同学却不局限在一国一校,而是遍及全球!申请交换友链
站点统计
• 文章总数: 258 篇
• 草稿数目: 0 篇
• 分类数目: 16 个
• 独立页面: 6 个
• 评论总数: 907 条
• 链接总数: 17 个
• 标签总数: 459 个
• 注册用户: 8149 人
• 访问总量: 9203255 次
• 最近更新: 2020年7月3日
服务热线:
173xxxx7240
QQ在线交流
旺旺在线 | __label__pos | 0.992278 |
利用MySQL Cluster 7.0 + LVS 搭建高可用环境
目录:
1、前言
随着数据量规模的扩大,企业对 MySQL 的要求就不仅仅是能用了,也在寻求各种高可用方案。以前我们的大部分高可用方案其实还存在一定缺陷,例如 MySQL Replication 方案,Master 是否存活检测需要一定时间,而和 Slave 的切换也需要时间,因此其高可用程度较大依赖监控软件或自动化管理工具。而早先的 MySQL Cluster 实在不能令人满意,性能差的不行,也让我们的期待一次次落空。本次 MySQL Cluster 7.0 的推出,终于实现了质的飞跃,性能上得到了很大提高。MySQL Cluster 7.0 新特性主要体现在以下几个方面:
• 数据节点多线程
• 可以在线增加节点
• 大记录存取改进
• 支持windows平台
本身MySQL Cluster已经实现了高可用,不过由于SQL节点无法对外部负载均衡,因此我们采用 LVS 来实现这一需求。
2、安装
环境描述:
内核:2.6.9-78.0.17.ELsmp
硬件:DELL 2950, 146G 15K RPM SAS * 6(raid 1+0), 8G Ram
各个节点描述:
IP 描述
192.168.0.2 ndb mgm node
192.168.0.3 data node1, sql node 1, LVS DR Server
192.168.0.4 data node2, sql node 2
192.168.0.5 data node3, sql node 3
192.168.0.6 data node4, sql node 4
192.168.0.7 sql node 5
192.168.0.8 sql node 6
192.168.0.9 sql node 7
192.168.0.10 sql node 8
是这样安排这些服务器的,192.168.0.2 作为 MySQL Cluster 的管理节点,2 ~ 6 既做数据节点(DATA node),也做SQL节点(SQL node),7 ~ 10 也做SQL节点。LVS采用 VS/DR 的模式,因此把 192.168.0.2 也同时作为 LVS 的 DR Server
分配好机器,接下来就是安装响应的软件包了。
2.1 LVS 安装、配置
老实说,我对LVS并不十分在行,以前折腾过一次,差点快崩溃了,后来才发现是我下载的版本太高了,没想到这次也是这样 :(,白折腾了1天。其实过程比较简单,只要下载的版本能对的上就快了。
在这里,我下载的是源码rpm包,因此需要用rpmbuild编译一次。
[[email protected] ~]# rpm -ivhU ~/kernel-2.6.9-78.0.17.EL.src.rpm
[[email protected] ~]# cd /usr/src/redhat/SPECS
[[email protected] ~]# rpmbuild -bp kernel-2.6.spec #解开源码包,打上各种pache
[[email protected] ~]# rpm -ivhU ~/ipvsadm-1.24-5.src.rpm #安装ipvsadm的源码包
[[email protected] SPECS]# ls
ipvsadm.spec kernel-2.6.spec
#需要做一下链接,编译ipvsadm时用得着
[[email protected] SPECS]# ln -s /usr/src/redhat/BUILD/kernel-2.6.9/linux-2.6.9 /usr/src/linux
[[email protected] SPECS]# rpm -bb ipvsadm.spec #编译出ipvsadm的rpm包
[[email protected] SPECS]# ls -l /usr/src/redhat/RPMS/x86_64/
total 36
-rw-r--r-- 1 root root 30941 May 4 18:06 ipvsadm-1.24-5.x86_64.rpm
-rw-r--r-- 1 root root 2968 May 4 18:06 ipvsadm-debuginfo-1.24-5.x86_64.rpm
[[email protected] ~]# rpm -ivhU /usr/src/redhat/RPMS/x86_64/ipvsadm-1.24-5.x86_64.rpm
看到了吧,其实很简单。网上的有些资料说要把 ipvsadm.spec 中的 Copyright 这个 Tag 改成 License,可能是因为版本较老,我用的这个版本就不需要这样。
接下来就是加载 ip_vs 模块,然后开始做 LVS DR 转发了。
[[email protected] ~]# /sbin/modprobe ip_vs
[[email protected] ~]# lsmod | grep ip_vs
ip_vs 103169 3 ip_vs_rr
直接编辑 /etc/sysconfig/ipvsadm 文件:
[[email protected] ~]# cat /etc/sysconfig/ipvsadm
-C
-A -t lvs_vip:mysql -s rr
-a -t lvs_vip:mysql -r ndb_data_node_1:mysql -g -w 1
-a -t lvs_vip:mysql -r ndb_data_node_2:mysql -g -w 1
-a -t lvs_vip:mysql -r ndb_data_node_3:mysql -g -w 1
-a -t lvs_vip:mysql -r ndb_data_node_4:mysql -g -w 1
-a -t lvs_vip:mysql -r ndb_sql_node_1:mysql -g -w 1
-a -t lvs_vip:mysql -r ndb_sql_node_2:mysql -g -w 1
-a -t lvs_vip:mysql -r ndb_sql_node_3:mysql -g -w 1
-a -t lvs_vip:mysql -r ndb_sql_node_4:mysql -g -w 1
保存退出。上面显示的是 hostname 的格式,因为我都在 /etc/hosts 里设置各自对应的 hostname 了。
然后就是在 DR Server 上绑定 vip,然后打开 ip_forward,启动 ipvsadm,LVS 就可以开始工作了。
[[email protected] ~]# echo 1 > /proc/sys/net/ipv4/ip_forward #修改内核,打开转发
[[email protected] ~]# /sbin/ifconfig eth0:0 192.168.0.11 netmask 255.255.255.0 #绑定vip
[[email protected] ~]# /etc/init.d/ipvsadm start #启动ipvsadm
[[email protected] ~]# ipvsadm -L #查看列表
ipvsadm -L
IP Virtual Server version 1.2.0 (size=4096)
Prot LocalAddress:Port Scheduler Flags
-> RemoteAddress:Port Forward Weight ActiveConn InActConn
TCP lvs_vip:mysql rr
-> gs_ndb_sql_node_1:mysql Route 1 0 0
-> gs_ndb_sql_node_2:mysql Route 1 0 0
-> gs_ndb_sql_node_3:mysql Route 1 0 0
-> gs_ndb_sql_node_4:mysql Route 1 0 0
-> gs_ndb_data_node_1:mysql Route 1 0 0
-> gs_ndb_data_node_2:mysql Route 1 0 0
-> gs_ndb_data_node_3:mysql Route 1 0 0
-> gs_ndb_data_node_4:mysql Route 1 0 0
[[email protected] ~]# lsmod | ip_vs #查看已加载模块
lsmod | grep ip_vs
ip_vs_rr 3649 1
ip_vs 103169 3 ip_vs_rr
DR Server 上设置完后,再在 Real Server 上绑定 vip,然后测试,没问题的话,就可以用了。
[[email protected] ~]# /sbin/ifconfig lo:0 192.168.0.11 netmask 255.255.255.255 broadcast 192.168.0.11
#设定noarp
[[email protected] ~]# echo '2' > /proc/sys/net/ipv4/conf/lo/arp_announce;echo '1' > /proc/sys/net/ipv4/conf/lo/arp_ignore;echo '2' > /proc/sys/net/ipv4/conf/all/arp_announce;echo '1' > /proc/sys/net/ipv4/conf/all/arp_ignore
2.2 MySQL Cluster安装
MySQL Cluster的安装重点在于管理节点的配置文件,只要把配置文件设置好了,其他的就很快了。我在这里是直接用 rpm 包安装的,因为下载整个预编译好的 tar.gz 文件实在太大了,这点上 MySQL 是越来越臃肿了 :(
[[email protected] ~]# cat /home/mysql/config.ini
[TCP DEFAULT]
SendBufferMemory=2M
ReceiveBufferMemory=2M
[NDB_MGMD DEFAULT]
PortNumber=1186
Datadir=/home/mysql/
[NDB_MGMD]
id=1
Datadir=/home/mysql/
Hostname=192.168.0.2
[NDBD DEFAULT]
NoOfReplicas=2
Datadir=/home/mysql/
DataMemory=2048M
IndexMemory=1024M
LockPagesInMainMemory=1
MaxNoOfConcurrentOperations=100000
StringMemory=25
MaxNoOfTables=4096
MaxNoOfOrderedIndexes=2048
MaxNoOfUniqueHashIndexes=512
MaxNoOfAttributes=24576
DiskCheckpointSpeedInRestart=100M
FragmentLogFileSize=256M
InitFragmentLogFiles=FULL
NoOfFragmentLogFiles=6
RedoBuffer=32M
TimeBetweenLocalCheckpoints=20
TimeBetweenGlobalCheckpoints=1000
TimeBetweenEpochs=100
MemReportFrequency=30
BackupReportFrequency=10
### Params for setting logging
LogLevelStartup=15
LogLevelShutdown=15
LogLevelCheckpoint=8
LogLevelNodeRestart=15
### Params for increasing Disk throughput
BackupMaxWriteSize=1M
BackupDataBufferSize=16M
BackupLogBufferSize=4M
BackupMemory=20M
#Reports indicates that odirect=1 can cause io errors (os err code 5) on some systems. You must test.
#ODirect=1
### Watchdog
TimeBetweenWatchdogCheckInitial=30000
### TransactionInactiveTimeout - should be enabled in Production
#TransactionInactiveTimeout=30000
### CGE 6.3 - REALTIME EXTENSIONS
#RealTimeScheduler=1
#SchedulerExecutionTimer=80
#SchedulerSpinTimer=40
### DISK DATA
#SharedGlobalMemory=384M
#read my blog how to set this:
#DiskPageBufferMemory=3072M
### Multithreading
MaxNoOfExecutionThreads=8
[NDBD]
id=2
Datadir=/home/mysql/
Hostname=192.168.221.3
#LockExecuteThreadToCPU=X
#LockMaintThreadsToCPU=Y
[NDBD]
id=3
Datadir=/home/mysql/
Hostname=192.168.0.4
#LockExecuteThreadToCPU=X
#LockMaintThreadsToCPU=Y
[NDBD]
id=4
Datadir=/home/mysql/
Hostname=192.168.0.5
#LockExecuteThreadToCPU=X
#LockMaintThreadsToCPU=Y
[NDBD]
id=5
Datadir=/home/mysql/
Hostname=192.168.0.6
#LockExecuteThreadToCPU=X
#LockMaintThreadsToCPU=Y
[MYSQLD]
id=6
Hostname=192.168.0.3
[MYSQLD]
id=7
Hostname=192.168.0.4
[MYSQLD]
id=8
Hostname=192.168.0.5
[MYSQLD]
id=9
Hostname=192.168.0.6
[MYSQLD]
id=10
Hostname=192.168.0.7
[MYSQLD]
id=11
Hostname=192.168.0.8
[MYSQLD]
id=12
Hostname=192.168.0.9
[MYSQLD]
id=13
Hostname=192.168.0.10
然后启动 ndb_mgmd 进程:
[[email protected] ~]# /usr/sbin/ndb_mgmd -f /home/mysql/config.ini --configdir=/home/mysql/
如果是修改了配置文件里的某些参数,则需要先关闭 ndb_mgmd 进程,然后重新启动,不过必须加上 --reload 选项,因为 7.0 版本中,会把配置文件放在 cache 里,如果不注意到这点,可能会被搞得莫名其妙的。
[[email protected] ~]# /usr/sbin/ndb_mgmd -f /home/mysql/config.ini --configdir=/home/mysql/ --reload
然后在数据节点上启动 ndbd 进程:
[[email protected] ~]# /usr/sbin/ndbd --initial
首次启动,需要加上 --initial 选项,其后的启动后就不需要了。
最后,修改SQL节点上的配置文件 my.cnf,然后启动 mysqld 进程:
[[email protected] ~]# cat /etc/my.cnf
#my.cnf
[mysql_cluster]
ndb-connectstring="192.168.0.2:1186"
[MYSQLD]
......
ndb-cluster-connection-pool=1
ndbcluster
ndb-connectstring="192.168.0.2:1186"
ndb-force-send=1
ndb-use-exact-count=0
ndb-extra-logging=1
ndb-autoincrement-prefetch-sz=256
engine-condition-pushdown=1
......
[[email protected] ~]# /etc/init.d/mysql start
[[email protected] ~]# mysqladmin pr
+------+-------------+-----------+----+---------+------+-----------------------------------+------------------+
| Id | User | Host | db | Command | Time | State | Info |
+------+-------------+-----------+----+---------+------+-----------------------------------+------------------+
| 1 | system user | | | Daemon | 0 | Waiting for event from ndbcluster | |
| 1579 | root | localhost | | Query | 0 | | show processlist |
+------+-------------+-----------+----+---------+------+-----------------------------------+------------------+
在管理节点上看下 cluster 的状态:
[[email protected] ~]# ndb_mgm
-- NDB Cluster -- Management Client --
ndb_mgm> show
Connected to Management Server at: localhost:1186
Cluster Configuration
---------------------
[ndbd(NDB)] 4 node(s)
id=2 @192.168.0.3 (mysql-5.1.32 ndb-7.0.5, Nodegroup: 0, Master)
id=3 @192.168.0.4 (mysql-5.1.32 ndb-7.0.5, Nodegroup: 0)
id=4 @192.168.0.5 (mysql-5.1.32 ndb-7.0.5, Nodegroup: 1)
id=5 @192.168.0.6 (mysql-5.1.32 ndb-7.0.5, Nodegroup: 1)
[ndb_mgmd(MGM)] 1 node(s)
id=1 @192.168.0.2 (mysql-5.1.32 ndb-7.0.5)
[mysqld(API)] 10 node(s)
id=6 @192.168.0.3 (mysql-5.1.32 ndb-7.0.5)
id=7 @192.168.0.4 (mysql-5.1.32 ndb-7.0.5)
id=8 @192.168.0.5 (mysql-5.1.32 ndb-7.0.5)
id=9 @192.168.0.6 (mysql-5.1.32 ndb-7.0.5)
id=10 @192.168.0.7 (mysql-5.1.32 ndb-7.0.5)
id=13 @192.168.0.8 (mysql-5.1.32 ndb-7.0.5)
id=14 @192.168.0.9 (mysql-5.1.32 ndb-7.0.5)
id=15 @192.168.0.10 (mysql-5.1.32 ndb-7.0.5)
ndb_mgm> exit
可以看到,一切正常。
3、测试
我们主要进行一下对比测试,看看新版本的 ndbcluster 引擎相对 MyISAM 和 InnoDB 到底区别多大。
3.1 mysqlslap测试结果
纵坐标是总共运行时间。
mysqlslap完整执行参数类似下面:
mysqlslap -hlocalhost -uroot --engine=myisam --auto-generate-sql-write-number=100000 --auto-generate-sql-guid-primary \
--concurrency=50,100,200 --number-of-queries=500000 --iterations=2 --number-char-cols=10 --number-int-cols=10 \
--auto-generate-sql --create-schema=ndb --auto-generate-sql-load-type=mixed
3.2 sysbench测试结果
纵坐标是每秒运行的事务数。
sysbench完整执行参数类似下面:
sysbench --mysql-user=root --test=oltp --mysql-host=localhost --oltp-test-mode=complex \
--mysql-table-engine=ndbcluster --oltp-table-size=10000000 --mysql-db=ndb --oltp-table-name=mdb_1kw \
--num-threads=200 --max-requests=500000 run
从上面的测试结果我们也可以看到,单独的mysqld实例下,MyISAM适合并发很小的业务,InnoDB适合类似连接池模式下的高并发业务,不适合非常大并发的情景,而采用了LVS后的ndbcluster则是真正的适合高并发环境,尽管其性能相对InnoDB来说不是太好,不过比以往版本也已经提升了很多,用于正式生产环境的时候真是指日可待了。
评论
--mysql-host=localhost
测试在本机的话,通过LVS的响应肯定没有单机快,因为通过LVS已经转发了1次。
建议另外找一台测试机。
测试lvs时,是在其他lvs环境外的机器上发起请求的,并非在本机发起。上面的2个只是例子,只需重点关注数据量、并发量、查询请求次数这几个。
MySQL方案、培训、支持
我还以为可以上生产线了,原来还是指日可待。
打开 ip_forward 这个只在NAT方式下需要,DR和TUN方式都不需要。
另外要是碰上机房断电,那数据。。。
You're totally wrong
老叶,这个配置insert的参数:--auto-generate-sql-write-number=100000和那个--auto-generate-sql-load-type=mixed有没有冲突呢?(mixed(half inserts, half scanning selects))。我了解下一般很少配置这个--auto-generate-sql-write-number参数的吧
请教!
这篇文章介绍lvs的安装多过于mysql cluster,我想知道tar.gz是怎么安装的好像找到,rpm的安装上以后是管理节呢?还是管理节点,sql节点和data节点都一起安装了?
晕糊中,有没有单独下载的tar.gz的格式,因为是ubuntu不能安装rpm
这篇文章介绍lvs的安装多过于mysql cluster,我想知道tar.gz是怎么安装的好像找到,rpm的安装上以后是管理节呢?还是管理节点,sql节点和data节点都一起安装了?
晕糊中,有没有单独下载的tar.gz的格式,因为是ubuntu不能安装rpm
学习并转载到论坛。
叶老师我在启动mgm data 节点之后 报一下错误
-- Node 3: Forced node shutdown completed. Occured during startphase 4. Caused by error 2310: 'Error while reading the REDO log(Ndbd file system inconsistency error, please report a bug). Ndbd file system error, restart node initial'.
尝试按照提示信息做一下: Ndbd file system error, restart node initial
数据库数据稳定性,可用性是第一位的,如果机房断电的话 。岂不是所有东西都没有了。5.1虽然支持非主键的数据存放到磁盘,但是索引还是放到了内存。这样一重启的话,怎么保证数据的完整性呢,就算索引可以自动重建,那也是一个不可完成的任务。如果不解决把内存放到磁盘,mysql cluster肯定是不能用的。不知道老叶有什么看法?
ndb cluster也是支持事务日志的,因此可以从日志中恢复;另外,就想你所说,关键数据还是要有冗余方案,不能产生单点故障
可不可以简单介绍一下需要下载安装的RPM包名,以及各节点的安装和配置,谢谢!
上面的内容已经比较详细了,还要“简单介绍一下”?
你好,最近在做mysql集群布署,但是中途有个问题一直未能解决:
背景:mgmd节点、ndbd节点、mysqld节点均正常启动,mgmd节点能检测到ndbd节点,一直不能检测到mysqld节点;
动作:我检查了mysqld节点服务器,防火墙处于关闭状态,mysqladmin pr查看状态正常;
所以想请教站主这可能是哪方面的问题。万分感谢。期待站主的回复!
还需要检查mgmd节点的防火墙是否正确,查看mgmd、mysqld节点日志,另外,再检查下id是否有重复。
谢谢站主的提醒,我检查过了,mgmd节点的防火墙一直是关着的,mgmd的日志上面显示Communication to Node 4 opened连接mysqld节点,但是一直没有连接上的显示。
但是mysqld在建表的时候日志上出现了一个Warning
NDB: Could not acquire global schema lock (4009)Cluster Failure
我上网上搜了,挺多这样的问题,但是基本上没有答案,请问站主有遇到过这样的问题吗?
mysqld节点对外的防火墙规则正确吗?印象中以前貌似碰到过,什么原因忘了...多看看mgmd节点的日志,说不定会有所发现
disabled selinux
config 請用 IP address, 不要用 hostname
另請參考此網站
http://johanandersson.blogspot.tw/2009/05/cluster-fails-to-start-self-diagnosis.html | __label__pos | 0.765954 |
GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: api/callback.cc Lines: 139 155 89.7 %
Date: 2022-06-23 04:15:39 Branches: 81 96 84.4 %
Line Branch Exec Source
1
#include "node.h"
2
#include "async_wrap-inl.h"
3
#include "env-inl.h"
4
#include "v8.h"
5
6
namespace node {
7
8
using v8::Context;
9
using v8::EscapableHandleScope;
10
using v8::Function;
11
using v8::HandleScope;
12
using v8::Isolate;
13
using v8::Local;
14
using v8::MaybeLocal;
15
using v8::Object;
16
using v8::String;
17
using v8::Value;
18
19
4
CallbackScope::CallbackScope(Isolate* isolate,
20
Local<Object> object,
21
4
async_context async_context)
22
4
: CallbackScope(Environment::GetCurrent(isolate), object, async_context) {}
23
24
115543
CallbackScope::CallbackScope(Environment* env,
25
Local<Object> object,
26
115543
async_context asyncContext)
27
: private_(new InternalCallbackScope(env,
28
object,
29
115543
asyncContext)),
30
231086
try_catch_(env->isolate()) {
31
115543
try_catch_.SetVerbose(true);
32
115543
}
33
34
115542
CallbackScope::~CallbackScope() {
35
115542
if (try_catch_.HasCaught())
36
1
private_->MarkAsFailed();
37
115542
delete private_;
38
115542
}
39
40
42819
InternalCallbackScope::InternalCallbackScope(AsyncWrap* async_wrap, int flags)
41
: InternalCallbackScope(async_wrap->env(),
42
async_wrap->object(),
43
42819
{ async_wrap->get_async_id(),
44
42819
async_wrap->get_trigger_async_id() },
45
42819
flags) {}
46
47
808603
InternalCallbackScope::InternalCallbackScope(Environment* env,
48
Local<Object> object,
49
const async_context& asyncContext,
50
808603
int flags)
51
: env_(env),
52
async_context_(asyncContext),
53
object_(object),
54
808603
skip_hooks_(flags & kSkipAsyncHooks),
55
1617206
skip_task_queues_(flags & kSkipTaskQueues) {
56
808603
CHECK_NOT_NULL(env);
57
808603
env->PushAsyncCallbackScope();
58
59
808603
if (!env->can_call_into_js()) {
60
17001
failed_ = true;
61
17001
return;
62
}
63
64
791602
Isolate* isolate = env->isolate();
65
66
1583204
HandleScope handle_scope(isolate);
67
791602
Local<Context> current_context = isolate->GetCurrentContext();
68
// If you hit this assertion, the caller forgot to enter the right Node.js
69
// Environment's v8::Context first.
70
// We first check `env->context() != current_context` because the contexts
71
// likely *are* the same, in which case we can skip the slightly more
72
// expensive Environment::GetCurrent() call.
73
1583204
if (UNLIKELY(env->context() != current_context)) {
74
6
CHECK_EQ(Environment::GetCurrent(isolate), env);
75
}
76
77
791602
isolate->SetIdle(false);
78
79
791602
env->async_hooks()->push_async_context(
80
async_context_.async_id, async_context_.trigger_async_id, object);
81
82
791602
pushed_ids_ = true;
83
84
791602
if (asyncContext.async_id != 0 && !skip_hooks_) {
85
// No need to check a return value because the application will exit if
86
// an exception occurs.
87
495646
AsyncWrap::EmitBefore(env, asyncContext.async_id);
88
}
89
}
90
91
1616227
InternalCallbackScope::~InternalCallbackScope() {
92
808158
Close();
93
808069
env_->PopAsyncCallbackScope();
94
808069
}
95
96
1226672
void InternalCallbackScope::Close() {
97
1840582
if (closed_) return;
98
808277
closed_ = true;
99
100
808277
Isolate* isolate = env_->isolate();
101
1616346
auto idle = OnScopeLeave([&]() { isolate->SetIdle(true); });
102
103
808277
if (!env_->can_call_into_js()) return;
104
1505493
auto perform_stopping_check = [&]() {
105
1505493
if (env_->is_stopping()) {
106
717
MarkAsFailed();
107
717
env_->async_hooks()->clear_async_id_stack();
108
}
109
2296692
};
110
791199
perform_stopping_check();
111
112
791199
if (!failed_ && async_context_.async_id != 0 && !skip_hooks_) {
113
495546
AsyncWrap::EmitAfter(env_, async_context_.async_id);
114
}
115
116
791199
if (pushed_ids_)
117
791199
env_->async_hooks()->pop_async_context(async_context_.async_id);
118
119
791198
if (failed_) return;
120
121
790207
if (env_->async_callback_scope_depth() > 1 || skip_task_queues_) {
122
76980
return;
123
}
124
125
713227
TickInfo* tick_info = env_->tick_info();
126
127
713227
if (!env_->can_call_into_js()) return;
128
129
1426239
auto weakref_cleanup = OnScopeLeave([&]() { env_->RunWeakRefCleanup(); });
130
131
713223
Local<Context> context = env_->context();
132
713223
if (!tick_info->has_tick_scheduled()) {
133
520187
context->GetMicrotaskQueue()->PerformCheckpoint(isolate);
134
135
520135
perform_stopping_check();
136
}
137
138
// Make sure the stack unwound properly. If there are nested MakeCallback's
139
// then it should return early and not reach this code.
140
713171
if (env_->async_hooks()->fields()[AsyncHooks::kTotals]) {
141
67991
CHECK_EQ(env_->execution_async_id(), 0);
142
67991
CHECK_EQ(env_->trigger_async_id(), 0);
143
}
144
145
713171
if (!tick_info->has_tick_scheduled() && !tick_info->has_rejection_to_warn()) {
146
518854
return;
147
}
148
149
194317
HandleScope handle_scope(isolate);
150
194317
Local<Object> process = env_->process_object();
151
152
194317
if (!env_->can_call_into_js()) return;
153
154
194314
Local<Function> tick_callback = env_->tick_callback_function();
155
156
// The tick is triggered before JS land calls SetTickCallback
157
// to initializes the tick callback during bootstrap.
158
194314
CHECK(!tick_callback.IsEmpty());
159
160
388473
if (tick_callback->Call(context, process, 0, nullptr).IsEmpty()) {
161
846
failed_ = true;
162
}
163
194159
perform_stopping_check();
164
}
165
166
422670
MaybeLocal<Value> InternalMakeCallback(Environment* env,
167
Local<Object> resource,
168
Local<Object> recv,
169
const Local<Function> callback,
170
int argc,
171
Local<Value> argv[],
172
async_context asyncContext) {
173
422670
CHECK(!recv.IsEmpty());
174
#ifdef DEBUG
175
for (int i = 0; i < argc; i++)
176
CHECK(!argv[i].IsEmpty());
177
#endif
178
179
422670
Local<Function> hook_cb = env->async_hooks_callback_trampoline();
180
422670
int flags = InternalCallbackScope::kNoFlags;
181
422670
bool use_async_hooks_trampoline = false;
182
422670
AsyncHooks* async_hooks = env->async_hooks();
183
422670
if (!hook_cb.IsEmpty()) {
184
// Use the callback trampoline if there are any before or after hooks, or
185
// we can expect some kind of usage of async_hooks.executionAsyncResource().
186
51286
flags = InternalCallbackScope::kSkipAsyncHooks;
187
51286
use_async_hooks_trampoline =
188
51286
async_hooks->fields()[AsyncHooks::kBefore] +
189
51286
async_hooks->fields()[AsyncHooks::kAfter] +
190
51286
async_hooks->fields()[AsyncHooks::kUsesExecutionAsyncResource] > 0;
191
}
192
193
845162
InternalCallbackScope scope(env, resource, asyncContext, flags);
194
422670
if (scope.Failed()) {
195
3071
return MaybeLocal<Value>();
196
}
197
198
MaybeLocal<Value> ret;
199
200
419599
Local<Context> context = env->context();
201
419599
if (use_async_hooks_trampoline) {
202
30882
MaybeStackBuffer<Local<Value>, 16> args(3 + argc);
203
61764
args[0] = v8::Number::New(env->isolate(), asyncContext.async_id);
204
30882
args[1] = resource;
205
30882
args[2] = callback;
206
41822
for (int i = 0; i < argc; i++) {
207
10940
args[i + 3] = argv[i];
208
}
209
30882
ret = hook_cb->Call(context, recv, args.length(), &args[0]);
210
} else {
211
388717
ret = callback->Call(context, recv, argc, argv);
212
}
213
214
419540
if (ret.IsEmpty()) {
215
1026
scope.MarkAsFailed();
216
1026
return MaybeLocal<Value>();
217
}
218
219
418514
scope.Close();
220
418395
if (scope.Failed()) {
221
757
return MaybeLocal<Value>();
222
}
223
224
417638
return ret;
225
}
226
227
// Public MakeCallback()s
228
229
10186
MaybeLocal<Value> MakeCallback(Isolate* isolate,
230
Local<Object> recv,
231
const char* method,
232
int argc,
233
Local<Value> argv[],
234
async_context asyncContext) {
235
Local<String> method_string =
236
10186
String::NewFromUtf8(isolate, method).ToLocalChecked();
237
10186
return MakeCallback(isolate, recv, method_string, argc, argv, asyncContext);
238
}
239
240
10195
MaybeLocal<Value> MakeCallback(Isolate* isolate,
241
Local<Object> recv,
242
Local<String> symbol,
243
int argc,
244
Local<Value> argv[],
245
async_context asyncContext) {
246
// Check can_call_into_js() first because calling Get() might do so.
247
Environment* env =
248
20390
Environment::GetCurrent(recv->GetCreationContext().ToLocalChecked());
249
10195
CHECK_NOT_NULL(env);
250
10205
if (!env->can_call_into_js()) return Local<Value>();
251
252
Local<Value> callback_v;
253
20370
if (!recv->Get(isolate->GetCurrentContext(), symbol).ToLocal(&callback_v))
254
return Local<Value>();
255
10185
if (!callback_v->IsFunction()) {
256
// This used to return an empty value, but Undefined() makes more sense
257
// since no exception is pending here.
258
return Undefined(isolate);
259
}
260
10185
Local<Function> callback = callback_v.As<Function>();
261
10185
return MakeCallback(isolate, recv, callback, argc, argv, asyncContext);
262
}
263
264
53760
MaybeLocal<Value> MakeCallback(Isolate* isolate,
265
Local<Object> recv,
266
Local<Function> callback,
267
int argc,
268
Local<Value> argv[],
269
async_context asyncContext) {
270
// Observe the following two subtleties:
271
//
272
// 1. The environment is retrieved from the callback function's context.
273
// 2. The context to enter is retrieved from the environment.
274
//
275
// Because of the AssignToContext() call in src/node_contextify.cc,
276
// the two contexts need not be the same.
277
Environment* env =
278
107520
Environment::GetCurrent(callback->GetCreationContext().ToLocalChecked());
279
53760
CHECK_NOT_NULL(env);
280
53760
Context::Scope context_scope(env->context());
281
MaybeLocal<Value> ret =
282
53760
InternalMakeCallback(env, recv, recv, callback, argc, argv, asyncContext);
283
53745
if (ret.IsEmpty() && env->async_callback_scope_depth() == 0) {
284
// This is only for legacy compatibility and we may want to look into
285
// removing/adjusting it.
286
1220
return Undefined(isolate);
287
}
288
52525
return ret;
289
}
290
291
// Use this if you just want to safely invoke some JS callback and
292
// would like to retain the currently active async_context, if any.
293
// In case none is available, a fixed default context will be
294
// installed otherwise.
295
16
MaybeLocal<Value> MakeSyncCallback(Isolate* isolate,
296
Local<Object> recv,
297
Local<Function> callback,
298
int argc,
299
Local<Value> argv[]) {
300
Environment* env =
301
32
Environment::GetCurrent(callback->GetCreationContext().ToLocalChecked());
302
16
CHECK_NOT_NULL(env);
303
16
if (!env->can_call_into_js()) return Local<Value>();
304
305
16
Local<Context> context = env->context();
306
16
Context::Scope context_scope(context);
307
16
if (env->async_callback_scope_depth()) {
308
// There's another MakeCallback() on the stack, piggy back on it.
309
// In particular, retain the current async_context.
310
16
return callback->Call(context, recv, argc, argv);
311
}
312
313
// This is a toplevel invocation and the caller (intentionally)
314
// didn't provide any async_context to run in. Install a default context.
315
MaybeLocal<Value> ret =
316
InternalMakeCallback(env, env->process_object(), recv, callback, argc, argv,
317
async_context{0, 0});
318
return ret;
319
}
320
321
// Legacy MakeCallback()s
322
323
Local<Value> MakeCallback(Isolate* isolate,
324
Local<Object> recv,
325
const char* method,
326
int argc,
327
Local<Value>* argv) {
328
EscapableHandleScope handle_scope(isolate);
329
return handle_scope.Escape(
330
MakeCallback(isolate, recv, method, argc, argv, {0, 0})
331
.FromMaybe(Local<Value>()));
332
}
333
334
Local<Value> MakeCallback(Isolate* isolate,
335
Local<Object> recv,
336
Local<String> symbol,
337
int argc,
338
Local<Value>* argv) {
339
EscapableHandleScope handle_scope(isolate);
340
return handle_scope.Escape(
341
MakeCallback(isolate, recv, symbol, argc, argv, {0, 0})
342
.FromMaybe(Local<Value>()));
343
}
344
345
Local<Value> MakeCallback(Isolate* isolate,
346
Local<Object> recv,
347
Local<Function> callback,
348
int argc,
349
Local<Value>* argv) {
350
EscapableHandleScope handle_scope(isolate);
351
return handle_scope.Escape(
352
MakeCallback(isolate, recv, callback, argc, argv, {0, 0})
353
.FromMaybe(Local<Value>()));
354
}
355
356
} // namespace node | __label__pos | 0.984903 |
What is 66 to the 100th Power?
So you want to know what 66 to the 100th power is do you? In this article we'll explain exactly how to perform the mathematical operation called "the exponentiation of 66 to the power of 100". That might sound fancy, but we'll explain this with no jargon! Let's do it.
What is an Exponentiation?
Let's get our terms nailed down first and then we can see how to work out what 66 to the 100th power is.
When we talk about exponentiation all we really mean is that we are multiplying a number which we call the base (in this case 66) by itself a certain number of times. The exponent is the number of times to multiply 66 by itself, which in this case is 100 times.
66 to the Power of 100
There are a number of ways this can be expressed and the most common ways you'll see 66 to the 100th shown are:
• 66100
• 66^100
So basically, you'll either see the exponent using superscript (to make it smaller and slightly above the base number) or you'll use the caret symbol (^) to signify the exponent. The caret is useful in situations where you might not want or need to use superscript.
So we mentioned that exponentation means multiplying the base number by itself for the exponent number of times. Let's look at that a little more visually:
66 to the 100th Power = 66 x ... x 66 (100 times)
So What is the Answer?
Now that we've explained the theory behind this, let's crunch the numbers and figure out what 66 to the 100th power is:
66 to the power of 100 = 66100 = 90,031,306,848,407,753,683,265,622,381,558,097,050,805,623,092,525,078,108,742,714,109,073,760,559,171,649,984,943,193,602,700,638,211,677,809,130,018,400,110,087,547,859,636,969,093,140,244,389,989,977,734,623,418,880,254,504,501,271,068,672
Why do we use exponentiations like 66100 anyway? Well, it makes it much easier for us to write multiplications and conduct mathematical operations with both large and small numbers when you are working with numbers with a lot of trailing zeroes or a lot of decimal places.
Hopefully this article has helped you to understand how and why we use exponentiation and given you the answer you were originally looking for. Now that you know what 66 to the 100th power is you can continue on your merry way.
Feel free to share this article with a friend if you think it will help them, or continue on down to find some more examples.
Cite, Link, or Reference This Page
If you found this content useful in your research, please do us a great favor and use the tool below to make sure you properly reference us wherever you use it. We really appreciate your support!
• "What is 66 to the 100th Power?". VisualFractions.com. Accessed on July 27, 2021. https://visualfractions.com/calculator/exponent/what-is-66-to-the-100th-power/.
• "What is 66 to the 100th Power?". VisualFractions.com, https://visualfractions.com/calculator/exponent/what-is-66-to-the-100th-power/. Accessed 27 July, 2021.
• What is 66 to the 100th Power?. VisualFractions.com. Retrieved from https://visualfractions.com/calculator/exponent/what-is-66-to-the-100th-power/.
Exponentiation Calculator
Want to find the answer to another problem? Enter your number and power below and click calculate.
Calculate Exponentiation
Random List of Exponentiation Examples
If you made it this far you must REALLY like exponentiation! Here are some random calculations for you: | __label__pos | 0.917547 |
帮助
详情页调用会员自定义属性的方法
2021-07-23 包工头
想在内容详情页调用会员自定义属性时,如何调用呢?下面给大家提供一个修改方法,此方法升级不会影响使用。
1.打开此文件/extend/function.php,添加下面代码
if (!function_exists('diy_users_attr_value')) {
/**
* 获取会员属性值
*/
function diy_users_attr_value($users_id = '', $para_id = '', $admin_id = '')
{
$info = '';
static $users_list = null;
if (null === $users_list) {
if(empty($users_id) && !empty($admin_id)){
$users_id = \think\Db::name('users')->where('admin_id',$admin_id)->value('users_id');
}
$users_list = \think\Db::name('users_list')->where(['users_id'=>$users_id])->getAllWithIndex('para_id');
}
if (!empty($users_list[$para_id])) {
$info = $users_list[$para_id]['info'];
}
$info = preg_replace('#(.*)(\#39;|"|"|\')?(/[/\w]+)?(/uploads/)(.*)#iU', '$1$2'.ROOT_DIR.'$4$5', $info);
return $info;
}
}
2.查看会员属性值
详情页调用会员自定义属性的方法(图1)
3.最后一步,在模板内填写标签调用 {$eyou.field.users_id|diy_users_attr_value=###,3,$eyou.field.admin_id}
下面标签里的3,为会员自定义属性字段的值,也就是我们第二部审查元素获取的值
{$eyou.field.users_id|diy_users_attr_value=###,3,$eyou.field.admin_id}
按照上面步骤即可在详情页调用会员自定义属性字段了。
图例:
模板标签
详情页调用会员自定义属性的方法(图2)
前端效果:
详情页调用会员自定义属性的方法(图3)
标签: 会员标签
本文地址:https://www.eyoucms.com/help/tag/2021/0723/11864.html 复制链接 如需定制请联系易优客服咨询:800182392 点击咨询
QQ在线咨询 | __label__pos | 0.975892 |
Dictionary > Indivisible
Indivisible
Indivisible
1. Not divisible; incapable of being divided, separated, or broken; not separable into parts. One indivisible point of time.
2. (Science: mathematics) Not capable of exact division, as one quantity by another; incommensurable.
Origin: L. Indivisibilis: cf. F. Indivisible. See in- not, and Divisible.
1. That which is indivisible. By atom, nobody will imagine we intend to express a perfect indivisible, but only the least sort of natural bodies. (Digby)
2. (Science: geometry) An infinitely small quantity which is assumed to admit of no further division. Method of indivisibles, a kind of calculus, formerly in use, in which lines were considered as made up of an infinite number of points; surfaces, as made up of an infinite number of lines; and volumes, as made up of an infinite number of surfaces.
You will also like...
Birth of a Human Baby
Birth of a Human Baby
Following nine months inside the mother's womb is the birth of the baby. Know the different stages of the birthing proce..
Homo Species
The Homo Species
The evolution of the species of the genus "Homo" led to the emergence of modern humans. Find out more about human evolut..
Nephrolepis exaltata
Vascular Plants: Ferns and Relatives
Ferns and their relatives are vascular plants, meaning they have xylem and phloem tissues. Because of the presence of va..
Water Cycle
The Water Cycle
The water cycle (also referred to as the hydrological cycle) is a system of continuous transfer of water from the air, s..
human respiratory system
Respiration
The human respiratory system is an efficient system of inspiring and expiring respiratory gases. This tutorial provides ..
Fossil trilobite imprint in the sediment
Insects
There are more species of insects than any other species combined. This surely illustrates that insects have the selecti..
Related Articles...
No related articles found
See all Related Topics | __label__pos | 0.528348 |
Earth Simulator
From Wikipedia, the free encyclopedia
Jump to navigation Jump to search
Earth Simulator 2 (ES2)
Earth Simulator (ES), original version.
The Earth Simulator (ES) (地球シミュレータ, Chikyū Shimyurēta), developed by the Japanese government's initiative "Earth Simulator Project", was a highly parallel vector supercomputer system for running global climate models to evaluate the effects of global warming and problems in solid earth geophysics. The system was developed for Japan Aerospace Exploration Agency, Japan Atomic Energy Research Institute, and Japan Marine Science and Technology Center (JAMSTEC) in 1997. Construction started in October 1999, and the site officially opened on 11 March 2002. The project cost 60 billion yen.
Built by NEC, ES was based on their SX-6 architecture. It consisted of 640 nodes with eight vector processors and 16 gigabytes of computer memory at each node, for a total of 5120 processors and 10 terabytes of memory. Two nodes were installed per 1 metre × 1.4 metre × 2 metre cabinet. Each cabinet consumed 20 kW of power. The system had 700 terabytes of disk storage (450 for the system and 250 for the users) and 1.6 petabytes of mass storage in tape drives. It was able to run holistic simulations of global climate in both the atmosphere and the oceans down to a resolution of 10 km. Its performance on the LINPACK benchmark was 35.86 TFLOPS, which was almost five times faster than the previous fastest supercomputer, ASCI White.
ES was the fastest supercomputer in the world from 2002 to 2004. Its capacity was surpassed by IBM's Blue Gene/L prototype on 29 September 2004.
ES was replaced by the Earth Simulator 2 (ES2) in March 2009.[1] ES2 is an NEC SX-9/E system, and has a quarter as many nodes each of 12.8 times the performance (3.2× clock speed, four times the processing resource per node), for a peak performance of 131 TFLOPS. With a delivered LINPACK performance of 122.4 TFLOPS,[2] ES2 was the most efficient supercomputer in the world at that point. In November 2010, NEC announced that ES2 topped the Global FFT, one of the measures of the HPC Challenge Awards, with the performance number of 11.876 TFLOPS.[3]
ES2 was replaced by the Earth Simulator 3 (ES3) in March 2015. ES3 is a NEC SX-ACE system with 5120 nodes.[4][5]
System overview[edit]
Hardware[edit]
The Earth Simulator (ES for short) was developed as a national project by three governmental agencies: the National Space Development Agency of Japan (NASDA), the Japan Atomic Energy Research Institute (JAERI), and the Japan Marine Science and Technology Center (JAMSTEC). The ES is housed in the Earth Simulator Building (approx; 50m × 65m × 17m). The Earth Simulator 2 (ES2) uses 160 nodes of NEC's SX-9E. The upgrade of the Earth Simulator has been completed in March 2015. The Earth Simulator 3(ES3) system uses 5120 nodes of NEC's SX-ACE.
System configuration[edit]
The ES is a highly parallel vector supercomputer system of the distributed-memory type, and consisted of 160 processor nodes connected by Fat-Tree Network. Each Processor nodes is a system with a shared memory, consisting of 8 vector-type arithmetic processors, a 128-GB main memory system. The peak performance of each Arithmetic processors is 102.4Gflops. The ES as a whole thus consists of 1280 arithmetic processors with 20 TB of main memory and the theoretical performance of 131Tflops.
Construction of CPU[edit]
Each CPU consists of a 4-way super-scalar unit (SU), a vector unit (VU), and main memory access control unit on a single LSI chip. The CPU operates at a clock frequency of 3.2 GHz. Each VU has 72 vector registers, each of which has 256 vector elements, along with 8 sets of six different types of vector pipelines: addition /shifting, multiplication, division, logical operations, masking, and load/store. The same type of vector pipelines works together by a single vector instruction and pipelines of different types can operate concurrently.
Processor Node (PN)[edit]
The processor node is composed of 8 CPU and 10 memory modules.
Interconnection Network (IN)[edit]
The RCU is directly connected to the crossbar switches and controls inter-node data communications at 64 GB/s bidirectional transfer rate for both sending and receiving data. Thus the total bandwidth of inter-node network is about 10 TB/s.
Processor Node (PN) Cabinet[edit]
The processor node is composed two nodes of one cabinet, and consists of power supply part 8 memory modules and PCI box with 8 CPU modules.
Software[edit]
Below is the description of software technologies used in the operating system, Job Scheduling and the programming environment of ES2.
Operating system[edit]
The operating system running on ES, "Earth Simulator Operating System", is a custom version of NEC's SUPER-UX used for the NEC SX supercomputers that make up ES.
Mass storage file system[edit]
If a large parallel job running on 640 PNs reads from/writes to one disk installed in a PN, each PN accesses to the disk in sequence and performance degrades terribly. Although local I/O in which each PN reads from or writes to its own disk solves the problem, it is a very hard work to manage such a large number of partial files. Then ES adopts Staging and Global File System (GFS) that offers a high-speed I/O performance.
Job scheduling[edit]
ES is basically a batch-job system. Network Queuing System II (NQSII) is introduced to manage the batch job. Queue configuration of the Earth Simulator. ES has two-type queues. S batch queue is designed for single-node batch jobs and L batch queue is for multi-node batch queue. There are two-type queues. One is L batch queue and the other is S batch queue. S batch queue is aimed at being used for a pre-run or a post-run for large-scale batch jobs (making initial data, processing results of a simulation and other processes), and L batch queue is for a production run. Users choose the appropriate queue for their job.
1. The nodes allocated to a batch job are used exclusively for that batch job.
2. The batch job is scheduled based on elapsed time instead of CPU time.
Strategy (1) enables to estimate the job termination time and to make it easy to allocate nodes for the next batch jobs in advance. Strategy (2) contributes to an efficient job execution. The job can use the nodes exclusively and the processes in each node can be executed simultaneously. As a result, the large-scale parallel program is able to be executed efficiently. PNs of L-system are prohibited from access to the user disk to ensure enough disk I/O performance. herefore the files used by the batch job are copied from the user disk to the work disk before the job execution. This process is called "stage-in." It is important to hide this staging time for the job scheduling. Main steps of the job scheduling are summarized as follows;
1. Node Allocation
2. Stage-in (copies files from the user disk to the work disk automatically)
3. Job Escalation (rescheduling for the earlier estimated start time if possible)
4. Job Execution
5. Stage-out (copies files from the work disk to the user disk automatically)
When a new batch job is submitted, the scheduler searches available nodes (Step.1). After the nodes and the estimated start time are allocated to the batch job, stage-in process starts (Step.2). The job waits until the estimated start time after stage-in process is finished. If the scheduler find the earlier start time than the estimated start time, it allocates the new start time to the batch job. This process is called "Job Escalation" (Step.3). When the estimated start time has arrived, the scheduler executes the batch job (Step.4). The scheduler terminates the batch job and starts stage-out process after the job execution is finished or the declared elapsed time is over (Step.5). To execute the batch job, the user logs into the login-server and submits the batch script to ES. And the user waits until the job execution is done. During that time, the user can see the state of the batch job using the conventional web browser or user commands. The node scheduling, the file staging and other processing are automatically processed by the system according to the batch script.
Programming environment[edit]
Programming model in ES
The ES hardware has a 3-level hierarchy of parallelism: vector processing in an AP, parallel processing with shared memory in a PN, and parallel processing among PNs via IN. To bring out high performance of ES fully, you must develop parallel programs that make the most use of such parallelism. the 3-level hierarchy of parallelism of ES can be used in two manners, which are called hybrid and flat parallelization, respectively . In the hybrid parallelization, the inter-node parallelism is expressed by HPF or MPI, and the intra-node by microtasking or OpenMP, and you must, therefore, consider the hierarchical parallelism in writing your programs. In the flat parallelization, the both inter- and intra-node parallelism can be expressed by HPF or MPI, and it is not necessary for you to consider such complicated parallelism. Generally speaking, the hybrid parallelization is superior to the flat in performance and vice versa in ease of programming. Note that the MPI libraries and the HPF runtimes are optimized to perform as well as possible both in the hybrid and flat parallelization.
Languages
Compilers for Fortran 90, C and C++ are available. All of them have an advanced capability of automatic vectorization and microtasking. Microtasking is a sort of multitasking provided for the Cray's supercomputer at the same time and is also used for intra-node parallelization on ES. Microtasking can be controlled by inserting directives into source programs or using the compiler's automatic parallelization. (Note that OpenMP is also available in Fortran 90 and C++ for intra-node parallelization.)
Parallelization
Message Passing Interface (MPI)
MPI is a message passing library based on the MPI-1 and MPI-2 standards and provides high-speed communication capability that fully exploits the features of IXS and shared memory. It can be used for both intra- and inter-node parallelization. An MPI process is assigned to an AP in the flat parallelization, or to a PN that contains microtasks or OpenMP threads in the hybrid parallelization. MPI libraries are designed and optimizedcarefully to achieve highest performance of communication on the ES architecture in both of the parallelization manner.
High Performance Fortrans (HPF)
Principal users of ES are considered to be natural scientists who are not necessarily familiar with the parallel programming or rather dislike it. Accordingly, a higher-level parallel language is in great demand. HPF/SX provides easy and efficient parallel programming on ES to supply the demand. It supports the specifications of HPF2.0, its approved extensions, HPF/JA, and some unique extensions for ES
Tools
-Integrated development environment (PSUITE)
Integrated development environment (PSUITE) is integration of various tools to develop the program that operates by SUPER-UX. Because PSUITE assumes that various tools can be used by GUI, and has the coordinated function between tools, it comes to be able to develop the program more efficiently than the method of developing the past the program and easily.
-Debug Support
In SUPER-UX, the following are prepared as strong debug support functions to support the program development.
Facilities[edit]
Features of the Earth Simulator building
Protection from natural disasters[edit]
The Earth Simulator Center has several special features that help to protect the computer from natural disasters or occurrences. A wire nest hangs over the building which helps to protect from lightning. The nest itself uses high-voltage shielded cables to release lightning current into the ground. A special light propagation system utilizes halogen lamps, installed outside of the shielded machine room walls, to prevent any magnetic interference from reaching the computers. The building is constructed on a seismic isolation system, composed of rubber supports, that protect the building during earthquakes.
Lightning protection system[edit]
Three basic features:
• Four poles at both sides of the Earth Simulator Building compose wire nest to protect the building from lightning strikes.
• Special high-voltage shielded cable is used for inductive wire which releases a lightning current to the earth.
• Ground plates are laid by keeping apart from the building about 10 meters.
Illumination[edit]
Lighting: Light propagation system inside a tube (255mm diameter, 44m(49yd) length, 19 tubes) Light source: halogen lamps of 1 kW Illumination: 300 lx at the floor in average The light sources installed out of the shielded machine room walls.
Seismic isolation system[edit]
11 isolators (1 ft height, 3.3 ft. Diameter, 20-layered rubbers supporting the bottom of the ES building)
Performance[edit]
LINPACK[edit]
The new Earth Simulator system, which began operation in March 2009, achieved sustained performance of 122.4 TFLOPS and computing efficiency (*2) of 93.38% on the LINPACK Benchmark (*1).
• 1. LINPACK Benchmark
The LINPACK Benchmark is a measure of a computer's performance and is used as a standard benchmark to rank computer systems in the TOP500 project. LINPACK is a program for performing numerical linear algebra on computers.
• 2. Computing efficiency
Computing efficiency is the ratio of sustained performance to a peak computing performance. Here, it is the ratio of 122.4TFLOPS to 131.072TFLOPS.
Computational performance of WRF on Earth Simulator[edit]
WRF (Weather Research and Forecasting Model) is a mesoscale meteorological simulation code which has been developed under the collaboration among US institutions, including NCAR (National Center for Atmospheric Research) and NCEP (National Centers for Environmental Prediction). JAMSTEC has optimized WRFV2 on the Earth Simulator (ES2) renewed in 2009 with the measurement of computational performance. As a result, it was successfully demonstrated that WRFV2 can run on the ES2 with outstanding and sustained performance.
The numerical meteorological simulation was conducted by using WRF on the Earth Simulator for the earth's hemisphere with the Nature Run model condition. The model spatial resolution is 4486 by 4486 horizontally with the grid spacing of 5 km and 101 levels vertically. Mostly adiabatic conditions were applied with the time integration step of 6 seconds. A very high performance on the Earth Simulator was achieved for high-resolution WRF. While the number of CPU cores used is only 1% as compared to the world fastest class system Jaguar (CRAY XT5) at Oak Ridge National Laboratory, the sustained performance obtained on the Earth Simulator is almost 50% of that measured on the Jaguar system. The peak performance ratio on the Earth Simulator is also record-high 22.2%.
See also[edit]
References[edit]
1. ^ "Japan's Earth Simulator 2 open for business". 1 March 2009.
2. ^ "Earth Simulator update breaks efficiency record". 5 June 2009.
3. ^ ""Earth Simulator" Wins First Place in the HPC Challenge Awards". 17 November 2010.
4. ^ https://www.jamstec.go.jp/es/en/info/150601_es.html
5. ^ https://www.jamstec.go.jp/es/en/system/hardware.html
External links[edit]
Records
Preceded by
ASCI White
7.226 teraflops
World's most powerful supercomputer
March 2002 – November 2004
Succeeded by
Blue Gene/L
70.72 teraflops
Coordinates: 35°22′51″N 139°37′34.8″E / 35.38083°N 139.626333°E / 35.38083; 139.626333 | __label__pos | 0.685904 |
How Internet Works?
If I ask you to imagine your life without the internet, rather than thinking about that, you would ask me to shut up and focus on what I want to say via the blog 🤣
Jokes apart, How many of you have actually thought what is internet and how it works?
Hopefully, I can provide some knowledge that gets you to the way there.
The Internet
Most people do not have the idea where the internet came from but it doesn’t matter, they don’t need to. This is one of the things we use every day, we don’t even think about the fact that one day somebody invented them. Earlier, communication was a major issue. So to overcome this hurdle, great scientists come with the idea of interconnectivity of computers. Now, this INTERconnected NETwork of computers is referred to as the INTERNET.
Now you might be thinking that if the internet is only interconnectivity of computers then why do we pay for this and who is getting paid for this? So, there are 3 types of ISP(Internet Service Providers):
• Tier 1 ISP
• Tier 2 ISP
• Tier 3 ISP
Tier 1 ISPs are those who spread optic fibre(aka submarine cables) cables all over the world under the sea. Without a Tier 1 ISP, Internet traffic could not be exchanged between continents and countries. This is how submarine cables are spread all over the world
Tier 2 ISPs are those who connect Tier 1 ISPs to Tier 3 ISPs and vice-versa. Tier 2 providers purchase links(cables) from Tier 3 providers. The goal to tier 2 providers is to have as many networks as possible.
Tier 3 ISPs are the end user internet providers. They are responsible for the last mile connectivity. They connect a normal user to a network via their links to a tier 2 provider. A tier 3 ISP can also have direct links with tier 1 ISPs.
INTERNET is totally free of cost, you are just paying for the maintenance of the optic fibre cables being used by the service providers. Even the highest quality optic fibre cables used by tier 1 have a life of around 25 years. In India, there are five junctions where tier 2 providers can connect tier 3 with tier 2 providers(refer to submarine cable map).
For instance, when someone visits google.com in India, the request travel from tier 3 provider’s network to tier 2 provider’s network. Then from tier 2, it will travel to Mumbai. From Mumbai, the request goes to California(where Google’s data centres are located) via the submarine cables. Now form California the response travels is the same way and reaches to the computer system of the one who has requested the service.
Now consider the situation when a company’s website whose server is in India, is being searched by an Indian. In this case, the data will not travel to other countries/continents thus submarine cables will not be involved. This will improve the privacy and security of the data. Considering the example of the Aadhar card, one would not want other countries to know what data(traffic) of the Aadhar card is coming from India. Thus, having an Indian server will not involve Tier 1 companies in this case, making the data more secure.
If you wanted to know the stats of data going out of India every day from the tier 1 junctions, you can refer this
You can see from above stats, data going out from 2am – 6am is least.
The IP Address and How we communicate?
Before going in detail with the IP addresses, I just wanted you to understand how we communicate with the servers and computers out there in the world.
Internet protocols(IP) are the set of rules which a request must follow to reach the owner. For a host to host communication, we need an IP address which is a Logical address. If you wanna know the IP address of your computer, just google ‘my IP address’. Considering the above image, it might happen that HOST2 is not the owner of the page you requested, then the request will travel to HOST3 which might have the source code of your request and can finally send you a particular response. For example, Google has different servers(machine) in different states/countries/continents. Now when you type ‘google.com’ you send a letter(request) that says you wanted to see Google’s website. Your letter(request) goes to the server nearest to you. Then it again goes to a server nearer to your addressee and another until it’s delivered at its destination. It is possible that you reach Google’s website with different IPs because there are many servers owned by them. When you send a request, there are certain features to be delivered correctly like different addresses. These set of rules are managed by Internet Protocols(https/http). You can verify the path followed by your request using the traceroute command(google it).
Now, you might be thinking that there are numerous processes running on a computer, how the server identifies the process number corresponding to a particular request. This is where the PORT number comes into play. Every process is defined with the different port number, which when matched with the port number on HOST2, sends back the response.
You don't need to learn this. This is only for people who are curious to know what happens under the hood.
I’ll try to come up with more information on servers, protocols and different terms you want to be familiar with, hopefully soon.
Written by - Dishant Sethi
Tags
Enjoyed the blog? If so, you'll appreciate collaborating with the minds behind it as well.
Last updated | __label__pos | 0.823838 |
The Math Forum
Ask Dr. Math - Questions and Answers from our Archives
_____________________________________________
Associated Topics || Dr. Math Home || Search Dr. Math
_____________________________________________
Decimal to Polar Coordinates
Date: 11/23/97 at 02:03:53
From: Michael Louis
Subject: Conversion from decimal to polar coordinates
The textbook I'm using for a PreCalculus course in night school shows
me how to convert polar coordinates into rectangular ones using the
formula:
x = r cos theta and y = r sin theta
I need to know how to convert in the opposite direction, from
rectangular coordinates back to polar.
Thank you.
Date: 11/23/97 at 05:09:48
From: Doctor Mitteldorf
Subject: Re: Conversion from decimal to polar coordinates
Dear Michael,
If you sum the squares of x and y, you find that you get r squared,
since sin^2 + cos^2 = 1 for any angle. Therefore
r = sqrt(x^2+y^2)
To find theta, divide your two equations
y/x = sin(theta)/cos(theta) = tan(theta)
You can find theta from the inverse tangent function. You will need
to resolve the ambiguity about whether you have theta or (pi+theta)
by using the signs of x and y. For example, (x = 1, y = 1) means
theta = pi/4, but (x = -1, y = -1) means theta = 3pi/4, even though
the tangents of these two angles are the same.
-Doctor Mitteldorf, The Math Forum
Check out our web site! http://mathforum.org/dr.math/
Associated Topics:
High School Equations, Graphs, Translations
Search the Dr. Math Library:
Find items containing (put spaces between keywords):
Click only once for faster results:
[ Choose "whole words" when searching for a word like age.]
all keywords, in any order at least one, that exact phrase
parts of words whole words
Submit your own question to Dr. Math
[Privacy Policy] [Terms of Use]
_____________________________________
Math Forum Home || Math Library || Quick Reference || Math Forum Search
_____________________________________
Ask Dr. MathTM
© 1994- The Math Forum at NCTM. All rights reserved.
http://mathforum.org/dr.math/ | __label__pos | 0.778171 |
Results 1 to 3 of 3
Math Help - Rational expression and binomial expansion
1. #1
Newbie
Joined
Sep 2013
From
united kingdom
Posts
8
Thanks
1
Rational expression and binomial expansion
Find the first four terms of the series expansion for the rational expression: 2+x / (1+4x)(1-3x)
In my attempt at this question I have simplified as partial fractions, but they don't look right, and also after using binomial expansion to find the first four terms, my terms are incorrect.
Please help me on how to solve this
Follow Math Help Forum on Facebook and Google+
2. #2
Newbie
Joined
Sep 2013
From
united kingdom
Posts
8
Thanks
1
Re: Rational expression and binomial expansion
Sorry guys, already solved it myself
Follow Math Help Forum on Facebook and Google+
3. #3
MHF Contributor
Prove It's Avatar
Joined
Aug 2008
Posts
12,300
Thanks
1758
Re: Rational expression and binomial expansion
Quote Originally Posted by Bernana View Post
Find the first four terms of the series expansion for the rational expression: 2+x / (1+4x)(1-3x)
In my attempt at this question I have simplified as partial fractions, but they don't look right, and also after using binomial expansion to find the first four terms, my terms are incorrect.
Please help me on how to solve this
Your approach seems fine. Attempting Partial Fractions:
\displaystyle \begin{align*} \frac{A}{1 + 4x} + \frac{B}{1 - 3x} &\equiv \frac{2 + x}{(1 + 4x)(1 - 3x)} \\ \frac{A(1 - 3x) + B(1 + 4x)}{(1 + 4x)(1 - 3x)} &\equiv \frac{2 + x}{(1 + 4x)(1 - 3x)} \\ A(1 - 3x) + B(1 + 4x) &\equiv 2 + x \end{align*}
Now let \displaystyle \begin{align*} x = \frac{1}{3} \end{align*} and we find \displaystyle \begin{align*} B\left[ 1 + 4 \left( \frac{1}{3} \right) \right] = 2 + \frac{1}{3} \implies \frac{7}{3}B = \frac{7}{3} \implies B = 1 \end{align*} and let \displaystyle \begin{align*} x = -\frac{1}{4} \end{align*} and we find \displaystyle \begin{align*} A \left[ 1 - 3 \left( -\frac{1}{4} \right) \right] = 2 - \frac{1}{4} \implies \frac{7}{4}A = \frac{7}{4} \implies A = 1 \end{align*}, we can then see
\displaystyle \begin{align*} \frac{2 + x}{(1 + 4x)(1 - 3x)} &= \frac{1}{1 + 4x} + \frac{1}{1 - 3x} \\ &= \frac{1}{1 - \left( -4x \right) } + \frac{1}{1 - 3x} \\ &= \sum_{m = 1}^{\infty} \left( -4x \right) ^m + \sum_{n = 1}^{\infty} \left( 3x \right) n \textrm{ if } |x| < \frac{1}{4} \textrm{ and } |x| < \frac{1}{3} \\ &= \sum_{n = 1}^{\infty} \left[ (-4x)^n + (3x)^n \right] \textrm{ if } |x| < \frac{1}{4} \end{align*}
So the first four terms will be \displaystyle \begin{align*} \left\{ -4x + 3x, (-4x)^2 + (3x)^2, (-4x)^3 + (3x)^3, (-4x)^4 + (3x)^4 \dots \right\} = \left\{ -x, 25x^2, -55x^3, 331x^4 \dots \right\} \end{align*}.
Follow Math Help Forum on Facebook and Google+
Similar Math Help Forum Discussions
1. Replies: 2
Last Post: December 8th 2009, 06:48 AM
2. Replies: 6
Last Post: May 1st 2009, 11:37 AM
3. Decimal expansion of a rational
Posted in the Algebra Forum
Replies: 2
Last Post: January 13th 2009, 02:30 AM
4. Rational Decimal Expansion
Posted in the Number Theory Forum
Replies: 0
Last Post: April 2nd 2006, 03:44 PM
5. ir/rational expansion
Posted in the Math Topics Forum
Replies: 7
Last Post: November 21st 2005, 11:52 PM
Search Tags
/mathhelpforum @mathhelpforum | __label__pos | 0.999806 |
Hello, This is my first post this forum. Query your connected data sources with SQL, Present and share customizable data visualizations, Explore example analysis and visualizations. In this section, we’re just listing all the possible combinations of GROUP BY columns that we want to use, which produces 8 distinct GROUPING SETS. Here’s a quick example of how to group on one or multiple columns and summarise data with aggregation functions using Pandas. No coding experience necessary. Sometimes, we want to get all rows in a table but eliminate the available NULL values. Order your results chronologically. But what if you want to aggregate only part of a table? We can count during aggregation using GROUP BY to make distinct when needed after the select statement to show the data with counts. SELECT year, month, COUNT(*) AS count FROM tutorial.aapl_historical_stock_price GROUP BY 1, 2 SQL Group By Tutorial: Count, Sum, Average, and Having Clauses Explained. The GROUP BY clause divides the rows in the payment into groups and groups them by value in the staff_id column. We illustrate this with two examples. SQL Courses: 1: Start Here - Intro: 2: SELECT Statement: 3: Aggregate Functions: 4: GROUP BY clause: 5: HAVING clause ... Table Joins, a must: 11: SQL Interpreter: 12: Advertise on SQLCourse.com: 13: Other Tutorial Links: Advertiser Disclosure. Using the group by statement with multiple columns is useful in many different situations – and it is best illustrated by an example. Exercise 10.8: For each player who lives in Inglewood, get the name, initials, and number of penalties incurred by him or her. I want to build a query that counts the number of people that are on a particular shift. Step 2: The GROUPING SETS. It is pulling the information from one table. The GROUP BY clause returns one row per group. We’ll see that in step 3. The following statement, therefore, is equivalent to the previous one: As an example, let us add some aggregation functions to the previous SELECT statement: In this example, the grouping is equal to [TEAMNO, PLAYERNO] and the aggregation level of the result is the combination of team number with player number. This aggregation level is lower than that of a statement in which the grouping is equal to [TEAMNO] or [TOWN]. The GROUP BY clause is often used with aggregate functions such as AVG() , COUNT() , MAX() , MIN() and SUM() . Suppose we have a table shown below called Purchases. Now lets say we want to know the number of subjects each student is attending. You typically use a GROUP BY clause in conjunction with an aggregate expression. Learn how to group with multiple columns using GROUP BY in SQL. It returns one record for each group. To this point, I’ve used aggregate functions to summarize all the values in a column or just those values that matched a WHERE search condition.You can use the GROUP BY clause to divide a table into logical groups (categories) and calculate aggregate statistics for each group.. An example will clarify the concept. If you group by a column with enough unique values that it exceeds the LIMIT number, the aggregates will be calculated, and then some rows will simply be omitted from the results. Group By multiple columns: Group by multiple column is say for example, GROUP BY column1, column2. This means to place all the rows with same values of both the columns column1 and column2 in one group… Example 10.6. GROUP BY and FILTER. ... By adding a second column in our GROUP BY we further sub-divide … My first attempt looked something like: SELECT dt.docId, COUNT(l.lineId), SUM(dt.weight) AS tot FROM DocumentTags dt LEFT JOIN Lines l ON dt.docId = lt.docId WHERE dt.tag = "example" GROUP BY dt.docId ORDER BY tot DESC SQL Group By Tutorial: Count, Sum, Average, and Having Clauses Explained. 208 Utah Street, Suite 400San Francisco CA 94103. In SQL, the group by statement is used along with aggregate functions like SUM, AVG, MAX, etc. GROUP BY Syntax The SQL GROUP BY statement is used in conjunction with the aggregate functions to arrange identical data into groups. For example, the COUNT() function returns the number of rows for each group. Let's give it a try: And there it is! As with ORDER BY, you can substitute numbers for column names in the GROUP BY clause. Hello, I am trying to use various aggregate functions on multiple tables, with limited success. SQL COUNT () with group by and order by In this page, we are going to discuss the usage of GROUP BY and ORDER BY along with the SQL COUNT () function. Write a query that calculates the lowest and highest prices that Apple stock achieved each month. The GROUP BY clause is used in a SELECT statement to group rows into a set of summary rows by values of columns or expressions. The following example groups by both Location and Type, producing total square miles for the deserts and lakes in each location in the Sql.Features table: SELECT Statement: The GROUP BY Clause in SQL, 10.6 General Rules for the GROUP BY Clause, Introduction to SQL: Mastering the Relational Database Language, 4th Edition, Database Design for Mere Mortals: 25th Anniversary Edition, 4th Edition, Database Design for Mere Mortals, 4th Edition, Product Analytics: Applied Data Science Techniques for Actionable Consumer Insights, Mobile Application Development & Programming. > The GROUP BY clause a selected group of rows into summary rows by values of one or more columns. Summary: this tutorial shows you how to use the SQL COUNT function to get the number of items in a group.. Introduction to SQL COUNT function. To aggregate means to make whole from individual parts. The GROUP BY clause is often used with aggregate functions such as AVG (), COUNT (), MAX (), MIN () and SUM (). GROUP BY Clause. A developer needs to get data from a SQL table with multiple conditions. SQL aggregate function like COUNT, AVG, and SUM have something in common: they all aggregate across the entire table. ... By adding a second column in our GROUP BY we further sub-divide our location groups into location groups per product. As with ORDER BY, you can substitute numbers for column names in the GROUP BY clause. The AVG() function returns the average value of all values in the group. Grouping Rows with GROUP BY. For the MATCHES table, get all the different combinations of team numbers and player numbers. Previous. To count the distinct of orders making up the details we would use the following: SELECT COUNT(Distinct SalesOrderID) FROM Sales.SalesOrderDetail. You can use aggregate functions with any of the columns that you select. A GROUP BY clause, part of a SelectExpression, groups a result into subsets that have matching values for one or more columns. It combines the multiple records in single or more columns using some functions. If you don't group by any columns, you'll get a 1-row result—no problem there. The SQL GROUP BY statement is used in conjunction with the aggregate functions to arrange identical data into groups.. As with ORDER BY, you can substitute numbers for column names in the GROUP BY clause. An introduction to the GROUP BY clause and FILTER modifier.. GROUP BY enables you to use aggregate functions on groups of data returned from a query.. FILTER is a modifier used on an aggregate function to limit the values used in an aggregation. In this chapter, we sometimes represent this as follows: The result is grouped by [TOWN]. The GROUP BY statement is often used with aggregate functions (COUNT, MAX, MIN, SUM, AVG) to group the result-set by … It is pulling the information from one table. Multiple groups. It means that for a given GROUPING SET, we didn’t group by that column. This means to place all the rows with same values of both the columns column1 and column2 in one group… A GROUP BY clause can group by one or more columns. It's generally recommended to do this only when you're grouping many columns, or if something else is causing the text in the GROUP BY clause to be excessively long: Note: this functionality (numbering columns instead of using names) is supported by Mode, but not by every flavor of SQL, so if you're using another system or connected to certain types of databases, it may not work. We illustrate this with two examples. In the SQL GROUP BY statement must contains a aggregate function in the SQL query.. We can group the data into as many groups or sub-groups as we want. The GROUP BY clause is used in a SELECT statement to group rows into a set of summary rows by values of columns or expressions. The intermediate result from the GROUP BY clause is: The sequence of the columns in the GROUP BY clause has no effect on the end result of a statement. The count now is 31465. Exercise 10.5: For each combination of won–lost sets, get the number of matches won. We’ll see that in step 3. Aggregate functions are functions that work on more than one row to return a result. Here's an example using the Apple stock prices dataset: You can group by multiple columns, but you have to separate column names with commas—just as with ORDER BY): Calculate the total number of shares traded each month. The order of column names in your GROUP BY clause doesn't matter—the results will be the same regardless. Multiple groups. Hello, This is my first post this forum. Step 2: The GROUPING SETS. It is actually wrong! Exercise 10.7: Group the matches on town of player and division of team, and get the sum of the sets won for each combination of town[nd]division. Suppose we have a table shown below called Purchases. The GROUP BY Clause is utilized in SQL with the SELECT statement to organize similar data into groups. All the columns in the select statement that aren’t aggregated should be specified in a GROUP BY clause in the query.
What Is One Criticism Of Nuclear Energy–development Projects?, Frank's Sweet Chili Sauce Meatballs, Hellmann's Roasted Garlic Mayonnaise, Last Leg Of Preparation, Tasty Cakes Recipes, Bancassurance Products List, Natural Gas Production In Pakistan Province Wise, Pomegranate Tree Zone 7, Volkswagen Coolant Warning Light, | __label__pos | 0.938988 |
Image_Graph
[ class tree: Image_Graph ] [ index: Image_Graph ] [ all elements ]
Class: Image_Graph_Marker_Pointing
Source Location: /Image_Graph-0.8.0/Graph/Marker/Pointing.php
Class Overview
Image_Graph_Common
|
--Image_Graph_Element
|
--Image_Graph_Plotarea_Element
|
--Image_Graph_Marker
|
--Image_Graph_Marker_Pointing
Data marker as a 'pointing marker'.
Author(s):
Version:
• Release: 0.8.0
Copyright:
• 2003-2009 The PHP Group
Methods
Child classes:
Image_Graph_Marker_Pointing_Radial
A pointing marker in a random angle from the data
Image_Graph_Marker_Pointing_Angular
Marker that points 'away' from the graph.
Inherited Variables
Inherited Methods
Class: Image_Graph_Marker
Image_Graph_Marker::setSecondaryMarker()
Set the secondary marker
Image_Graph_Marker::setSize()
Set the 'size' of the marker
Class: Image_Graph_Element
Image_Graph_Element::height()
The height of the element on the canvas
Image_Graph_Element::setBackground()
Sets the background fill style of the element
Image_Graph_Element::setBackgroundColor()
Sets the background color of the element.
Image_Graph_Element::setBorderColor()
Sets the border color of the element.
Image_Graph_Element::setBorderStyle()
Sets the border line style of the element
Image_Graph_Element::setFillColor()
Sets the fill color of the element.
Image_Graph_Element::setFillStyle()
Sets the fill style of the element
Image_Graph_Element::setFont()
Sets the font of the element
Image_Graph_Element::setFontAngle()
Sets the font angle
Image_Graph_Element::setFontColor()
Sets the font color
Image_Graph_Element::setFontSize()
Sets the font size
Image_Graph_Element::setLineColor()
Sets the line color of the element.
Image_Graph_Element::setLineStyle()
Sets the line style of the element
Image_Graph_Element::setPadding()
Sets padding of the element
Image_Graph_Element::showShadow()
Shows shadow on the element
Image_Graph_Element::width()
The width of the element on the canvas
Image_Graph_Element::write()
Writes text to the canvas.
Image_Graph_Element::_clip()
Clip the canvas to the coordinates of the element
Class: Image_Graph_Common
Image_Graph_Common::Image_Graph_Common()
Constructor [Image_Graph_Common]
Image_Graph_Common::add()
Adds an element to the objects element list.
Image_Graph_Common::addNew()
Creates an object from the class and adds it to the objects element list.
Image_Graph_Common::hide()
Hide the element
Class Details
[line 52]
Data marker as a 'pointing marker'.
Points to the data using another marker (as start and/or end)
[ Top ]
Method Detail
Image_Graph_Marker_Pointing (Constructor) [line 91]
Image_Graph_Marker_Pointing Image_Graph_Marker_Pointing( int $deltaX, int $deltaY, Marker &$markerEnd)
Create an pointing marker, ie a pin on a board
Parameters:
int $deltaX — The the X offset from the real 'data' point
int $deltaY — The the Y offset from the real 'data' point
Marker &$markerEnd — The ending marker that represents 'the head of the pin'
[ Top ]
setMarkerStart [line 108]
void setMarkerStart( Marker &$markerStart)
Sets the starting marker, ie the tip of the pin on a board
Parameters:
Marker &$markerStart — The starting marker that represents 'the tip of the pin'
[ Top ]
Documentation generated on Mon, 11 Mar 2019 15:39:37 -0400 by phpDocumentor 1.4.4. PEAR Logo Copyright © PHP Group 2004. | __label__pos | 0.87222 |
Take the 2-minute tour ×
Mathematics Stack Exchange is a question and answer site for people studying math at any level and professionals in related fields. It's 100% free, no registration required.
Many statements of mathematics are phrased most naturally in terms of multisets. For example:
Every positive integer can be uniquely expressed as the product of a multiset of primes.
But this theorem is usually phrased more clumsily, without multisets:
Any integer greater than 1 can be written as a unique product (up to ordering of the factors) of prime numbers.¹
Apart from rearrangement of factors, $n$ can be expressed as a product of primes in one way only.²
Every integer greater than 1 can be expressed as a product of prime numbers in a way that is unique up to order.³
Many similar factorization theorems are most naturally stated in terms of multisets; try a search for the phrase "up to rearrangement" or "disregarding order". Other examples: a monic polynomial is uniquely determined by its multiset of roots, not by its set of roots. The eigenvalues of a matrix are a multiset, not a set.
Two types that are ubiquitous in mathematics are the set and the sequence. The sequence has both order and multiplicity. The set disregards both. The multiset has multiplicity without order, but is rare in mathematical literature.
When we do handle a multiset, it's usually by interpreting it as a function into $\Bbb N$. This leads to somewhat strange results. For example, suppose $M$ is the multiset of the prime factors of some integer $n$. We would like to write:
$$n = \prod_{p\in M} p$$
or perhaps even just:
$$n = \prod M$$
But if we take the usual path and embed multisets in the conventional types as a function $M:\mathrm{Primes}\to\Bbb N$, then we have to write the statement with an infinite product and significantly more notation:
$$n = \prod_{p\in\mathrm{ Primes}}p^{M(p)} $$
(For comparison, imagine how annoying it would be if sets were always understood as characteristic functions with codomain $\{0, 1\}$, and if we had to write $\sum_{x\in S}{F(x)}$ all the time instead of just $|F|$.)
Interpreting multisets as functions is infelicitous in other ways too. Except in basic set theory, we usually take for granted that the difference between a finite and an infinite set is obvious. But for multisets-as-functions, we have to say something like:
A multiset $M$ is finite if $M(x)=0$ for all but finitely many values of $x$.
The other way that multisets are sometimes handled in mathematical proofs is as (nonstrict) monotonic sequences. One often sees proofs that begin "Let $a_1\le a_2\le\ldots\le a_n$; then…". The intent here is that the $a_i$ are a multiset, and if $b_i$ are a similar sequence of the same length, then the multisets are equal if and only if $a_i = b_i$ for each $i$. Without the monotonicity, we don't get this equality property. With first-class multisets, we would just say $A=B$ and avoid a lot of verbiage.
Sets and sequences both have a full complement of standard notation and jargon. Multisets don't. There is no standard notation for the union or intersection of multisets. Part of the problem here is that there are two reasonable definitions of multiset union:
$$(M\uplus N)(x) = M(x) + N(x)$$ or $$(M\Cup N)(x) = \max(M(x), N(x))$$
For example, if $M$ and $N$ are the prime factorizations of $m$ and $n$, then $M\uplus N$ is the prime factorization of $mn$, and $M\Cup N$ is the prime factorization of $\mathrm{lcm}(m,n)$.
Similarly there is no standard notation for multiset containment, for the empty multiset, for the natural injection from sets to multisets, or for the forgetful mapping from multisets to sets. If there was standard notation for multisets, we could state potentially useful theorems like this one:
$$ m|n \quad\mbox{if and only if}\quad \mathrm{factors}(m) \prec \mathrm{factors}(n)$$
Here $\mathrm{factors}(m)$ means the multiset of prime factors of $m$, and $\prec$ means multiset containment. The analogous statement with sets, that $m|n$ if and only if factors$(m)\subset$ factors$(n)$, is completely false.
It seems to me that multisets are a strangely missing piece of math jargon. Clearly, we get along all right without them, but it seems that a lot of circumlocution would be avoided if we used multisets more freely when appropriate. Is it just a historical accident that multisets are second-class citizens of the mathematical universe?
share|improve this question
16
Historical inertia. What are you gonna do? – Qiaochu Yuan May 31 '12 at 21:40
3
Dear Mark, A nice question, with great examples. I think that the answer, as @Qiachu write, is historical inertia/accident. Cheers, – Matt E May 31 '12 at 22:06
2
Interestingly, many software container libraries ignore the concept as well; one exception that I am aware of the the C++ standard library which includes a container, quite appropriately named, called multiset; I know that .Net does not; Java might..I'm not sure where the prejudice against the concept of a multiset derives, but in practical applications, I have rolled my own on many occasions... – ItsNotObvious May 31 '12 at 22:22
1
@user12477: I've seen people post comments-that-are-too-long-for-a-comment as a series of comments instead, which I feel is preferable to posting an answer-that-is-not-really-an-answer. – Rahul May 31 '12 at 23:00
2
Very clearly explained! In that last example, don't you mean factors(m) ≺ factors(n)? – user32648 May 31 '12 at 23:00
5 Answers 5
up vote 30 down vote accepted
This question reminded me of several notes by the influential computer scientist Edsger W. Dijkstra, who spent a lot of time thinking about how our notation can affect how we think and reason formally. (He preferred the term "bag" to "multiset", as in "a bag of positive integers.")
For example:
• In writing about how computing science influenced mathematical style:
I similarly prefer products to be defined on bags of factors rather than on sequences of factors. In the last case, one of the first things one has to do is to point out that as far as the value of the product is concerned, the order in which the factors occur in the sequence is irrelevant. Why then order them in the first place?
• In discussing the notational conventions he uses, and why he uses them:
Not making superfluous distinctions should always be encouraged; it is bad enough that we don’t have a canonical representation for the unordered pair.
Indeed--- forget multisets in general: why don't we even have the unordered pair? In this note, Dijkstra observes how a lack of a standard notation for this object often prevents us from recognizing that two statements are the same. (We are often fooled by superficial differences into saying things like "it suffices" to prove one of A, B, when from a logical point of view there is no difference between A and B.)
For my part, I think that we unconsciously "avoid" the formalism of multisets because we are generally uncomfortable with unordered things as unordered things. It is far more congenial to the human mind to think in terms of ordered things whose order then might, or might not, matter.
For some reason, the unordered set concept really "caught on" and we have all of this standard terminology associated with it. I would regard this as exceptional. I would definitely not regard it as evidence that sets are truly "first-class citizens" in written mathematics:
• Have you noticed how often it is possible to simplify the language and notation of a published argument by using "arbitrary" index sets, instead of initial segments of $\mathbb{N}$? (People introduce integer subscripts that play no role in organizing the ideas of an argument all the time.)
• Have you noticed how often people explicitly rule out the empty set in situations when it only complicates a statement or proof?
We could also avoid "a lot of circumlocution" if we only made better use of firmly established things! But do we?
I think that many mathematicians simply "think in lists." I think this preference has its roots in how humans communicate. Outside of mathematics, it is almost impossible to communicate the elements of an unordered collection without choosing some arbitrary order. (e.g. "Who is going to your party next weekend?" "What do we need from the grocery store?" "What are the nations of Europe?") We naturally communicate the elements of finite sets as lists, and then understand that they are sets. "De-listing" is so natural to us that we barely notice the "circumlocutions" it requires.
Another reason I think that multisets have not caught on is terminological.
• The word "multiset" sounds too technical for what it is.
• Dijkstra's "bag," on the other hand, doesn't sound technical enough. (To me, it only sounds OK for collections of "elementary" things, like integers).
• Neither "multiset" nor "bag" gives rise to a decent-sounding subobject name.
(Note, for example, how the OP unconsciously avoided the awful word "submultiset" through repeated use of the phrase "multiset containment".)
share|improve this answer
6
Dijkstra's remarks remind me of something J.H. Conway said complaining that mathematicians were too concerned with the specific implementation of objects in terms of set theory. He said that one should simply be able to postulate, say, two kinds of ordered pairs $\langle a,b\rangle$ and $\lbrack a,b\rbrack$ with $\langle a,b\rangle = \langle c,d\rangle$ if and only if $a=c$ and $b=d$, $\lbrack a,b\rbrack = \lbrack c,d\rbrack$ if and only if $a=c$ and $b=d$, and $\langle a,b\rangle\ne\lbrack c,d\rbrack$ for all $a,b,c,d$, without having to worry about how these would be represented by sets. – MJD Jun 5 '12 at 2:18
1
Similarly one should be able to causally define an unordered pair $\def\ll{\langle\!\langle} \def\rr{\rangle\!\rangle}\ll a,b\rr$ with $\ll a,b\rr = \ll c,d\rr$ if and only if $(a=c \mathrm{\ and\ } b=d) \mathrm{\ or\ } (a=d \mathrm{\ and\ } b=c)$ without having to allay anyone's suspicions by demonstrating a particular set-theoretic object with that property. Conway wanted a someone to establish a general principle that all "reasonable" objects were definable in any "reasonable" theory, including ZF. – MJD Jun 5 '12 at 2:20
I agree with Qiaochu that historical inertia plays the largest rôle: short of independent invention, you can’t use what you’ve never seen, and if there’s a familiar alternative, you probably won’t use something that’s less familiar to you, especially if you expect it to be somewhat unfamiliar to your audience. I don’t think that I ever saw them singled out as a separate kind of object until I decided to use Scheinerman’s text for our elementary discrete math course not too many years ago.
The fact that they’re a bit awkward to formalize probably also has had some effect. Had they come into common use early enough, this probably wouldn’t have mattered: ordered pairs are also a little awkward to formalize, but in most contexts no one cares. But their widespread utility was recognized late enough that (a) formalization was more of a concern, and (b) a variety of work-arounds was already available and often in use.
Why the general utility of the concept wasn’t recognized earlier is probably an unanswerable question, though I suspect that the variety of guises in which it can appear, or perhaps better, the variety of equivalent formulations in terms of more ‘standard’ objects, has something to do with the matter. One could also point to the fact that many applications in which they play a more than incidental rôle seem to fall in the area between logic and computer science.
share|improve this answer
1
I'm pleased that you made the connection to ordered pairs, which I had not thought of before in this context. I think the comparison is quite apt. Ordered pairs also arrived surprisingly late, and I've observed before that a lot of Principia Mathematica would be superfluous if Whitehead and Russell had had a modern conception of the ordered pair. Whole chapters of PM are devoted to proving theorems about relations which, in a modern presentation, would be special cases of the theorems about sets that were proved in earlier chapters. But in $PM$ relations are a different sort than sets. – MJD Jun 1 '12 at 1:59
I'd suggest that part of the problem is the non-obviousness of operations on multisets. Take a look at the nLab page, for instance, where there's discussion about how precisely to think of morphisms, colimits, etc. with regard to multisets.
Also see the discussion on signed-multisets (a natural and immediate generalization) on haskell-cafe, where there was a large range of opinions regarding the meanings of a range of basic operations.
Arguably, if there were more attention to multisets in general, then more of these issues would be agreed on by convention or understood more broadly. On the other hand, the complexity of these issues vs. the definition of a simple set also points to why there hasn't necessarily been such attention. Also, of course, as one moves to fields like combinatorics, my sense is that multiset constructions become more common.
share|improve this answer
I could remark that what you call signed multisets on a base set $X$, if the multisets are finite (which I think is implicitly assumed in the discussion linked to), are nothing other than elements of the free Abelian group generated by $X$, a construction that is fairly well known and employed in the areas (mostly of algebra) where it is useful. – Marc van Leeuwen Jul 13 '12 at 7:09
One reason to prefer working with sequences is that they respond well to having their properties proven by induction. The syntactic representation of associative/commutative structures, by contrast, invites tricky reasoning and proofs with hard-to-spot errors in reasoning by case - if one is forced to reason about equivalence classes of sequences, then there will be no advantage and some additional complexity compared to working with sequences directly.
This problem facing the mathematician at work on a proof is faced in the automatic theorem proving community when trying to do pattern matching on associative-commutative structures. A lot of work has been done in the past thirty years applying term rewriting systems to this problem. As an example, here are how multisets of natural numbers are represented in Maude, an implementation of rewriting logic.
share|improve this answer
Here's another reason I think multisets have not entered common usage: they are very complicated! Blizard's multiset paper is just full of… stuff. Here are a couple of examples.
1. There are at least three analogs of the 'subset' relation. Writing $x\in_n M$ for "$x$ occurs in the multiset $M$ exactly $n$ times", and $x\in M$ for "$x\in_n M$ for some positive $n$", one can define:
• $A\Subset B$ if $x\in_n A$ implies $x\in_m B$ for some $m\ge n$.
• $A\sqsubset B$ if $x\in_n A$ implies $x\in_n B$
• $A\subset{\llap\sqsubset } B$ if $A\Subset B$ and $x\in B$ implies $x\in A$.
See page 43 of Blizard.
2. A union of multisets may fail to be a multiset. Let $M_i$ be the multiset that contains the single element $\ast$ with multiplicity $i$. Then $\bigcup M_i$ is not a multiset; this holds for both the $\Cup$ and $\uplus$ operations I mentioned in the original question.
share|improve this answer
4
Point 2 could be resolved by allowing arbitrary cardinal numbers as multiplicity. Then $\bigcup M_i$ would contain the single element $*$ with multiplicity $\aleph_0$. – celtschk Jul 9 '12 at 16:23
I agree that some notions are really difficult to generalize from sets to multisets. However your examples are not the most convincing. $A\Subset B$ should mean $A\Cup B=B$ and this gives the first interpretation. If arbirtary unions are not allowed, too bad, topology is used to such restrictions as well. However there is a real difficulty in defining maps between multisets (or morphisms of multisets for the categorial oriented), not to mention injections, surjections. – Marc van Leeuwen Jul 13 '12 at 7:16
@MarcvanLeeuwen, I think that's kind of missing the point. We can have a set $X$, and we can say, "Let $A$ denote a subset of $X$," and we can also say, "Let $B$ denote a multiset in $X$." And just like we can take images and preimages of subsets under functions, we can take images and preimages of multisets under functions. In neither case are subsets/multisets the objects of a category. – goblin May 7 '13 at 7:10
1
@user18921: Of course one can, and does, work with multisets without considering them objects of a category. However the real difficulty of finding a natural definition of morphism is quite remarkable (see this discussion that sclv linked to) and certainly explains why we cannot treat multiset like a natural generalisation of sets for all purposes. Also, while I agree with what you say for images, I don't for preimages. If $f(x)=y$, how does the multiplicity of $x$ in $f^{-1}(M)$ depend on the multiplicity of $y$ in the multiset $M$? – Marc van Leeuwen May 7 '13 at 9:35
1
@MarcvanLeeuwen, write $x * A$ for the multiplicity of $x$ in $A$, which is understood to be a cardinal number. Then for an arbitrary relation $f : X \rightarrow Y$ and any multiset $A \subseteq X$, we can define $y * f(A) = \sum_{x \in X : (x,y) \in f}x * A$. (From this, you can work out the answer to your question - simply view $f^{-1}$ as the converse of $f$.) Indeed, we can generalize. For an arbitrary multirelation $f : X \rightarrow Y$, we define $y * f(A) = \sum_{x \in X}[x * A][(x,y)*f]$. The point is, in both cases, the source and target of $f$ are sets, not multisets. – goblin May 7 '13 at 12:50
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.918367 |
Skip to main content
Calico Enterprise 3.19 (latest) documentation
Trace and block suspicious IPs
Big picture
Add threat intelligence feeds to Calico Enterprise to trace network flows of suspicious IP addresses, and optionally block traffic to suspicious IPs.
Value
Calico Enterprise integrates with threat intelligence feeds so you can detect when your Kubernetes clusters communicate with suspicious IPs. When communications are detected, an anomaly detection dashboard in the UI shows the full context, including which pod(s) were involved so you can analyze and remediate. You can also use a threat intelligence feed to power a dynamic deny-list, either to or from a specific group of sensitive pods, or your entire cluster.
Concepts
Pull or push threat feeds?
Calico Enterprise supports both push and pull methods for updating threat feeds. Use the pull method for fully automated threat feed updates without user intervention. Use the push method to schedule your own updates or if your threat feed is not available over HTTP(S).
Suspicious IPs: test before you block
There are many different types of threat intelligence feeds (community-curated, company-paid, and internally-developed) that you can choose to monitor in Calico Enterprise. We recommend that you assess the threat feed contents for false positives before blocking based on the feed. If you decide to block, test a subset of your workloads before rolling to production to ensure legitimate application traffic is not blocked.
Before you begin...
Required
Privileges to manage GlobalThreatFeed and GlobalNetworkPolicy.
We recommend that you turn down the aggregation of flow logs sent to Elasticsearch for configuring threat feeds. If you do not adjust flow logs, Calico Enterprise aggregates over the external IPs for allowed traffic, and threat feed searches will not provide useful results (unless the traffic is denied by policy). Go to: FelixConfiguration and set the field, flowLogsFileAggregationKindForAllowed to 1.
You can adjust the flow logs by running the following command:
kubectl patch felixconfiguration default --type='merge' -p '{"spec":{"flowLogsFileAggregationKindForAllowed":1}}'
How to
This section describes how to pull or push threat feeds to Calico Enterprise, and block traffic to a cluster for a suspicious IP.
Pull threat feed updates
To add threat feeds to Calico Enterprise for automatic updates (default is once a day), the threat feed(s) must be available using HTTP(S), and return a newline-separated list of IP addresses or prefixes in CIDR notation.
Using Manager UI
1. From the Manager UI, select Threat Feeds --> Add Feed.
2. Add your threat feed on the Add a New Threat Feed window. For example:
3. Click Save Changes.
From the **Action** menu, you can view or edit the details that you entered and can download the manifest file.
Go to the Security Events page to view events that are generated when an IP is displayed on the threat feed list. For more information, see Manage alerts. When you create a global threat feed in Manager UI, network traffic is not automatically blocked. If you find suspicious IPs on the Security Events page, you need to create a network policy to block the traffic. For help with policy, see Block traffic to a cluster.
Using CLIs
1. Create the GlobalThreatFeed YAML and save it to file. The simplest example of this looks like the following. Replace the name and the URL with your feed.
apiVersion: projectcalico.org/v3
kind: GlobalThreatFeed
metadata:
name: my-threat-feed
spec:
content: IPSet
mode: Enabled
description: 'This is my threat feed'
feedType: Custom
pull:
http:
url: https://my.threatfeed.com/deny-list
2. Add the global threat feed to the cluster.
kubectl apply -f <your_threatfeed_filename>
Go to the Security Events page to view events that are generated when an IP is displayed on the threat feed list. For more information, see Manage alerts.
Push threat feed updates
Use the push method if your threat feeds that are not in newline-delimited format, not available over HTTP, or if you prefer to push updates as they become available.
1. Create the GlobalThreatFeed YAML and save it to file. Replace the name field with your own name. The name is important in the later steps so make note of it.
apiVersion: projectcalico.org/v3
kind: GlobalThreatFeed
metadata:
name: my-threat-feed
spec:
content: IPSet
mode: Enabled
description: 'This is my threat feed'
feedType: Custom
2. Add the global threat feed to the cluster.
kubectl apply -f <your_threatfeed_filename>
3. Configure or program your threat feed to write updates to Elasticsearch. This Elasticsearch document is written using the tigera_secure_ee_threatfeeds_domainnameset.\<cluster_name>. alias and must have the ID set to the name of the global threat feed object. The doc should have a single field called ips, containing a list of IP prefixes. For example:
PUT tigera_secure_ee_threatfeeds_domainnameset.cluster./_doc/my-threat-feed/_doc/my-threat-feed
{
"ips" : ["99.99.99.99/32", "100.100.100.0/24"]
}
See the Elasticsearch document APIs for how to create and update documents in Elasticsearch.
If no alias exists in your Elasticsearch cluster, configure to write the Elastic document by specifying an index. Since the index name <tigera_secure_ee_threatfeeds_ipset.cluster.linseed-{now/s{yyyyMMdd}}-000001> contains a date pattern, make sure to send the request using the index name URL encoded.
PUT /%3Ctigera_secure_ee_threatfeeds_ipset.cluster.linseed-%7Bnow%2Fs%7ByyyyMMdd%7D%7D-000001%3E/_doc/my-threat-feed
{
"domains" : ["malicious.badstuff", "hacks.r.us"]
}
4. In Calico Enterprise Manager, go the “Security Events" page to view events that are generated when an IP is displayed on the threat feed list.
Block traffic to a cluster
Create a new/edit existing threat feed to include the globalNetworkSet stanza, setting the labels you want to use to represent the deny-listed IPs. This stanza instructs Calico Enterprise to search for flows to and from the listed IP addresses, and maintain a GlobalNetworkSet containing the IP addresses.
apiVersion: projectcalico.org/v3
kind: GlobalThreatFeed
metadata:
name: sample-global-threat-feed
spec:
content: IPSet
mode: Enabled
description: 'This is the sample global threat feed'
feedType: Custom
pull:
http:
url: https://an.example.threat.feed/deny-list
globalNetworkSet:
labels:
security-action: block
1. Add the global threat feed to the cluster.
kubectl apply -f <your_threatfeed_filename>
2. Create a GlobalNetworkPolicy that blocks traffic based on the threat feed, by selecting sources or destinations using the labels you assigned in step 1. For example, the following GlobalNetworkPolicy blocks all traffic coming into the cluster if it came from any of the suspicious IPs.
apiVersion: projectcalico.org/v3
kind: GlobalNetworkPolicy
metadata:
name: default.blockthreats
spec:
tier: default
selector: all()
types:
- Ingress
ingress:
- action: Deny
source:
selector: security-action == 'block'
3. Add the global network policy to the cluster.
kubectl apply -f <your_policy_filename>
Tutorial
In this tutorial, we’ll walk through setting up a threat feed to search for connections to suspicious IPs. Then, we’ll use the same threat feed to block traffic to those IPs.
We will use the free FEODO botnet tracker from abuse.ch that lists IP addresses associated with command and control servers. But the steps are the same for your commercial or internal threat feeds.
If you haven’t already adjusted your aggregation flows, we recommend it before you start.
Configure the threat feed
1. Create a file called feodo-tracker.yaml with the following contents:
apiVersion: projectcalico.org/v3
kind: GlobalThreatFeed
metadata:
name: feodo-tracker
spec:
content: IPSet
mode: Enabled
description: 'This is the feodo-tracker threat feed'
feedType: Custom
pull:
http:
url: https://feodotracker.abuse.ch/downloads/ipblocklist.txt
This pulls updates using the default period of once per day. See the Global Resource Threat Feed API for all configuration options.
2. Add the feed to your cluster.
kubectl apply -f feodo-tracker.yaml
Check search results
Open Calico Enterprise Manager, and navigate to the “Security Events” page. If any of your pods have been communicating with the IP addresses in the FEODO tracker feed, you will see the results listed on this page. It is normal to not see any events listed on this page.
Block pods from contacting IPs
If you have high confidence in the IP addresses listed as malicious in a threat feed, you can take stronger action than just searching for connections after the fact. For example, the FEODO tracker lists IP addresses used by command and control servers for botnets. We can configure Calico Enterprise to block all egress traffic to addresses on this list.
It is strongly recommended that you assess the contents of a threat feed for false positives before using it as a deny-list, and that you apply it to a test subset of your workloads before rolling out application or cluster-wide. Failure to do so could cause legitimate application traffic to be blocked and could lead to an outage in your application.
In this demo, we will apply the policy only to a test workload (so we do not impact other traffic).
1. Create a file called tf-ubuntu.yaml with the following contents:
apiVersion: v1
kind: Pod
metadata:
labels:
docs.tigera.io-tutorial: threat-feed
name: tf-ubuntu
spec:
nodeSelector:
kubernetes.io/os: linux
containers:
- command:
- sleep
- '3600'
image: ubuntu
name: test
2. Apply the pod configuration.
kubectl apply -f tf-ubuntu.yaml
3. Edit the feodo-tracker.yaml to include a globalNetworkSet stanza:
apiVersion: projectcalico.org/v3
kind: GlobalThreatFeed
metadata:
name: feodo-tracker
spec:
content: IPSet
mode: Enabled
description: 'This is the feodo-tracker threat feed'
feedType: Custom
pull:
http:
url: https://feodotracker.abuse.ch/downloads/ipblocklist.txt
globalNetworkSet:
labels:
docs.tigera.io-threat-feed: feodo
4. Reapply the new YAML.
kubectl apply -f feodo-tracker.yaml
5. Verify that the GlobalNetworkSet is created.
kubectl get globalnetworksets threatfeed.feodo-tracker -o yaml
Apply global network policy
We will now apply a GlobalNetworkPolicy that blocks the test workload from connecting to any IPs in the threat feed.
1. Create a file called block-feodo.yaml with the following contents:
apiVersion: projectcalico.org/v3
kind: GlobalNetworkPolicy
metadata:
name: default.block-feodo
spec:
tier: default
selector: docs.tigera.io-tutorial == 'threat-feed'
types:
- Egress
egress:
- action: Deny
destination:
selector: docs.tigera.io-threat-feed == 'feodo'
- action: Allow
2. Apply this policy to the cluster
kubectl apply -f block-feodo.yaml
Verify policy on test workload
We will verify the policy from the test workload that we created earlier.
1. Get a shell in the pod by running the following command:
kubectl exec -it tf-ubuntu -- bash
You should get a prompt inside the pod.
2. Install the ping command.
apt update && apt install iputils-ping
3. Ping a known safe IP (like 8.8.8.8, Google’s public DNS server).
ping 8.8.8.8
4. Open the FEODO tracker list and choose an IP on the list to ping. You should not get connectivity, and the pings will show up as denied traffic in the flow logs.
Additional resources
See GlobalThreatFeed resource definition for all configuration options. | __label__pos | 0.851726 |
A separable metric space and surjective, continuous function
In summary: If f(E) is finite, most people would qualify that as being countable. At any rate you are correct that the definition of separable has to allow for your dense set to be finite - for example if X is any separable space and Y is just a point.
• #1
mahler1
222
0
Homework Statement .
Let X, Y be metric spaces and ##f:X→Y## a continuous and surjective function. Prove that if X is separable then Y is separable.
The attempt at a solution.
I've tried to show separabilty of Y by exhibiting explicitly a dense enumerable subset of Y:
X is separable → ##\exists## ##E\subset X## such that E is a dense enumerable subset. Let's prove that f(E) is a dense enumerable subset of Y. Let ##y\in Y## and let ##ε_y>0##, f is surjective so there is ##x \in X## such that f(x)=y; and f is continuous, so ##f^{-1}B(f(x),ε_y)## is an open subset of X. By definition of open subset, there exists ##δ_x>0## such that ##B(x,δ_x) \subset f^{-1}B(f(x),ε_y)##. E is dense in X, then ##\exists## ##e \in E## : ##e \in B(x,δ_x)##. But this means that ##f(e) \in B(f(x),ε_y)##, which implies that f(E) is a dense subset of Y.
Here is my doubt: providing that what I've proved up to now is correct, I haven't got the slightest idea of how to prove that f(E) is enumerable. As a matter of fact, I am not at all convinced that this is even true. Couldn't be the case that the function sends all the elements of E to one single element in Y? Then f(E) would consist of only one element, I suppose that this being the case, f(E) wouldn't be enumerable in Y. Maybe what I have to prove is that the function can't send the domain E to a finite subset in Y. And as E is enumerable and f is surjective, then I would conclude f(E) is not uncountable, so the only thing f(E) can be enumerable. Am I correct in all of these?
Physics news on Phys.org
• #2
If f(E) is finite, most people would qualify that as being countable. At any rate you are correct that the definition of separable has to allow for your dense set to be finite - for example if X is any separable space and Y is just a point.
• Like
Likes 1 person
• #3
Office_Shredder said:
If f(E) is finite, most people would qualify that as being countable. At any rate you are correct that the definition of separable has to allow for your dense set to be finite - for example if X is any separable space and Y is just a point.
Maybe I am wrong and confused: I thought that a metric space was separable if it contained a dense enumerable subset, I mean, not only countable, but also not finite. I will check this in my textbook. If we only need to ask for the dense subset to be countable, then proving that a surjective function from a countable set to another implies that the codomain has to be countable is enough.
• #4
Enumerable typically just means countable - I think your textbook intended to allow finite subsets. At any rate the common usage of separable allows for a finite dense subset (for example you can check wikipedia).
• Like
Likes 1 person
1. What is a separable metric space?
A separable metric space is a mathematical concept in topology that describes a space where every point can be approximated by a sequence of points from a countable subset of the space. This means that the space has a dense subset, which is a set of points that are "close" to every point in the space.
2. How is a separable metric space different from a metric space?
A metric space is a mathematical concept that describes a space where the distance between any two points can be measured. A separable metric space is a type of metric space that has the additional property of having a countable dense subset.
3. What is a surjective function?
A surjective function is a type of function in mathematics that maps every element in the target set to at least one element in the domain set. In other words, every element in the output set has a corresponding input element.
4. How does a surjective function relate to a separable metric space?
In the context of a separable metric space, a surjective function is often used to map the dense subset to the entire space. This means that the function "covers" the entire space and can be used to approximate any point in the space with a point from the dense subset.
5. What is the significance of a continuous function in a separable metric space?
A continuous function is a type of function in mathematics that preserves the "closeness" of points. In a separable metric space, a continuous function is important because it ensures that the dense subset remains dense in the target space. This means that the approximations of points from the dense subset will still be "close" to the actual points in the space.
Similar threads
• Calculus and Beyond Homework Help
Replies
23
Views
1K
• Calculus and Beyond Homework Help
Replies
2
Views
851
• Calculus and Beyond Homework Help
Replies
1
Views
488
• Calculus and Beyond Homework Help
Replies
20
Views
2K
• Calculus and Beyond Homework Help
Replies
12
Views
1K
• Calculus and Beyond Homework Help
Replies
2
Views
1K
• Calculus and Beyond Homework Help
Replies
1
Views
1K
• Calculus and Beyond Homework Help
Replies
5
Views
1K
• Calculus and Beyond Homework Help
Replies
2
Views
746
• Calculus and Beyond Homework Help
Replies
2
Views
1K
Back
Top | __label__pos | 0.999252 |
p3zo p3zo - 6 months ago 55
Scala Question
merge spark dStream with variable to saveToCassandra()
I have a
DStream[String, Int
] with pairs of word counts, e.g.
("hello" -> 10)
. I want to write these counts to cassandra with a step index. The index is initialized as
var step = 1
and is incremented with each microbatch processed.
The cassandra table created as:
CREATE TABLE wordcounts (
step int,
word text,
count int,
primary key (step, word)
);
When trying to write the stream to the table...
stream.saveToCassandra("keyspace", "wordcounts", SomeColumns("word", "count"))
... I get
java.lang.IllegalArgumentException: Some primary key columns are missing in RDD or have not been selected: step
.
How can I prepend the
step
index to the stream in order to write the three columns together?
I'm using spark 2.0.0, scala 2.11.8, cassandra 3.4.0 and spark-cassandra-connector 2.0.0-M3.
Answer
As noted, while the Cassandra table expects something of the form (Int, String, Int), the wordCount DStream is of type DStream[(String, Int)], so for the call to saveToCassandra(...) to work, we need a DStream of type DStream[(Int, String, Int)].
The tricky part in this question is how to bring a local counter, that is by definition only known in the driver, up to the level of the DStream.
To do that, we need to do two things: "lift" the counter to a distributed level (in Spark, we mean "RDD" or "DataFrame") and join that value with the existing DStream data.
Departing from the classic Streaming word count example:
// Split each line into words
val words = lines.flatMap(_.split(" "))
// Count each word in each batch
val pairs = words.map(word => (word, 1))
val wordCounts = pairs.reduceByKey(_ + _)
We add a local var to hold the count of the microbatches:
@transient var batchCount = 0
It's declared transient, so that Spark doesn't try to close over its value when we declare transformations that use it.
Now the tricky bit: Within the context of a DStream transformation, we make an RDD out of that single variable and join it with underlying RDD of the DStream using cartesian product:
val batchWordCounts = wordCounts.transform{ rdd =>
batchCount = batchCount + 1
val localCount = sparkContext.parallelize(Seq(batchCount))
rdd.cartesian(localCount).map{case ((word, count), batch) => (batch, word, count)}
}
(Note that a simple map function would not work, as only the initial value of the variable would be captured and serialized. Therefore, it would look like the counter never increased when looking at the DStream data.
Finally, now that the data is in the right shape, save it to Cassandra:
batchWordCounts.saveToCassandra("keyspace", "wordcounts") | __label__pos | 0.987233 |
Opened 11 days ago
Last modified 32 hours ago
#15149 new bug
Identical distinct type family fields miscompiled
Reported by: NeilMitchell Owned by:
Priority: normal Milestone: 8.6.1
Component: Compiler Version: 8.4.2
Keywords: ORF Cc: ndmitchell@…, adamgundry
Operating System: Unknown/Multiple Architecture: Unknown/Multiple
Type of failure: GHC rejects valid program Test Case:
Blocked By: Blocking:
Related Tickets: Differential Rev(s):
Wiki Page:
Description
Given the code:
-- An.hs
{-# LANGUAGE TypeFamilies #-}
module An where
data family An c :: *
-- AnInt.hs
{-# LANGUAGE TypeFamilies #-}
module AnInt where
import An
data instance An Int = AnInt {an :: Int} deriving Show
-- AnDouble.hs
{-# LANGUAGE TypeFamilies #-}
module AnDouble where
import An
data instance An Double = AnDouble {an :: Double} deriving Show
-- Main.hs
{-# LANGUAGE DisambiguateRecordFields #-}
module Main where
import AnInt
import AnDouble
main = print (AnDouble{an=1}, AnInt{an=1})
I would expect this code to work. In reality it fails at runtime with GHC 8.2.2:
Main.hs:4:15-28: warning: [-Wmissing-fields]
* Fields of `AnDouble' not initialised: an
* In the expression: AnDouble {an = 1}
In the first argument of `print', namely
`(AnDouble {an = 1}, AnInt {an = 1})'
In the expression: print (AnDouble {an = 1}, AnInt {an = 1})
|
6 | main = print (AnDouble{an=1}, AnInt{an=1})
| ^^^^^^^^^^^^^^
*** Exception: Main.hs:4:15-28: Missing field in record construction an
And fails at compile time in GHC 8.4.2:
Main.hs:4:31-41: error:
* Constructor `AnInt' does not have field `an'
* In the expression: AnInt {an = 1}
In the first argument of `print', namely
`(AnDouble {an = 1}, AnInt {an = 1})'
In the expression: print (AnDouble {an = 1}, AnInt {an = 1})
|
6 | main = print (AnDouble{an=1}, AnInt{an=1})
| ^^^^^^^^^^^
This code was extracted from a real example, where this bug is pretty fatal, as I haven't been able to find any workarounds (without just avoiding clashing record fields).
Change History (3)
comment:1 Changed 11 days ago by RyanGlScott
Keywords: ORF added
comment:2 Changed 35 hours ago by simonpj
Cc: adamgundry added
I investigated. Here is what is going on:
• When compiling module An, there are two an's in scope
• You might resaonably think that with DisamgiguateRecordFields, the an in AnInt { an = 1 } is obviously the an from module AnInt.
• But in fact GHC's renamer uses the type constructor, not the data constructor to disambiguate which an you mean. And both an's have the same "parent", namely the type constructor An.
This was fine before data families, because a single type constructor could not have data constructors with distinct an record fields. But now it can.
A short term fix is to complain about ambiguity rather than arbitrarily picking one (as is done now). This happens here in TcExpr:
tcRecordField con_like flds_w_tys (L loc (FieldOcc sel_name lbl)) rhs
| Just field_ty <- assocMaybe flds_w_tys sel_name
= ...
That assocMaybe just picks the first. So we could fix that.
But how can we fix it properly? After all, all the information is there, staring us in the face.
• One way forward might be to say that the data constructor AnInt is the "parent" of AnInt.an, and the type constructor An is the parent of the data constructor AnInt. But that change would mean we had a multi-level parent structure, with consequences that are hard to foresee.
• But I think a better way is to stop trying to make the choice in the renamer. Instead in a HsRecordFields structure, keep the field names as not-yet-looked-up OccNames in the renamer, and look them up in the typechecker. At that point, we have the data constructor available in its full glory and don't need to bother with the tricky parent structures in the renamer.
Adam, do you think that would work?
comment:3 Changed 32 hours ago by adamgundry
I think this would work, and would amount to eliminating the distinction between HsRecField (containing FieldOcc) and HsRecUpdField (containing AmbiguousFieldOcc). At the moment, the former is used for record construction and pattern matching (fields always resolved by the renamer), while the latter is used for selection and update (ambiguous fields resolved by the type-checker). Here "ambiguous" really means "ambiguous from the renamer's perspective, but not necessarily the type-checker".
It would probably be simpler to defer all field resolution to the type-checker, though we've also considered going in the opposite direction, and moving all field resolution back to the renamer (see https://github.com/ghc-proposals/ghc-proposals/pull/84). I'm not really sure which is better!
There's an awkward corner if we were to defer all field resolution to the type-checker, which is that Ambiguous fields are not currently supported by DsMeta. That is, using them inside a TH bracket will fail with a "not supported" error. The basic problem is that DsMeta works on renamed syntax, even though it runs after type-checking. Would that be difficult to change?
Note: See TracTickets for help on using tickets. | __label__pos | 0.958077 |
Rumus Pythagoras: Konsep dan Aplikasi dalam Kehidupan Sehari-hari
Rumus Pythagoras: Konsep dan Aplikasi dalam Kehidupan Sehari-hari
Rumus PythagorasSource: bing.com
Anda pasti sudah tidak asing lagi dengan rumus Pythagoras, bukan? Rumus yang biasanya diajarkan di sekolah menengah ini sangat penting dalam matematika dan memiliki aplikasi yang luas dalam kehidupan sehari-hari. Dalam artikel ini, kami akan membahas konsep dasar dari rumus Pythagoras, serta beberapa contoh penggunaannya.
Konsep Dasar Rumus Pythagoras
Rumus Pythagoras ditemukan oleh matematikawan Yunani kuno bernama Pythagoras. Rumus ini digunakan untuk menghitung sisi miring segitiga siku-siku, jika diketahui panjang kedua sisi yang lain. Konsep dasar dari rumus Pythagoras adalah teorema Pythagoras, yang menyatakan bahwa kuadrat dari sisi miring segitiga siku-siku sama dengan jumlah kuadrat dari kedua sisi lainnya. Secara matematis, rumus Pythagoras dapat dituliskan sebagai berikut:
a2 + b2 = c2
Di mana a dan b adalah panjang sisi-sisi yang membentuk sudut siku-siku, dan c adalah panjang sisi miring segitiga siku-siku.
Contoh Penggunaan Rumus Pythagoras
Rumus Pythagoras dapat digunakan dalam berbagai aplikasi, salah satunya adalah untuk menghitung jarak antara dua titik dalam sistem koordinat. Misalnya, jika kita ingin menghitung jarak antara titik A(-2, 3) dan titik B(4, -1), kita dapat mengikuti langkah-langkah berikut:
1. Hitung selisih koordinat x dan y untuk kedua titik: xB – xA = 4 – (-2) = 6 dan yB – yA = -1 – 3 = -4.
2. Hitung kuadrat dari selisih koordinat: (6)2 + (-4)2 = 36 + 16 = 52.
3. Hitung akar kuadrat dari hasil sebelumnya: √52 ≈ 7,21.
Cek Juga Soal Bahasa Inggris Kelas 5 Semester 2 Dan Kunci Jawaban
Jadi, jarak antara titik A dan B adalah sekitar 7,21 satuan.
Selain itu, rumus Pythagoras juga dapat digunakan untuk menghitung jarak tempuh dalam perjalanan. Misalnya, jika kita ingin menghitung jarak tempuh dalam perjalanan dari titik A ke titik B yang membentuk sudut siku-siku, kita dapat menghitung jarak langsung antara kedua titik menggunakan rumus Pythagoras.
Kesimpulan
Rumus Pythagoras adalah rumus matematika penting yang digunakan untuk menghitung sisi miring segitiga siku-siku, serta memiliki aplikasi yang luas dalam kehidupan sehari-hari, seperti dalam menghitung jarak antara dua titik dalam sistem koordinat dan jarak tempuh dalam perjalanan. Dengan memahami konsep dasar dari rumus Pythagoras dan cara mengaplikasikannya, kita dapat memecahkan berbagai masalah matematika dan non-matematika yang muncul dalam kehidupan sehari-hari.
Artikel Terkait
Pertanyaan yang Sering Diajukan
Apa itu rumus Pythagoras?
Rumus Pythagoras adalah rumus matematika yang digunakan untuk menghitung sisi miring segitiga siku-siku, jika diketahui panjang kedua sisi yang lain. Konsep dasar dari rumus Pythagoras adalah teorema Pythagoras, yang menyatakan bahwa kuadrat dari sisi miring segitiga siku-siku sama dengan jumlah kuadrat dari kedua sisi lainnya.
Bagaimana cara mengaplikasikan rumus Pythagoras?
Rumus Pythagoras dapat diaplikasikan dalam berbagai situasi, seperti untuk menghitung jarak antara dua titik dalam sistem koordinat atau jarak tempuh dalam perjalanan. Untuk mengaplikasikan rumus Pythagoras, kita perlu mengikuti langkah-langkah yang sesuai dengan situasi yang dihadapi.
Apa saja contoh penggunaan rumus Pythagoras?
Rumus Pythagoras dapat digunakan dalam berbagai aplikasi, seperti untuk menghitung jarak antara dua titik dalam sistem koordinat, jarak tempuh dalam perjalanan, dan menghitung luas bidang datar yang membentuk segitiga siku-siku.
Cek Juga Matematika Kelas 4 Kurikulum Merdeka Semester 1
Apa itu teorema Pythagoras?
Teorema Pythagoras adalah konsep matematika yang menyatakan bahwa kuadrat dari sisi miring segitiga siku-siku sama dengan jumlah kuadrat dari kedua sisi lainnya. Teorema ini merupakan dasar bagi rumus Pythagoras.
Mengapa rumus Pythagoras penting?
Rumus Pythagoras penting karena memiliki aplikasi yang luas dalam kehidupan sehari-hari, seperti dalam menghitung jarak antara dua titik dalam sistem koordinat dan jarak tempuh dalam perjalanan. Selain itu, rumus Pythagoras juga merupakan dasar bagi konsep matematika lainnya.
Related video of Rumus Pythagoras: Konsep dan Aplikasi dalam Kehidupan Sehari-hari
By admin | __label__pos | 0.998092 |
Where is contact / calendar data stored?
Discussion in 'Motorola Droid X' started by dtmfcc, Sep 1, 2010.
1. dtmfcc
dtmfcc New Member
Joined:
Sep 1, 2010
Messages:
3
Likes Received:
0
Trophy Points:
1
Ratings:
+0
My phone will be here soon. I have HIPAA privacy concerns regarding contact /calendar data. Was going to use Companion Link / Dejaoffice for private USB sync, but just found out that data is stored on the removable SD card, which is worrisome.
If I used a MS Exchange server (which might be hard as a single user), where would the contact / calendar data be stored? Where is the native Android contact/calendar data stored?
Does anyone have a referral to a hosted exchange server with encryption for privacy.
Thanks!
2. crspang
crspang Member
Joined:
Dec 15, 2009
Messages:
691
Likes Received:
0
Trophy Points:
16
Location:
Lexington, SC
Ratings:
+0
In the google cloud.
3. crspang
crspang Member
Joined:
Dec 15, 2009
Messages:
691
Likes Received:
0
Trophy Points:
16
Location:
Lexington, SC
Ratings:
+0
I have to be HIPPA compliant also. The folks that did my accreditation didn't have a problem with it. I have also had several Medicare inspections and passed all those.
4. dtmfcc
dtmfcc New Member
Joined:
Sep 1, 2010
Messages:
3
Likes Received:
0
Trophy Points:
1
Ratings:
+0
Thanks for your reply. Do you use the Google sync method, or something else? Also, is there any reference you could point me to that says using the Google cloud is ok for HIPAA?
Thanks so much!
5. crspang
crspang Member
Joined:
Dec 15, 2009
Messages:
691
Likes Received:
0
Trophy Points:
16
Location:
Lexington, SC
Ratings:
+0
All of my contacts and calender info are my business gmail account which is a secure account, the main gmail account synced to my phone is the same. I enabled the password lock to open the phone from sleep. I don't have any reference for you sorry.
There are several apps in the market that will allow you to remotely wipe data if your phone is lost or stolen.
6. wmscottmc
wmscottmc Member
Joined:
Jul 6, 2010
Messages:
217
Likes Received:
0
Trophy Points:
16
Ratings:
+0
Can anybody verify that one of these "remote wipe" apps actually works, and that they do not require the phone to be rooted?
Thanks.
Search tags for this page
android calendar file location
,
android calendar storage location
,
where are contacts files stored on a motorola droid pro
,
where are contacts stored in android
,
where are contacts stored on android
,
where are contacts stored on android phone
,
where are my android contacts stored on my droid razr
,
where does android store calendar data
,
where is android calendar data stored
,
where is calendar data stored on android | __label__pos | 0.995466 |
ODC
Webopedia Staff
Last Updated June 23, 2021 7:07 am
Short for on-demand computing, a typically enterprise-level computing model in which the technology and computing resources are allocated to the organization and its individual users on an as-needed basis. For example, computing resources such as CPU cycles, bandwidth availability, storage and applications can be channeled to users based on the tasks they are performing at specified times. If one group of users is working with bandwidth-heavy applications, for instance, the bandwidth can be allocated specifically to them and diverted away from users who do not need the bandwidth at that moment. In another scenario, an organization that is collecting large amounts of data may have adequate computing resources to collect the data but needs extra computing resources to analyze all of the data collected, in which case it could outsource its needs to a server farm that would provide the extra boost of resources but only at the specified times.
ODC resources may come from within the enterprise, or the organization may outsource its computing needs to a third-party service provider. The benefit of ODC is that the enterprise uses its resources more efficiently by only making available what the user needs at a specific time. For the enterprise outsourcing its computing needs, under this model it would only pay for resources that are used.
On-demand computing also is referred to as utility computing. | __label__pos | 0.546151 |
Clerk.js 2 is a faster and much more flexible version of our JavaScript library that makes installing Clerk.io on any webshop a breeze.
However, since the two versions work slightly differently, you need to follow these steps to successfully upgrade.
The two main differences in Clerk.js 2 is that the Designs in my.clerk.io use the Liquid templating language, but they can also easily be created using the Design Editor.
Step 1: Converting Designs
Since Clerk.js 2 has a different approach Designs, you need to create new ones.
You can create your Clerk.js 2 Designs in one of two ways:
1.1 Start by going to my.clerk.io -> Recommendations / Search -> Designs and click New Design:
1.2 On the following screen, give your Design a Name (we recommend adding "V2" so its obvious that you are using Clerk.js2).
1.3. Choose Design Type: Product Slider (Design Editor), Exit Intent or Product Slider (HTML).
1.4. When you are done, click Create Design
1.5. In the Design Editor, click any of the existing elements like the name, image, button, etc. to edit it, or drag-and-drop new elements to the Design to add more information about products.
1.6. Click Save Design when you are done, and go to Step 2 in the guide.
1.7. Lastly, go to Recommendations / Search -> Content and change your Clerk.io Content to use your new Design.
1.8. Click Update Content. This will temporarily cause them to not show up on your webshop until you are done with Step 2. Choose the new Design for all Content that should be updated.
1.9. There! You are now ready to switch over to Clerk.js 2.
Step 2: Upgrading your plugin
WARNING: Remember to take backups of any modified files, as they will be overwritten.
Upgrading the Plugin can be done directly from the WooCommerce admin.
Start by going to Plugin->Add New
Then, search for Clerk in the search-field to the right, and click Update Now.
Thats it! Now you are running the latest version of Clerk.io for WooCommerce and Clerk.js 2 is running on your webshop!
If you already have the latest version, this button will simply say Active.
The full documentation for Clerk.js 2 can be found here:
https://docs.clerk.io/docs/clerkjs-quick-start
Did this answer your question? | __label__pos | 0.76958 |
Scilab Home page | Wiki | Bug tracker | Forge | Mailing list archives | ATOMS | File exchange
Please login or create an account
Change language to: Français - Português - 日本語 - Русский
Please note that the recommended version of Scilab is 6.1.1. This page might be outdated.
See the recommended documentation of this function
Scilab help >> Optimization and Simulation > Neldermead > neldermead
neldermead
Provides direct search optimization algorithms.
SYNOPSIS
newobj = neldermead_new ()
this = neldermead_destroy (this)
this = neldermead_configure (this,key,value)
value = neldermead_cget (this,key)
value = neldermead_get ( this , key )
this = neldermead_search ( this )
this = neldermead_restart ( this )
[ this , result ] = neldermead_function ( this , x )
stop = neldermead_defaultoutput(state, data)
Description
This class provides several direct search optimization algorithms based on the simplex method.
The optimization problem to solve is the minimization of a cost function, with bounds and nonlinear constraints
min f(x)
l_i <= x_i <= h_i, i = 1,n
g_i(x) >= 0, i = 1,nbineq
where
n
number of variables
nbineq
number of inequality constraints
The provided algorithms are direct search algorithms, i.e. algorithms which do not use the derivative of the cost function. They are based on the update of a simplex, which is a set of k>=n+1 vertices, where each vertex is associated with one point and one function value.
The following algorithms are available :
Spendley, Hext and Himsworth fixed shape simplex method
This algorithm solves an unconstrained optimization problem with a fixed shape simplex made of k=n+1 vertices.
Nelder and Mead variable shape simplex method
This algorithm solves an unconstrained optimization problem with a variable shape simplex made of k=n+1 vertices.
Box complex method
This algorithm solves an constrained optimization problem with a variable shape simplex made of an arbitrary k number of vertices (k=2n is recommended by Box).
See the demonstrations, in the Optimization section, for an overview of this component.
See the "Nelder-Mead User's Manual" on Scilab's wiki and on the Scilab forge for further information.
Design
The neldermead component is built on top of the optimbase and optimsimplex components.
Functions
The following functions are available.
newobj = neldermead_new ()
Creates a new neldermead object.
newobj
The new object.
this = neldermead_destroy (this)
Destroy the given object.
this
The current object.
this = neldermead_configure (this,key,value)
Configure the current object with the given value for the given key.
this
The current object.
key
the key to configure. The following keys are available.
Basic.
-numberofvariables
a 1-by-1 matrix of doubles, positive, integer value, the number of variables to optimize (default numberofvariables = 0).
-function
a function or a list, the objective function. This function computes the value of the cost and the non linear constraints, if any.
There is no default value, i.e. the user must provide f.
See below for the details of the communication between the optimization system and the cost function.
-x0
a n-by-1 matrix of doubles, where n is the number of variables, the initial guess.
There is no default value, i.e. the user must provide x0.
Output.
-outputcommand
a function or a list, a function which is called back for output.
The default output function is empty, meaning that there is no output.
See below for the details of the communication between the optimization system and the output command function.
-storehistory
a 1-by-1 matrix of booleans, set to %t to enable the history storing (default storehistory = %f).
-verbose
a 1-by-1 matrix of doubles, positive, integer value, set to 1 to enable verbose logging (default verbose = 0).
-verbosetermination
a 1-by-1 matrix of doubles, positive, integer value, set to 1 to enable verbose termination logging (default verbosetermination = 0).
Bounds and constraints.
-boundsmin
a n-by-1 matrix of doubles, the minimum bounds for the parameters where n is the number of variables (default boundsmin = [], i.e. there are no minimum bounds).
-boundsmax
a n-by-1 matrix of doubles, the maximum bounds for the parameters where n is the number of variables (default boundsmax = [], i.e. there are no maximum bounds).
-nbineqconst
a 1-by-1 matrix of doubles, positive, integer value, the number of inequality constraints (default nbineqconst = 0).
Initialization.
-simplex0method
a 1-by-1 matrix of strings, the method to use to compute the initial simplex (default simplex0method = "axes"). The first vertex in the simplex is always the initial guess associated with the -x0 option. The following methods are available :
"given"
the coordinates associated with the -coords0 option are used to compute the initial simplex, with arbitrary number of vertices.
This allow the user to setup the initial simplex by a specific method which is not provided by the current component (for example with a simplex computed from a design of experiments). This allows also to configure the initial simplex so that a specific behaviour of the algorithm an be reproduced (for example the Mac Kinnon test case).
The given matrix is expected to have n rows and k columns, where n is the dimension of the problem and k is the number of vertices.
"axes"
the simplex is computed from the coordinate axes and the length associated with the -simplex0length option.
"spendley"
the simplex is computed so that it is regular with the length associated with the -simplex0length option (i.e. all the edges have the same length).
"pfeffer"
the simplex is computed from a heuristic, in the neighborhood of the initial guess. This initial simplex depends on the -simplex0deltausual and -simplex0deltazero.
"randbounds"
the simplex is computed from the bounds and a random number. This option is available only if bounds are available : if bounds are not available, an error is generated. This method is usually associated with Box's algorithm. The number of vertices in the simplex is taken from the -boxnbpoints option.
-coords0
a nbve-by-n matrix of doubles, where nbve is the number of vertices and n is the number of variables, the coordinates of the vertices of the initial simplex (default coords0=[]). If the -simplex0method option is set to "given", these coordinates are used to compute the initial simplex.
-simplex0length
a 1-by-1 matrix of doubles, the length to use when the initial simplex is computed with the "axes" or "spendley" methods (default simplex0length = 1). If the initial simplex is computed from "spendley" method, the length is expected to be a scalar value. If the initial simplex is computed from "axes" method, it may be either a scalar value or a vector of values, with rank n, where n is the number of variables.
-simplex0deltausual
a 1-by-1 matrix of doubles, the relative delta for non-zero parameters in "pfeffer" method (default simplex0deltausual = 0.05).
-simplex0deltazero
a 1-by-1 matrix of doubles, the absolute delta for non-zero parameters in "pfeffer" method (default simplex0deltazero = 0.0075).
Termination.
-maxfunevals
a 1-by-1 matrix of doubles, positive, integer value, the maximum number of function evaluations (default maxfunevals = 100). If this criteria is triggered, the status of the optimization is set to "maxfuneval".
-maxiter
a 1-by-1 matrix of doubles, positive, integer value, the maximum number of iterations (default maxiter = 100). If this criteria is triggered, the status of the optimization is set to "maxiter".
-tolfunabsolute
a 1-by-1 matrix of doubles, positive, the absolute tolerance for the function value (default tolfunabsolute = 0).
-tolfunrelative
a 1-by-1 matrix of doubles, positive, the relative tolerance for the function value (default tolfunrelative = %eps).
-tolfunmethod
a 1-by-1 matrix of booleans, set to %t to enable termination with tolerance on function value (default tolfunmethod = %f).
If this criteria is triggered, the status of the optimization is set to "tolf".
-tolxabsolute
a 1-by-1 matrix of doubles, positive, the absolute tolerance on x (default tolxabsolute = 0).
-tolxrelative
a 1-by-1 matrix of doubles, positive, the relative tolerance on x (default tolxrelative = sqrt(%eps)).
-tolxmethod
a 1-by-1 matrix of booleans, set to %t to enable the tolerance on x in the termination criteria (default tolxmethod = %t).
If this criteria is triggered, the status of the optimization is set to "tolx".
-tolsimplexizemethod
a 1-by-1 matrix of booleans, set to %f to disable the tolerance on the simplex size (default tolsimplexizemethod = %t). If this criteria is triggered, the status of the optimization is set to "tolsize".
When this criteria is enabled, the values of the options -tolsimplexizeabsolute and -tolsimplexizerelative are used in the termination criteria. The method to compute the size is the "sigmaplus" method.
-tolsimplexizeabsolute
a 1-by-1 matrix of doubles, positive, the absolute tolerance on the simplex size (default tolsimplexizeabsolute = 0).
-tolsimplexizerelative
a 1-by-1 matrix of doubles, positive, the relative tolerance on the simplex size (default tolsimplexizerelative = %eps).
-tolssizedeltafvmethod
a 1-by-1 matrix of booleans, set to %t to enable the termination criteria based on the size of the simplex and the difference of function value in the simplex (default tolssizedeltafvmethod = %f). If this criteria is triggered, the status of the optimization is set to "tolsizedeltafv".
This termination criteria uses the values of the options -tolsimplexizeabsolute and -toldeltafv. This criteria is identical to Matlab's fminsearch.
-toldeltafv
a 1-by-1 matrix of doubles, positive, the absolute tolerance on the difference between the highest and the lowest function values (default toldeltafv = %eps).
Algorithm.
-method
a 1-by-1 matrix of strings, the name of the algorithm to use (default method = "variable"). The following methods are available :
"fixed"
the Spendley et al. fixed simplex shape algorithm. This algorithm is for unconstrained problems (i.e. bounds and non linear constraints are not taken into account)
"variable"
the Nelder-Mead variable simplex shape algorithm. This algorithm is for unconstrained problems (i.e. bounds and non linear constraints are not taken into account)
"box"
the Box complex algorithm. This algorithm takes into account bounds and nonlinear inequality constraints.
"mine"
the user-defined algorithm, associated with the -mymethodoption. See below for details.
-mymethod
a function, a user-derined simplex algorithm. See below for details (default is empty).
Options of the "variable" algorithm.
-rho
a 1-by-1 matrix of doubles, the reflection coefficient. This parameter is used when the -method option is set to "fixed" or "variable" (default rho = 1).
-chi
a 1-by-1 matrix of doubles, the expansion coefficient. This parameter is used when the -method option is set to "variable" (default chi = 2).
-gamma
a 1-by-1 matrix of doubles, the contraction coefficient. This parameter is used when the -method option is set to "variable" (default gamma = 0.5).
-sigma
a 1-by-1 matrix of doubles, the shrinkage coefficient. This parameter is used when the -method option is set to "fixed" or "variable" (default sigma = 0.5).
Option of "box" algorithm.
-scalingsimplex0
a 1-by-1 matrix of strings, the algorithm used to scale the initial simplex into the nonlinear constraints (default scalingsimplex0 = "tox0"). The following two algorithms are provided :
• "tox0": scales the vertices toward the initial guess.
• "tocenter": scales the vertices toward the centroid, as recommended by Box.
If the centroid happens to be unfeasible, because the constraints are not convex, the scaling of the initial simplex toward the centroid may fail. Since the initial guess is always feasible, scaling toward the initial guess cannot fail. The default value is "tox0".
-boxnbpoints
a 1-by-1 matrix of doubles, positive, integer value, the number of points in the initial simplex, when the -simplex0method is set to "randbounds" (default boxnbpoints = 2*n, where n is the number of variables of the problem). The value of this option is also use to update the simplex when a restart is performed and the -restartsimplexmethod option is set to "randbounds".
-boxineqscaling
a 1-by-1 matrix of doubles, in the interval [0,1], the scaling coefficient used to scale the trial point for function improvement or into the constraints of Box's algorithm (default boxineqscaling = 0.5).
-guinalphamin
a 1-by-1 matrix of doubles, positive, the minimum value of alpha when scaling the vertices of the simplex into nonlinear constraints in Box's algorithm (default guinalphamin = 1.e-5).
-boxreflect
a 1-by-1 matrix of doubles, positive, the reflection factor in Box's algorithm (default = 1.3).
-boxtermination
a 1-by-1 matrix of booleans, set to %t to enable Box termination criteria (default boxtermination = %f).
-boxtolf
a 1-by-1 matrix of doubles, positive, the absolute tolerance on difference of function values in the simplex, suggested by Box (default boxtolf = 1.e-5). This tolerance is used if the -boxtermination option is set to %t.
-boxnbmatch
a 1-by-1 matrix of doubles, positive, integer value, the number of consecutive match of Box termination criteria (default boxnbmatch = 5).
-boxboundsalpha
a 1-by-1 matrix of doubles, positive, the parameter used to project the vertices into the bounds in Box's algorithm (default boxboundsalpha = 1.e-6).
Auto-Restart.
-kelleystagnationflag
a 1-by-1 matrix of booleans, set to %t to enable the termination criteria using Kelley's stagnation detection, based on sufficient decrease condition (default kelleystagnationflag = %f). If this criteria is triggered, the status of the optimization is set to "kelleystagnation".
-kelleynormalizationflag
a 1-by-1 matrix of booleans, set to %f to disable the normalization of the alpha coefficient in Kelley's stagnation detection, i.e. use the value of the option -kelleystagnationalpha0 as is (default kelleynormalizationflag = %t, i.e. the simplex gradient of the initial simplex is taken into account in the stagnation detection).
-kelleystagnationalpha0
a 1-by-1 matrix of doubles, the parameter used in Kelley's stagnation detection (default kelleystagnationalpha0 = 1.e-4).
-restartflag
a 1-by-1 matrix of booleans, set to %t to enable the automatic restart of the algorithm (default restartflag = %f).
-restartdetection
a 1-by-1 matrix of strings, the method to detect if the automatic restart must be performed (default restartdetection = "oneil"). The following methods are available:
"oneill"
the factorial local optimality test by O'Neill is used. If the test finds a local point which is better than the computed optimum, a restart is performed.
"kelley"
the sufficient decrease condition by O'Neill is used. If the test finds that the status of the optimization is "kelleystagnation", a restart is performed. This status may be generated if the -kelleystagnationflag option is set to %t.
The default method is "oneill".
-restartmax
a 1-by-1 matrix of doubles, the maximum number of restarts, when automatic restart is enabled via the -restartflag option (default restartmax=3).
-restarteps
a 1-by-1 matrix of doubles, the relative epsilon value used to check for optimality in the factorial O'Neill restart detection (default restarteps = %eps).
-restartstep
a 1-by-1 or a n-by-1 matrix of doubles, positive, where n is the number of variables in the problem, the absolute step length used to check for optimality in the factorial O'Neill restart detection (default restartstep = 1).
-restartsimplexmethod
a 1-by-1 matrix of strings, the method to compute the initial simplex after a restart (default restartsimplexmethod = "oriented"). The following methods are available.
"given"
the coordinates associated with the -coords0 option are used to compute the initial simplex, with arbitrary number of vertices.
This allow the user to setup the initial simplex by a specific method which is not provided by the current component (for example with a simplex computed from a design of experiments). This allows also to configure the initial simplex so that a specific behaviour of the algorithm an be reproduced (for example the Mc Kinnon test case).
The given matrix is expected to have n rows and k columns, where n is the dimension of the problem and k is the number of vertices.
"axes"
the simplex is computed from the coordinate axes and the length associated with the -simplex0length option.
"spendley"
the simplex is computed so that it is regular with the length associated with the -simplex0length option (i.e. all the edges have the same length).
"pfeffer"
the simplex is computed from a heuristic, in the neighborhood of the initial guess. This initial simplex depends on the -simplex0deltausual and -simplex0deltazero.
"randbounds"
the simplex is computed from the bounds and a random number. This option is available only if bounds are available : if bounds are not available, an error is generated. This method is usually associated with Box's algorithm. The number of vertices in the simplex is taken from the -boxnbpoints option.
"oriented"
the simplex is computed so that it is oriented, as suggested by C.T. Kelley.
The default method is "oriented".
value
the value.
value = neldermead_cget (this,key)
Get the value for the given key. If the key is unknown, generates an error.
this
The current object.
key
the name of the key to quiery. The list of available keys is the same as for the neldermead_configure function.
value = neldermead_get ( this , key )
Get the value for the given key. If the key is unknown, generates an error.
Most fields are available only after an optimization has been performed with one call to the neldermead_search method.
this
The current object.
key
the key to get.
The following keys are available :
-funevals
the number of function evaluations
-iterations
the number of iterations
-xopt
the x optimum, as a n x 1 column vector, where n is the number of variables.
-fopt
the optimum cost function value
-historyxopt
an array, with nbiter values, containing the history of x during the iterations.
This array is available after optimization if the history storing was enabled with the -storehistory option.
-historyfopt
an array, with nbiter values, containing the history of the function value during the iterations.
This array is available after optimization if the history storing was enabled with the -storehistory option.
-fx0
the function value for the initial guess
-status
a string containing the status of the optimization. See below for details about the optimization status.
-historysimplex
a matrix containing the history of the simplex during the iterations. This matrix has rank nbiter x nbve x n, where nbiter is the number of iterations, nbve is the number of vertices in the simplex and n is the number of variables.
-simplex0
the initial simplex. This is a simplex object, which is suitable for processing with the optimsimplex component.
-simplexopt
the optimum simplex. This is a simplex object, which is suitable for processing with the optimsimplex component.
-restartnb
the number of actual restarts performed.
this = neldermead_search ( this )
Performs the optimization associated with the method associated with the -method option and find the optimum.
this
The current object.
If the -restartflag option is enabled, automatic restarts are performed, based on the -restartdetection option.
this = neldermead_restart ( this )
Restarts the optimization by updating the simplex and performing a new search.
this
The current object.
[ this , result ] = neldermead_function ( this , x )
Call the cost function and return the value.
this
The current object.
x
the point where the function is to be evaluated
index
optional, a flag to pass to the cost function (default = 1). See the section "The cost function" for available values of index.
stop = neldermead_defaultoutput(state, data)
Prints messages at an iteration.
This function provides a default implementation for the output function. There is one line by iteration, presenting the number of iterations, the number of function evaluations, the current function value and the current algorithm step.
See "The output function" section below for a description of the input and output arguments. See in the Examples section below for examples of this function.
The cost function
The option -function allows to configure the cost function. The cost function is used to compute the objective function value f. If the -nbineqconst option is configured to a non-zero value, the cost function must also compute the value of the nonlinear, positive, inequality constraints c. Depending of these options, the cost function can have one of the following headers :
[ f , index ] = costf ( x , index )
[ f , c , index ] = costf ( x , index )
where
x
the current point, as a column vector
index
optional, an integer representing the value to compute
f
the value of the cost function
c
the value of the non-linear, positive, inequality constraints
The index input parameter tells to the cost function what is expected in the output arguments. It has the following meaning
index = 2
compute f
index = 5
compute c
index = 6
compute f and c
In the most simplex case, there is no additionnal cost function argument and no nonlinear constraints. In this case, the cost function is expected to have the following header
[ f , index ]= myfunction ( x , index )
It might happen that the function requires additionnal arguments to be evaluated. In this case, we can use the following feature. The argument fun can also be the list (myfun,a1,a2,...). In this case myfun, the first element in the list, must be a function and must have the header:
[ f , index ] = myfun ( x , index , a1, a2, ... )
[ f , c , index ] = myfun ( x , index , a1, a2, ...)
where the input arguments a1, a2, ... are automatically appended at the end of the calling sequence.
The output function
The option -outputcommand allows to configure a command which is called back at the start of the optimization, at each iteration and at the end of the optimization.
The output function must have the following header
stop = outputcmd(state, data)
where
state
a string representing the current state of the algorithm. Available values are "init", "iter", "done".
data
a data structure containing at least the following entries
x
the current optimum
fval
the current function value
iteration
the current iteration index
funccount
the number of function evaluations
simplex
the current simplex
step
the previous step in the algorithm. The following values are available : "init", "done", "reflection", "expansion", "insidecontraction", "outsidecontraction", "reflectionnext", "shrink".
stop
a 1-by-1 matrix of booleans, set to true to stop the algorithm, set to false to continue the optimization.
It might happen that the output function requires additionnal arguments to be evaluated. In this case, we can use the following feature. The argument outputcmd can also be the list (outf,a1,a2,...). In this case outf, the first element in the list, must be a function and must have the header:
stop = outf ( state, data, a1, a2, ... )
where the input arguments a1, a2, ... are automatically appended at the end of the calling sequence.
If the output function sets the stop variable to true, then the optimization alorithm stops and the status of the optimization is set to "userstop".
Termination
The current component takes into account for several generic termination criterias.
The following termination criterias are enabled by default :
• -maxiter,
• -maxfunevals,
• -tolxmethod.
• -tolsimplexizemethod.
The optimization_terminate function uses a set of rules to compute if the termination occurs, which leads to an optimization status which is equal to one of the following : "continue", "maxiter", "maxfunevals", "tolf", "tolx", "tolsize", "tolsizedeltafv", "kelleystagnation", "tolboxf", "tolvariance". The value of the status may also be a user-defined string, in the case where a user-defined termination function has been set.
The following set of rules is examined in this order.
• By default, the status is "continue" and the terminate flag is %f.
• The number of iterations is examined and compared to the -maxiter option : if the following condition
iterations >= maxiter
is true, then the status is set to "maxiter" and terminate is set to %t.
• The number of function evaluations and compared to the -maxfunevals option is examined : if the following condition
funevals >= maxfunevals
is true, then the status is set to "maxfuneval" and terminate is set to %t.
• The tolerance on function value is examined depending on the value of the -tolfunmethod.
%f
then the criteria is just ignored.
%t
if the following condition
abs(currentfopt) < tolfunrelative * abs(previousfopt) + tolfunabsolute
is true, then the status is set to "tolf" and terminate is set to %t.
The relative termination criteria on the function value works well if the function value at optimum is near zero. In that case, the function value at initial guess fx0 may be used as previousfopt.
This criteria is sensitive to the -tolfunrelative and -tolfunabsolute options.
The absolute termination criteria on the function value works if the user has an accurate idea of the optimum function value.
• The tolerance on x is examined depending on the value of the -tolxmethod.
%f
then the criteria is just ignored.
%t
if the following condition
norm(xopt - previousxopt) < tolxrelative * norm(xopt) + tolxabsolute
is true, then the status is set to "tolx" and terminate is set to %t.
This criteria is sensitive to the -tolxrelative and -tolxabsolute options.
The relative termination criteria on x works well if x at optimum is different from zero. In that case, the condition measures the distance between two iterates.
The absolute termination criteria on x works if the user has an accurate idea of the scale of the optimum x. If the optimum x is near 0, the relative tolerance will not work and the absolute tolerance is more appropriate.
• The tolerance on simplex size is examined depending on the value of the -tolsimplexizemethod option.
%f
then the criteria is just ignored.
%t
if the following condition
ssize < tolsimplexizerelative * simplexsize0 + tolsimplexizeabsolute
is true where simplexsize0 is the size of the simplex at iteration 0, then the status is set to "tolsize" and terminate is set to %t.
The size of the simplex is computed from the "sigmaplus" method of the optimsimplex component. This criteria is sensitive to the -tolsimplexizeabsolute and the -tolsimplexizerelative options.
• The absolute tolerance on simplex size and absolute difference of function value is examined depending on the value of the -tolssizedeltafvmethod option.
%f
then the criteria is just ignored.
%t
if both the following conditions
ssize < tolsimplexizeabsolute
shiftfv < toldeltafv
is true where ssize is the current simplex size and shiftfv is the absolute value of the difference of function value between the highest and lowest vertices, then the status is set to "tolsizedeltafv" and terminate is set to %t.
• The stagnation condition based on Kelley sufficient decrease condition is examined depending on the value of the -kelleystagnationflag option.
%f
then the criteria is just ignored.
%t
if the following condition
newfvmean <= oldfvmean - alpha * sg' * sg
is true where newfvmean (resp. oldfvmean) is the function value average in the current iteration (resp. in the previous iteration), then the status is set to "kelleystagnation" and terminate is set to %t. Here, alpha is a non-dimensional coefficient and sg is the simplex gradient.
• The termination condition suggested by Box is examined depending on the value of the -boxtermination option.
%f
then the criteria is just ignored.
%t
if both the following conditions
shiftfv < boxtolf
boxkount == boxnbmatch
is true where shiftfvis the difference of function value between the best and worst vertices, and boxkount is the number of consecutive iterations where this criteria is met, then the status is set to "tolboxf" and terminate is set to %t. Here, the boxtolf parameter is the value associated with the -boxtolf option and is a user-defined absolute tolerance on the function value. The boxnbmatch parameter is the value associated with the -boxnbmatch option and is the user-defined number of consecutive match.
• The termination condition based on the variance of the function values in the simplex is examined depending on the value of the -tolvarianceflag option.
%f
then the criteria is just ignored.
%t
if the following condition
var < tolrelativevariance * variancesimplex0 + tolabsolutevariance
is true where varis the variance of the function values in the simplex, then the status is set to "tolvariance" and terminate is set to %t. Here, the tolrelativevariance parameter is the value associated with the -tolrelativevariance option and is a user-defined relative tolerance on the variance of the function values. The tolabsolutevariance parameter is the value associated with the -tolabsolutevariance option and is the user-defined absolute tolerance of the variance of the function values.
Kelley's stagnation detection
The stagnation detection criteria suggested by Kelley is based on a sufficient decrease condition, which requires a parameter alpha > 0 to be defined. The -kelleynormalizationflag option allows to configure the method to use to compute this alpha parameter : two methods are available, where each method corresponds to a different paper by Kelley :
constant
In "Detection and Remediation of Stagnation in the Nelder--Mead Algorithm Using a Sufficient Decrease Condition", Kelley uses a constant alpha, with the suggested value 1.e-4, which is is typical choice for line search method.
normalized
in "Iterative Methods for Optimization", Kelley uses a normalized alpha, computed from the following formula
alpha = alpha0 * sigma0 / nsg
where sigma0 is the size of the initial simplex and nsg is the norm of the simplex gradient for the initial guess point.
O'Neill factorial optimality test
In "Algorithm AS47 - Function minimization using a simplex procedure", R. O'Neill presents a fortran 77 implementation of the simplex method. A factorial test is used to check if the computed optimum point is a local minimum. If the -restartdetection option is set to "oneill", that factorial test is used to see if a restart should be performed. O'Neill's factorial test requires 2n function evaluations, where n is the number of variables.
User-defined algorithm
The -mymethod option allows to configure a user-defined simplex-based algorithm. The reason for this option is that many simplex-based variants of Nelder-Mead's algorithm have been developed over the years, with specific goals. While it is not possible to provide them all, it is very convenient to use the current structure without being forced to make many developments.
The value of the -mymethod option is expected to be a Scilab function with the following header
this = myalgorithm ( this )
where this is the current object.
In order to use the user-defined algorithm, the -method option must be set to "mine". In this case, the component performs the optimization exactly as if the user-defined algorithm was provided by the component.
The user interested in that feature may use the internal scripts provided in the distribution as templates and tune his own algorithm from that point. There is of course no warranty that the user-defined algorithm improves on the standard algorithm, so that users use this feature at their own risks.
Example #1: basic use
In the following example, we solve a simple quadratic test case. We begin by defining the cost function, which takes 2 input arguments and returns the objective. The classical starting point [-1.2 1.0] is used. The neldermead_new creates a new neldermead object. Then we use the neldermead_configure method to configure the parameters of the problem. We use all default settings and perform the search for the optimum. The neldermead_display function is used to display the state of the optimization and the neldermead_get is used to retrieve the optimum parameters.
function [f, index]=quadratic(x, index)
f = x(1)^2 + x(2)^2;
endfunction
x0 = [1.0 1.0].';
nm = neldermead_new ();
nm = neldermead_configure(nm,"-numberofvariables",2);
nm = neldermead_configure(nm,"-function",quadratic);
nm = neldermead_configure(nm,"-x0",x0);
nm = neldermead_search(nm);
nm
xopt = neldermead_get(nm,"-xopt");
nm = neldermead_destroy(nm);
Example #2: customized use
In the following example, we solve the Rosenbrock test case. We begin by defining the Rosenbrock function, which takes 2 input arguments and returns the objective. The classical starting point [-1.2 1.0] is used. The neldermead_new creates a new neldermead object. Then we use the neldermead_configure method to configure the parameters of the problem. The initial simplex is computed from the axes and the single length 1.0 (this is the default, but is explicitly written here as an example). The variable simplex algorithm by Nelder and Mead is used, which corresponds to the -method "variable" option. The neldermead_search function performs the search for the minimum. Once the minimum is found, the neldermead_contour allows to compute the data required by the contour function. This is possible since our problem involves only 2 parameters. This function uses the cost function previously configured to compute the required data. The contour plot is directly drawn from the data provided by neldermead_contour. Then we plot the initial guess on the contour plot as a blue dot. The neldermead_get function is used to get the optimum, which is associated with the -xopt option. The optimum is plot on the contour plot as a red dot.
function [f, index]=rosenbrock(x, index)
f = 100*(x(2)-x(1)^2)^2+(1-x(1))^2;
endfunction
x0 = [-1.2 1.0]'
nm = neldermead_new ();
nm = neldermead_configure(nm,"-numberofvariables",2);
nm = neldermead_configure(nm,"-function",rosenbrock);
nm = neldermead_configure(nm,"-x0",x0);
nm = neldermead_configure(nm,"-maxiter",200);
nm = neldermead_configure(nm,"-maxfunevals",300);
nm = neldermead_configure(nm,"-tolfunrelative",10*%eps);
nm = neldermead_configure(nm,"-tolxrelative",10*%eps);
nm = neldermead_configure(nm,"-simplex0method","axes");
nm = neldermead_configure(nm,"-simplex0length",1.0);
nm = neldermead_configure(nm,"-method","variable");
nm = neldermead_configure(nm,"-verbose",1);
nm = neldermead_configure(nm,"-verbosetermination",1);
nm = neldermead_search(nm);
xopt = neldermead_get(nm,"-xopt")
nm = neldermead_destroy(nm);
// Contouring the function.
function f=rosenbrockC(x1, x2)
index = 2
[ f , index ] = rosenbrock ( [x1,x2]' , index )
endfunction
xdata = linspace ( -2 , 2 , 100 );
ydata = linspace ( -1 , 2 , 100 );
h = scf();
contour ( xdata , ydata , rosenbrockC , [2 10 100 500 1000 2000] )
// Plot starting point: x0 : blue dot
plot(x0(1),x0(2),"bo");
// xopt : red star
plot(xopt(1),xopt(2),"r*");
The -verbose option allows to get detailed information about the current optimization process. The following is a sample output for an optimization based on the Nelder and Mead variable-shape simplex algorithm. Only the output corresponding to the iteration #156 is displayed. In order to display specific outputs (or to create specific output files and graphics), the -outputcommand option should be used.
[...]
Iteration #156 (total = 156)
Function Eval #299
Xopt : [1 1]
Fopt : 6.871D-27
DeltaFv : 2.881D-26
Center : [1 1]
Size : 2.549D-13
Optim Simplex Object:
=====================
nbve: 3
n: 2
x: 3-by-2 matrix
fv: 3-by-1 matrix
> Termination ?
> iterations=156 >= maxiter=200
> funevals=299 >= maxfunevals=300
> e(x)=8.798D-15 < 2.220D-15 * 1.4142136 + 0
> Terminate = F, status = continue
> simplex size=2.549D-13 < 0 + 2.220D-16 * 1
> Terminate = F, status = continue
Reflect
xbar=1 1
Function Evaluation #300, index=2, x= [1 1]
xr=[1 1], f(xr)=0.000000
Contract - inside
Function Evaluation #301, index=2, x= [1 1]
xc=1 1, f(xc)=0.000000
> Perform Inside Contraction
Sort
[...]
Example #3: use output function
There are several ways to print intermediate messages or plots during the optimization process. The first method is to set the "-verbose" option to 1, which prints a lot of detailed information. The other method is to use the "-outputcommand" option. We can either set it to the neldermead_defaultoutput or define our own function. In this section, we present the methods based on the "-outputcommand" option.
In the following example, we use the "-outputcommand"option and set it to the neldermead_defaultoutput default output function. This function prints one line by iteration, with the main optimization information.
function [f, index]=quadratic(x, index)
f = x(1)^2 + x(2)^2;
endfunction
x0 = [1.0 1.0].';
nm = neldermead_new ();
nm = neldermead_configure(nm,"-numberofvariables",2);
nm = neldermead_configure(nm,"-function",quadratic);
nm = neldermead_configure(nm,"-x0",x0);
nm = neldermead_configure(nm,"-outputcommand",neldermead_defaultoutput);
nm = neldermead_search(nm);
nm = neldermead_destroy(nm);
The previous script produces the following output.
Initialization
Iter. #0, Feval #5, Fval = 2 -- init
Iter. #1, Feval #5, Fval = 2 -- init
Iter. #2, Feval #6, Fval = 2 -- reflection
Iter. #3, Feval #8, Fval = 0.5 -- expansion
Iter. #4, Feval #9, Fval = 0.5 -- reflection
[...]
Iter. #48, Feval #92, Fval = 8.557D-13 -- reflection
Iter. #49, Feval #94, Fval = 7.893D-13 -- insidecontraction
Iter. #50, Feval #96, Fval = 1.601D-13 -- insidecontraction
Iter. #51, Feval #98, Fval = 1.291D-13 -- insidecontraction
Iter. #52, Feval #100, Fval = 3.139D-14 -- outsidecontraction
=================================
End of Optimization
Iter. #52, Feval #100, Fval = 3.139D-14 -- done
In the following example, we define our own output function "myoutputcmd", which takes the current state as its first argument. The state is a string which can contain "init", "iter" or "done", depending on the status of the optimization. The data input argument is a tlist, which contains the data associated with the current iteration. In this case, we use the fields to print a message in the console.
function [f, index]=rosenbrock(x, index)
f = 100*(x(2)-x(1)^2)^2 + (1-x(1))^2;
endfunction
function stop=myoutputcmd(state, data)
iter = data.iteration
if ( state == "init" ) then
mprintf ( "=================================\n");
mprintf ( "Initialization\n");
elseif ( state == "done" ) then
mprintf ( "=================================\n");
mprintf ( "End of Optimization\n");
end
fc = data.funccount
fval = data.fval
x = data.x
simplex = data.simplex
// Simplex is a data structure, which can be managed
// by the optimsimplex class.
ssize = optimsimplex_size ( simplex )
mprintf ( "Iter. #%3d, Feval #%3d, Fval = %.1e, x = %s, S = %.1e\n", ..
iter, fc, fval, strcat(string(x)," "), ssize);
stop = %f
endfunction
nm = neldermead_new ();
nm = neldermead_configure(nm,"-numberofvariables",2);
nm = neldermead_configure(nm,"-function",rosenbrock);
nm = neldermead_configure(nm,"-x0",[-1.2 1.0]');
nm = neldermead_configure(nm,"-maxiter",200);
nm = neldermead_configure(nm,"-maxfunevals",300);
nm = neldermead_configure(nm,"-tolfunrelative",10*%eps);
nm = neldermead_configure(nm,"-tolxrelative",10*%eps);
nm = neldermead_configure(nm,"-simplex0method","axes");
nm = neldermead_configure(nm,"-simplex0length",1.0);
nm = neldermead_configure(nm,"-method","variable");
nm = neldermead_configure(nm,"-verbose",0);
nm = neldermead_configure(nm,"-verbosetermination",0);
nm = neldermead_configure(nm,"-outputcommand",myoutputcmd);
nm = neldermead_search(nm);
nm = neldermead_destroy(nm);
The previous script produces the following output.
=================================
Initialization
Iter. # 0, Feval # 5, Fval = 2.4e+001, x = -1.2 1, S = 1.0e+000
Iter. # 1, Feval # 5, Fval = 2.4e+001, x = -1.2 1, S = 1.0e+000
Iter. # 2, Feval # 7, Fval = 2.4e+001, x = -1.2 1, S = 1.0e+000
Iter. # 3, Feval # 9, Fval = 2.4e+001, x = -1.2 1, S = 1.0e+000
Iter. # 4, Feval # 11, Fval = 1.0e+001, x = -1.0125 0.78125, S = 6.0e-001
Iter. # 5, Feval # 13, Fval = 4.7e+000, x = -1.028125 1.1328125, S = 3.5e-001
...
Iter. #155, Feval #297, Fval = 2.0e-026, x = 1 1, S = 4.6e-013
Iter. #156, Feval #299, Fval = 6.9e-027, x = 1 1, S = 2.5e-013
Iter. #157, Feval #301, Fval = 6.0e-027, x = 1 1, S = 2.8e-013
=================================
End of Optimization
Iter. #157, Feval #301, Fval = 6.0e-027, x = 1 1, S = 2.8e-013
As another example of use, we could format the message so that it uses LaTeX formatting rules, which may allow the user to directly copy and paste the output into a LaTeX report.
Example #4: Optimization with bounds
The neldermead solver can optimize problems with bounds. To do this, we can use Box's algorithm, which projects the simplex into the bounds during the optimization. In this case, the initial guess must be located within the bounds.
In the following example, we find the minimum of a quadratic function within given bounds. In order to compute the initial simplex, we use randomized bounds, that is, we compute k random vertices uniformly distributed within the bounds. The default value is so that the number of points is twice the number of variables of the problem. In this particular case, we have n=2 variables and k=4 vertices.
function [f, index]=myquad(x, index)
f = x(1)^2 + x(2)^2
endfunction
rand("seed" , 0)
x0 = [1.3 1.8].';
nm = neldermead_new ();
nm = neldermead_configure(nm,"-numberofvariables",2);
nm = neldermead_configure(nm,"-function",myquad);
nm = neldermead_configure(nm,"-x0",x0);
nm = neldermead_configure(nm,"-method","box");
nm = neldermead_configure(nm,"-boundsmin",[1 1]);
nm = neldermead_configure(nm,"-boundsmax",[2 2]);
nm = neldermead_configure(nm,"-simplex0method","randbounds");
nm = neldermead_search(nm);
xopt = neldermead_get(nm,"-xopt") // Should be [1 1]
fopt = neldermead_get(nm,"-fopt") // Should be 2
nm = neldermead_destroy(nm);
Example #5: Optimization with nonlinear constraints
The neldermead solver can optimize problems with nonlinear constraints. In the following example, we solve Rosenbrock's Post Office problem, which has both bounds and linear constraints. In our example, we will manage the linear constraints as general non-linear constraints (i.e. the solver does not make a difference if the constraints are linear or non-linear). This example was first presented in "An automatic method for finding the greatest or least value of a function", Rosenbrock, 1960. This example was first used with the complex method of Box in "Algorithm 454: The complex method for constrained optimization" by Richardson, Kuester, 1971. Richardson and Kuester found the minimum function value F=-3456, with X1 = 24.01, X2 = 12.00, X3 = 12.00 and 72 Iterations were necessary for them to get this result.
In the following function, we define the function fpostoffice, which returns both the objective function f and the constraint value c. The original constraint is the "double" inequality constraint 0<=x(1) + 2 * x(2) + 2 * x(3) <=72. To take this constraint into account, we turn it into two separate, positive, constraints and set c as a 1-by-2 matrix of doubles.
function [f, c, index]=fpostoffice(x, index)
f = []
c = []
if ( index==2 | index==6 ) then
f = -x(1) * x(2) * x(3)
end
if ( index==5 | index==6 ) then
c1 = x(1) + 2 * x(2) + 2 * x(3)
c2 = 72 - c1
c = [c1 c2]
end
endfunction
In the following script, we solve Rosenbrock's Post Office problem. First, we initialize the random number generator, so that the results are always the same. Then, we check that the cost function is correctly defined and that the constraints are satisfied at the initial guess. Then we configure the algorithm so that Box's algorithm is used and setup the bounds of the problem. We configure the parameters of the algorithm as suggested by Box.
rand("seed" , 0);
x0 = [1.0 1.0 1.0].';
// Compute f(x0) : should be close to -1
fx0 = fpostoffice ( x0 , 2 )
// Compute the constraints: cx0 should be [5 67]
[ fx0 , cx0, index ] = fpostoffice ( x0 , 6 )
// Compute f(xopt) : fopt should be -3456
xopt = [24 12 12].';
fopt = fpostoffice ( xopt );
// Setup optimization
nm = neldermead_new ();
nm = neldermead_configure(nm,"-numberofvariables",3);
nm = neldermead_configure(nm,"-function",fpostoffice);
nm = neldermead_configure(nm,"-x0",x0);
nm = neldermead_configure(nm,"-maxiter",300);
nm = neldermead_configure(nm,"-maxfunevals",300);
nm = neldermead_configure(nm,"-method","box");
nm = neldermead_configure(nm,"-boundsmin",[0.0 0.0 0.0]);
nm = neldermead_configure(nm,"-boundsmax",[42.0 42.0 42.0]);
// Configure like Box
nm = neldermead_configure(nm,"-simplex0method","randbounds");
nm = neldermead_configure(nm,"-nbineqconst",2);
nm = neldermead_configure(nm,"-tolxmethod" , %f );
nm = neldermead_configure(nm,"-tolsimplexizemethod",%f);
nm = neldermead_configure(nm,"-boxtermination" , %t );
nm = neldermead_configure(nm,"-boxtolf" , 0.001 );
nm = neldermead_configure(nm,"-boxboundsalpha" , 0.0001 );
//
// Check that the cost function is correctly connected.
[ nm , result ] = neldermead_function ( nm , x0 );
//
// Perform optimization
nm = neldermead_search(nm);
xcomp = neldermead_get(nm,"-xopt")
// Compare with the exact optimum:
xopt
fcomp = neldermead_get(nm,"-fopt")
// Compare with the exact function value:
fopt
nm = neldermead_destroy(nm);
In general, we should not expect too much from this algorithm with nonlinear constraints. Indeed, some cases require thousands of iterations to converge to an optimum, because the nonlinear constraints leave a too small space for the simplex to evolve.
Example #6: Passing extra parameters
In the following example, we solve a simple quadratic test case. Notice that the objective function has two extra parameters a and b. This is why the "-function" option is set as a list, where the first element is the function and the remaining elements are the extra parameters.
function [f, index]=quadratic_ab(x, index, a, b)
f = a * x(1)^2 + b * x(2)^2;
endfunction
x0 = [1.0 1.0].';
nm = neldermead_new ();
nm = neldermead_configure(nm,"-numberofvariables",2);
a = 1;
b = 2;
nm = neldermead_configure(nm,"-function",list(quadratic_ab,a,b));
nm = neldermead_configure(nm,"-x0",x0);
nm = neldermead_search(nm);
xopt = neldermead_get(nm,"-xopt")
nm = neldermead_destroy(nm);
Example #7: Restarting without bounds
In the following example, we reproduce the experiment published by Ken McKinnon in 1998. For this particular function and this particular initial simplex, the Nelder-Mead algorithm converges to a nonstationnary point.
We first define the objective function, the initial simplex and the expected solution of this unconstrained optimization problem.
function [f, index]=mckinnon(x, index)
tau = 3
theta = 6
phi = 400
if ( x(1) <= 0 )
f = theta*phi*abs(x(1))^tau+x(2)*(1+x(2))
else
f = theta*x(1)^tau+x(2)*(1+x(2))
end
endfunction
// The initial simplex
lambda1 = (1.0 + sqrt(33))/8;
lambda2 = (1.0 - sqrt(33))/8;
coords0 = [
1 1
0 0
lambda1 lambda2
];
// The expected solution
xstar = [0;-0.5];
fstar = -0.25;
Then we run the algorithm two times in sequence. At the end of the first optimization process, the algorithm has converged to the point [0,0] which is nonstationnary. This is why we restart the algorithm and get the correct minimum.
nm = neldermead_new ();
nm = neldermead_configure(nm,"-numberofvariables",2);
nm = neldermead_configure(nm,"-function",mckinnon);
nm = neldermead_configure(nm,"-x0",[1.0 1.0]');
nm = neldermead_configure(nm,"-tolsimplexizerelative",1.e-4);
nm = neldermead_configure(nm, "-maxiter",200);
nm = neldermead_configure(nm, "-maxfunevals",500);
nm = neldermead_configure(nm,"-simplex0method","given");
nm = neldermead_configure(nm,"-coords0",coords0);
nm = neldermead_configure(nm,"-method","variable");
// Search #1: fails
nm = neldermead_search(nm);
xopt = neldermead_get(nm,"-xopt")
fopt = neldermead_get(nm,"-fopt")
iterations = neldermead_get(nm,"-iterations")
status = neldermead_get(nm,"-status")
// Search #2: succeeds
nm = neldermead_restart ( nm );
xopt = neldermead_get(nm,"-xopt")
fopt = neldermead_get(nm,"-fopt")
iterations = neldermead_get(nm,"-iterations")
status = neldermead_get(nm,"-status")
nm = neldermead_destroy(nm);
We can also use the automatic stagnation detection method created by Kelley, so that the algorithm automatically restart the algorithm when needed.
nm = neldermead_new ();
nm = neldermead_configure(nm,"-numberofvariables",2);
nm = neldermead_configure(nm,"-function",mckinnon);
nm = neldermead_configure(nm,"-x0",[1.0 1.0]');
nm = neldermead_configure(nm,"-tolsimplexizerelative",1.e-4);
nm = neldermead_configure(nm, "-maxiter",200);
nm = neldermead_configure(nm, "-maxfunevals",500);
nm = neldermead_configure(nm,"-simplex0method","given");
nm = neldermead_configure(nm,"-coords0",coords0);
nm = neldermead_configure(nm,"-method","variable");
nm = neldermead_configure(nm,"-kelleystagnationflag",%t);
nm = neldermead_configure(nm,"-restartflag",%t);
nm = neldermead_configure(nm,"-restartdetection","kelley");
nm = neldermead_search(nm);
xopt = neldermead_get(nm,"-xopt")
fopt = neldermead_get(nm,"-fopt")
iterations = neldermead_get(nm,"-iterations")
restartnb = neldermead_get ( nm , "-restartnb" )
status = neldermead_get(nm,"-status")
nm = neldermead_destroy(nm);
See the demonstrations to get a graphical plot of the intermediate simplices in Mc Kinnon's experiment.
Example #8: Restarting with bounds
In the following experimeant, we solve an optimization problem with bounds. We use Box's algorithm, which is the only algorithm which manages bounds. We use the randomized bounds simplex both for the initial simplex and for the restart simplex.
function [f, index]=myquad(x, index)
f = x(1)^2 + x(2)^2 + x(3)^2
endfunction
x0 = [1.2 1.9,1.5].';
// The solution
xstar = [1;1;1];
fstar = 3;
//
nm = neldermead_new ();
nm = neldermead_configure(nm,"-numberofvariables",3);
nm = neldermead_configure(nm,"-function",myquad);
nm = neldermead_configure(nm,"-x0",x0);
nm = neldermead_configure(nm,"-method","box");
nm = neldermead_configure(nm,"-boundsmin",[1 1 1]);
nm = neldermead_configure(nm,"-boundsmax",[2 2 2]);
nm = neldermead_configure(nm,"-simplex0method","randbounds");
nm = neldermead_search(nm);
nm = neldermead_configure(nm,"-maxiter",200);
nm = neldermead_configure(nm,"-maxfunevals",200);
nm = neldermead_configure(nm,"-restartsimplexmethod","randbounds");
nm = neldermead_restart(nm);
xopt = neldermead_get(nm,"-xopt")
fopt = neldermead_get(nm,"-fopt")
status = neldermead_get(nm,"-status")
nm = neldermead_destroy(nm);
Changes in Scilab 5.4
Many changes have been done in Scilab 5.4, which simplify the use of the neldermead component.
Tagged -costfargument option of optimbase as obsolete: will be maintained for backward compatibility until 5.4.1. The -fun option can now be a list, where the element #1 is a function, and the elements #2 to the end are automatically appended to the calling sequence. To update your code, replace:
nm = neldermead_configure(nm,"-function",myfun);
nm = neldermead_configure(nm,"-costfargument",mystuff);
with
nm = neldermead_configure(nm,"-function",list(myfun,mystuff));
Tagged -outputcommandarg option of optimbase as obsolete: will be maintained for backward compatibility until 5.4.1. The -outputcommand option can now be a list, where the element #1 is a function, and the elements #2 to the end are automatically appended to the calling sequence. To update your code, replace:
nm = neldermead_configure(nm,"-outputcommand",myoutputfun);
nm = neldermead_configure(nm,"-outputcommandarg",mystuff);
with:
nm = neldermead_configure(nm,"-outputcommand",list(myoutputfun,mystuff));
Tagged "outputfun(x,optimValues,state)" calling sequence of fminsearch as obsolete: will be maintained for backward compatibility until 5.4.1. The new calling sequence is "stop=outputfun(x,optimValues,state)" To update your code, replace:
function outfun ( x , optimValues , state )
[...]
endfunction
with:
function stop = outfun ( x , optimValues , state )
[...]
stop = %f
endfunction
Tagged "myoutputfun(state,data)" calling sequence of neldermead as obsolete: will be maintained for backward compatibility until 5.4.1. The new calling sequence is "stop=myoutputfun(state,data)" To update your code, replace:
function myoutputfun ( state , data )
[...]
endfunction
with:
function stop = myoutputfun ( state , data )
[...]
stop = %f
endfunction
Tagged "-myterminateflag" and "-myterminate" options as obsolete: will be maintained for backward compatibility until 5.4.1. To update your code, replace:
function [ this , terminate , status ] = myoldterminate ( this , simplex )
ssize = optimsimplex_size ( simplex , "sigmaplus" );
if ( ssize < 1.e-2 ) then
terminate = %t;
status = "mysize";
else
terminate = %f
end
endfunction
with :
function stop = myoutputcmd ( state , data )
simplex = data.simplex
ssize = optimsimplex_size ( simplex , "sigmaplus" );
if ( ssize < 1.e-2 ) then
stop = %t;
else
stop = %f
end
endfunction
and replace the configuration:
nm = neldermead_configure(nm,"-myterminateflag",%t);
nm = neldermead_configure(nm,"-myterminate",myoldterminate);
with:
nm = neldermead_configure(nm,"-outputcommand",myoutputcmd);
Tagged "-tolvarianceflag", "-tolabsolutevariance", and "-tolrelativevariance" options as obsolete: will be maintained for backward compatibility until 5.4.1. To update your code, create an output function:
function stop = myoutputcmd ( state, data, tolrelativevariance, tolabsolutevariance, variancesimplex0 )
simplex = data.simplex
stop = %f
if ( state == "iter") then
var = optimsimplex_fvvariance ( simplex )
if ( var < tolrelativevariance * variancesimplex0 + tolabsolutevariance ) then
stop = %t;
end
end
endfunction
Create the initial simplex and compute the variance of the function values:
x0 = [1.1 1.1]';
simplex0 = optimsimplex_new ( "axes" , x0.' );
coords0 = optimsimplex_getallx(simplex0);
variancesimplex0 = optimsimplex_fvvariance ( simplex0 );
Finally, replace the configuration:
nm = neldermead_configure(nm,"-tolvarianceflag",%t);
nm = neldermead_configure(nm,"-tolabsolutevariance",1.e-4);
nm = neldermead_configure(nm,"-tolrelativevariance",1.e-4);
with:
tolabsolutevariance = 1.e-4;
tolrelativevariance = 1.e-4;
stopfun = list(myoutputcmd, tolrelativevariance, tolabsolutevariance, variancesimplex0);
nm = neldermead_configure(nm,"-outputcommand",stopfun);
Spendley et al. implementation notes
The original paper may be implemented with several variations, which might lead to different results. This section defines what algorithmic choices have been used.
The paper states the following rules.
• "Rule 1. Ascertain the lowest reading y, of yi ... yk+1 Complete a new simplex Sp by excluding the point Vp corresponding to y, and replacing it by V* defined as above."
• "Rule 2. If a result has occurred in (k + 1) successive simplexes, and is not then eliminated by application of Rule 1, do not move in the direction indicated by Rule 1, or at all, but discard the result and replace it by a new observation at the same point."
• "Rule 3. If y is the lowest reading in So , and if the next observation made, y* , is the lowest reading in the new simplex S , do not apply Rule 1 and return to So from Sp . Move out of S, by rejecting the second lowest reading (which is also the second lowest reading in So)."
We implement the following "rules" of the Spendley et al. method.
• Rule 1 is strictly applied, but the reflection is done by reflection the high point, since we minimize a function instead of maximizing it, like Spendley.
• Rule 2 is NOT implemented, as we expect that the function evaluation is not subject to errors.
• Rule 3 is applied, ie reflection with respect to next to high point.
The original paper does not mention any shrink step. When the original algorithm cannot improve the function value with reflection steps, the basic algorithm stops. In order to make the current implementation of practical value, a shrink step is included, with shrinkage factor sigma. This perfectly fits into to the spirit of the original paper. Notice that the shrink step make the rule #3 (reflection with respect to next-to-worst vertex) unnecessary. Indeed, the minimum required steps are the reflection and shrinkage. Never the less, the rule #3 has been kept in order to make the algorithm as close as it can be to the original.
Nelder-Mead implementation notes
The purpose of this section is to analyse the current implementation of Nelder-Mead's algorithm.
The algorithm that we use is described in "Iterative Methods for Optimization" by C. T. Kelley.
The original paper uses a "greedy" expansion, in which the expansion point is accepted whatever its function value. The current implementation, as most implementations, uses the expansion point only if it improves over the reflection point, that is,
• if fe<fr, then the expansion point is accepted,
• if not, the reflection point is accepted.
The termination criteria suggested by Nelder and Mead is based on an absolute tolerance on the standard deviation of the function values in the simplex. We provide this original termination criteria with the -tolvarianceflag option, which is disabled by default.
Box's complex algorithm implementation notes
In this section, we analyse the current implementation of Box's complex method.
The initial simplex can be computed as in Box's paper, but this may not be safe. In his paper, Box suggest that if a vertex of the initial simplex does not satisfy the non linear constraints, then it should be "moved halfway toward the centroid of those points already selected". This behaviour is available when the -scalingsimplex0 option is set to "tocenter". It may happen, as suggested by Guin, that the centroid is not feasible. This may happen if the constraints are not convex. In this case, the initial simplex cannot be computed. This is why we provide the "tox0" option, which allows to compute the initial simplex by scaling toward the initial guess, which is always feasible.
In Box's paper, the scaling into the non linear constraints is performed "toward" the centroid, that is, by using a scaling factor equal to 0.5. This default scaling factor might be sub-optimal in certain situations. This is why we provide the -boxineqscaling option, which allows to configure the scaling factor.
In Box's paper, whether we are concerned with the initial simplex or with the simplex at a given iteration, the scaling for the non linear constraints is performed without end. This is because Box's hypothesis is that "ultimately, a satisfactory point will be found". As suggested by Guin, if the process fails, the algorithm goes into an infinite loop. In order to avoid this, we perform the scaling until a minimum scaling value is reached, as defined by the -guinalphamin option.
We have taken into account for the comments by Guin, but it should be emphasized that the current implementation is still as close as possible to Box's algorithm and is not Guin's algorithm. More precisely, during the iterations, the scaling for the non linear constraints is still performed toward the centroid, be it feasible or not.
Bibliography
"Sequential Application of Simplex Designs in Optimisation and Evolutionary Operation", Spendley, W. and Hext, G. R. and Himsworth, F. R., American Statistical Association and American Society for Quality, 1962
"A Simplex Method for Function Minimization", Nelder, J. A. and Mead, R., The Computer Journal, 1965
"A New Method of Constrained Optimization and a Comparison With Other Methods", M. J. Box, The Computer Journal 1965 8(1):42-52, 1965 by British Computer Society
"Discussion and correspondence: modification of the complex method of constrained optimization", J. A. Guin, The Computer Journal, 1968
"Detection and Remediation of Stagnation in the Nelder--Mead Algorithm Using a Sufficient Decrease Condition", Kelley C. T., SIAM J. on Optimization, 1999
"Iterative Methods for Optimization", C. T. Kelley, SIAM Frontiers in Applied Mathematics, 1999
"Algorithm AS47 - Function minimization using a simplex procedure", O'Neill, R., Applied Statistics, 1971
"Nelder Mead's User Manual", Consortium Scilab - Digiteo, Michael Baudin, 2010
Ken McKinnon, Convergence of the Nelder-Mead simplex method to a nonstationary point, SIAM Journal on Optimization, Volume 9, Number 1, 1998, pages 148-158.
See Also
• optimbase — Provides an abstract class for a general optimization component.
• optimsimplex — Manage a simplex with arbitrary number of points.
• nmplot — Manage a simplex with arbitrary number of points.
Scilab Enterprises
Copyright (c) 2011-2017 (Scilab Enterprises)
Copyright (c) 1989-2012 (INRIA)
Copyright (c) 1989-2007 (ENPC)
with contributors
Last updated:
Tue Apr 02 17:36:22 CEST 2013 | __label__pos | 0.916069 |
Главная
Алгебра 7 класс А.Г.Мордкович, Л.А.Александрова, Т.Н.Мишустина, Е.Е.Тульчинская
ГДЗ учебник по алгебре 7 класс А.Г.Мордкович, Л.А.Александрова, Т.Н.Мишустина, Е.Е.Тульчинская
авторы: , , , .
издательство: "Мнемозина" 2013 г
Раздел:
Номер №11.8.
Убедитесь, что пара чисел (12;15) является решением системы уравнений:
а)
{ x + y = 27 , 2 x 4 y = 36 ;
б)
{ 2 x y = 9 , 4 y = 5 x .
Решение а
{ 12 + 15 = 27 2 12 4 15 = 24 60 = 36
{ 27 = 27 36 = 36
Решение б
{ 2 12 15 = 24 15 = 9 4 15 = 5 12
{ 9 = 9 60 = 60 | __label__pos | 0.963785 |
Mike Mike - 6 months ago 62
Python Question
Django REST: create CRUD operations for OneToOne Field
I'm trying to create basic CRUD operations for OneToOne field.
The user is not required to set the profile when signing in. How do I create/update/delete profile when needed (assuming the user is already in the DB)?
My models are the default User models from Django REST and:
class UserProfile(models.Model):
user = models.OneToOneField(User)
location = models.CharField(max_length=50,blank=True)
title = models.CharField(max_length=80,blank=True)
#picture = models.ImageField(upload_to='user_imgs', blank=True)
website = models.URLField(blank=True)
My Viewsets are:
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
filter_fields = ['id', 'username', 'email', 'first_name', 'last_name']
class UserProfileViewSet(viewsets.ModelViewSet):
queryset = UserProfile.objects.all()
serializer_class = UserProfileSerializer
filter_fields = ['user_id', 'location', 'title', 'website']
And serializes:
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
email = serializers.EmailField()
fields = ('id','username', 'email', 'first_name', 'last_name')
class UserProfileSerializer(serializers.HyperlinkedModelSerializer):
user_id = serializers.CharField(source='user.id')
class Meta:
model = UserProfile
fields = ('user_id', 'location','title','website')
Answer
I belive you want to restrict the profile creation to the current logged in user. You can filter the queryset of profiles to the current user, this way only that user's profile will be accessible by the logged in user.
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
filter_fields = ['id', 'username', 'email', 'first_name', 'last_name']
class UserProfileViewSet(viewsets.ModelViewSet):
queryset = UserProfile.objects.all()
serializer_class = UserProfileSerializer
filter_fields = ['user_id', 'location', 'title', 'website']
def get_queryset(self):
return super(UserProfileViewSet, self).get_queryset().filter(
user=self.request.user)
def perform_create(self, serializer):
serializer.save(user=user)
You make the user field read only and is being saved in the above method perform_create and assigned always to the current user.
class UserProfileSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = UserProfile
fields = ('user', 'location','title','website')
read_only_fields = ('user',) | __label__pos | 0.925043 |
Jump to content
• Log In with Google Sign In
• Create Account
XNA - Making A Sprite Fire A Projectile
Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.
• You cannot reply to this topic
7 replies to this topic
#1 mistervirtue Members - Reputation: 593
Like
0Likes
Like
Posted 03 June 2013 - 08:34 AM
Hello Fellow GameDev'ers,
I am working on my personal project and I have hit a serious road block. I am trying to making the player fire projectiles, but I can't really make it work. I have searched online for tutorials, but I can't seem to find any that make use of SpriteManager like I am doing. I am trying to make it as Object-Oriented as possible but I don't really know what to do.
I currently have a base Sprite.cs, a UserControlled.cs, and now a ProjectileSprite.cs, and a game component called SpriteManager.cs. I figure should model my ProjectileSprite.cs similarly to my other sprites and then add it to the SpriteManager.cs. But I also don't know how to make it interact with the UserControlled.cs so it will shoot when you want it to.
Does GameDev.net have any resources on this kind of problem? If anyone can give me any hints/points/shoves in the right direction that would be awesome.
Sponsor:
#2 adt7 Members - Reputation: 590
Like
0Likes
Like
Posted 03 June 2013 - 09:05 AM
Without seeing any code it's hard to give any advice on how to fit it into your existing setup.
Coudl you post snippets of the relavent parts of your Sprite, SpriteManager, UserController and ProjectileSprite classes? Or at least the parts that seem to be causing you difficulty?
#3 Aurioch Crossbones+ - Reputation: 1304
Like
2Likes
Like
Posted 03 June 2013 - 11:50 AM
Hello
I believe I can help you with basics (since tags mention C# and XNA), because my current project involves lots of projectiles.
Basically, what you need is to make a projectile as a separate object:
public class Projectile()
{
Texture2D projectileSprite;
Rectangle projectileHitBox; // assuming you're going with hit box collision, otherwise use commented block below
/*
Vector2 projectilePosition;
Vector2 projectileOrigin;
float projectileScale;
float projectileRotation;
*/
// rest of the code
}
As you can see, that class will hold all relevant information for your projectile.
For creation of new projectile, you'll need a constructor which will allow you to create new projectile fast:
public Projectile(Texture2D spriteTexture, Vector2 projectilePosition) // change parameters as you see fit
{
projectileSprite = spriteTexture;
// insert additional code here, such as creation of hitbox
}
In your main code now you can manipulate projectiles:
Projectile Bullet; // declaration of single bullet
List<Projectile> Bullets; // if you plan to track multiple bullets at the same time
public override void Update(GameTime gameTime)
{
// code snippet
// Creation of new bullet
Bullet = new Projectile(bulletTexture, currentPlayerPosition);
// If you need to add to the list
Bullets.Add(new Projectile(bulletTexture, currentPlayerPosition)); // or in this case just add Bullet
// code snippet; bullet update code
}
Drawing is done the same way; first in Projectile class write separate Draw method:
public void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Draw(bulletTexture, bulletHitBox, Color.White); // this one is simplest; use other Draw overrides if you need to
}
Then in your main Draw function just call the above method:
public override void Draw (GameTime gameTime)
{
// code snippet; spriteBatch.Begin is somewhere here if spriteBatch exists
Projectile.Draw(spriteBatch)
//code snippet; spriteBatch.End is somewhere here
}
How to destroy projectile?
// if single projectile
Bullet = null;
// if using lists
Bullets.Remove(Bullet) // removal by specific object
Bullets.RemoveAt(bulletIndex) // removal by index of relevant projectile
I have no idea how you modelled your classes (and also, those names are fairly suspicious, probably just me/my style of coding) so if you plan to use any of this code, you'll need it to adapt to your own setup. I could show you my code if you're interested (be it PM or forum post) but my setup is completely different than yours.
#4 mistervirtue Members - Reputation: 593
Like
1Likes
Like
Posted 03 June 2013 - 12:24 PM
Here is my code for the most part
--------- SpriteManager ---------
public class SpriteManager : Microsoft.Xna.Framework.DrawableGameComponent
{
SpriteBatch spriteBatch;
UserControlledSprite player;
Texture2D testingRec;
Texture2D projectileSprite;
List<Sprite> spriteList = new List<Sprite>();
public SpriteManager(Game game)
: base(game)
{
}
protected override void LoadContent()
{
spriteBatch = new SpriteBatch(Game.GraphicsDevice);
player = new UserControlledSprite(Game.Content.Load<Texture2D>(@"images/SmallHero"),
Vector2.Zero, new Point(85, 97), 1, new Point(0, 0), new Point(1, 1), new Vector2(3, 3));
testingRec = Game.Content.Load<Texture2D>(@"images/testRec");
projectileSprite = Game.Content.Load<Texture2D>(@"images/fireblast");
base.LoadContent();
}
public override void Initialize()
{
base.Initialize();
}
public override void Update(GameTime gameTime)
{
player.Update(gameTime, Game.Window.ClientBounds);
base.Update(gameTime);
}
public override void Draw(GameTime gameTime)
{
spriteBatch.Begin();
player.Draw(gameTime, spriteBatch);
spriteBatch.Draw(testingRec,player.collisionRect ,Color.White);
spriteBatch.End();
base.Draw(gameTime);
}
}
----- My base Sprite Class -------
namespace ProjectGaslightKnights
{
abstract class Sprite
{
public Texture2D textureImage;
protected Vector2 position;
protected Point frameSize;
int collisionOffset;
public Point currentFrame;
public Point sheetSize;
int timeSinceLastFrame = 0;
protected Vector2 speed;
int milisecondsPerFrame;
const int defaultMillisecondsPerFrame = 16;
SpriteEffects myEffect;
Texture2D testingRecTexture;
public Sprite(Texture2D textureImage, Vector2 position, Point frameSize,
int collisionOffset, Point currentFrame, Point sheetSize, Vector2 speed)
: this(textureImage, position, frameSize, collisionOffset, currentFrame, sheetSize, speed, defaultMillisecondsPerFrame)
{
}
public Sprite(Texture2D textureImage, Vector2 position, Point frameSize, int collisionOffset, Point currentFrame,
Point sheetSize, Vector2 speed, int millisecondsPerFrame)
{
this.textureImage = textureImage;
this.position = position;
this.frameSize = frameSize;
this.collisionOffset = collisionOffset;
this.currentFrame = currentFrame;
this.sheetSize = sheetSize;
this.speed = speed;
this.milisecondsPerFrame = milisecondsPerFrame;
}
public virtual void Update(GameTime gameTime, Rectangle ClientBounds)
{
timeSinceLastFrame += gameTime.ElapsedGameTime.Milliseconds;
if (timeSinceLastFrame > milisecondsPerFrame)
{
timeSinceLastFrame = 0;
++currentFrame.X;
if (currentFrame.X >= sheetSize.X)
{
currentFrame.X = 0;
++currentFrame.Y;
if (currentFrame.Y >= sheetSize.Y)
{
currentFrame.Y = 0;
}
}
}
}
public virtual void Draw(GameTime gameTime, SpriteBatch spriteBatch)
{
spriteBatch.Draw(textureImage, position,
new Rectangle(currentFrame.X * frameSize.X, currentFrame.Y * frameSize.Y,
frameSize.X, frameSize.Y), Color.White, 0, Vector2.Zero, 1f, myEffect, 0);
spriteBatch.Draw(testingRecTexture, collisionRect, Color.White);
}
public abstract Vector2 direction
{
get;
}
public Rectangle collisionRect
{
get
{
return new Rectangle(
(int)position.X + collisionOffset,
(int)position.Y + collisionOffset,
frameSize.X - (collisionOffset * 2),
frameSize.Y - (collisionOffset * 2));
}
}
internal void Update(GameTime gameTime)
{
throw new NotImplementedException();
}
}
}
-------And my user Class -------
class UserControlledSprite : Sprite
{
SpriteEffects myEffect;
public UserControlledSprite(Texture2D textureImage, Vector2 position,
Point frameSize, int collisionOffset, Point currentFrame, Point sheetSize,
Vector2 speed)
: base(textureImage, position, frameSize, collisionOffset,
currentFrame, sheetSize, speed)
{
}
public UserControlledSprite(Texture2D textureImage, Vector2 position,
Point frameSize, int collisionOffset, Point currentFrame, Point sheetSize,
Vector2 speed, int millisecondsPerFrame)
: base(textureImage, position, frameSize, collisionOffset,
currentFrame, sheetSize, speed, millisecondsPerFrame)
{
}
public override Vector2 direction
{
get
{
Vector2 inputDirection = Vector2.Zero;
if (Keyboard.GetState().IsKeyDown(Keys.Left))
{
inputDirection.X -= 1;
}
if (Keyboard.GetState().IsKeyDown(Keys.Right))
{
inputDirection.X += 1;
}
if (Keyboard.GetState().IsKeyDown(Keys.Down))
{
inputDirection.Y += 1;
}
if (Keyboard.GetState().IsKeyDown(Keys.Up))
{
inputDirection.Y -= 1;
}
return inputDirection * speed;
}
}
public override void Update(GameTime gameTime, Rectangle ClientBounds)
{
//Move the spite according to the direction property
position += direction;
//If the player is facing left, flip it horizontally
if (direction.X < 0)
{
this.myEffect = SpriteEffects.FlipHorizontally;
}
//If The player is facing right, no effect
if (direction.X > 0)
{
this.myEffect = SpriteEffects.None;
}
//If the player leaves bounds off the screen put it back in play
if (position.X < 0)
{
position.X = 0;
}
if (position.Y < 0)
{
position.Y = 0;
}
if (position.X > ClientBounds.Width - (frameSize.X))
{
position.X = ClientBounds.Width - (frameSize.X );
}
if (position.Y > ClientBounds.Height - (frameSize.Y))
{
position.Y = ClientBounds.Height - (frameSize.Y);
}
base.Update(gameTime, ClientBounds);
}
public override void Draw(GameTime gameTime, SpriteBatch spriteBatch)
{
spriteBatch.Draw(textureImage, position,
new Rectangle(currentFrame.X * frameSize.X, currentFrame.Y * frameSize.Y,
frameSize.X, frameSize.Y), Color.White, 0, Vector2.Zero, 1, myEffect, 0);
}
}
I feel like I am cheating though. This isn't a school project or anything but all my professers tell me that Programmers need to learn to solve their own problems. But I think problem solving should involve other people, see as most of us want to work with other programmers. Anyway I am trying to build it such that my UserClass will be able to fire projectiles. So i Think the way I am going to model my ProjecticleSprite with a it's own draw(), and Update() and not inherit from the base class sprite. Thanks for your help everyone.
#5 SelethD Members - Reputation: 455
Like
1Likes
Like
Posted 03 June 2013 - 09:55 PM
I didnt look through all the code posted, so not sure if this will help. However, this is how I would do it.
Since you have a sprite manager, you need to be able to 'create' sprites, manage them while they are alive, and eventually destroy them after a certain time, or condition.
For the projectile, you need to 'create' it at the location of your player, and let your sprites hold a heading and velocity.
so when player fires, create projectile sprite, set its heading to whatever heading your player has, set its velocity to something fast, then let the sprite manager, continue to update its movement, check collisions, and draw the projecting, until it gets off screen or hits something, etc... then let the sprite manager destory the object.
#6 Gorge Express Members - Reputation: 179
Like
0Likes
Like
Posted 04 June 2013 - 04:53 AM
For something simple like shooting a projectile, i'd just give the class dealing with input access to the sprite manager so that it can create the projectile sprite. The sprite manager should be able to do the rest, storing the sprite in some structure and iterating over that structure calling each sprite's update method each frame.
Also you should probably store the player's direction in a variable. If you can only face right or left, you can use a boolean.
#7 LordRhys Members - Reputation: 378
Like
0Likes
Like
Posted 04 June 2013 - 07:17 AM
For a perfecty example of what you want check out XNA-40-Game-Development-by-Example-Beginners-Guide, the second example project uses a ShotManager class which manageds the bullets being shot by the Player and the author uses it in the next project to manage shots by the player and by enemies.
#8 DishSoap Members - Reputation: 620
Like
0Likes
Like
Posted 04 June 2013 - 03:20 PM
For projectiles you are going to want to have an acceleration, velocity and position vector. I would argue for all physical objects in your world you will want these three vectors and integrate them according to some law such as Euler or RK4.
When I create my games I tend to have some base class, "MoveableObject" or PhysicalObject, that simply holds these three vectors and is responsible for integrating them.
class MoveableObject
{
public:
integrate(dt)
{
position += velocity * dt;
velocity += velocity + acceleration * dt;
};
Vector2 position;
Vector2 velocity;
Vector2 acceleration;
};
If you choose to add gravity to your projectile all you'd have to do is set the acceleration vector accordingly.
This way every moving object in your world has some base object you can access these variables by. A projectile would have this as a base class and would simply be integrated just like any other moving object in your would.
Here is a great article on it! http://gafferongames.com/game-physics/integration-basics/
Edited by DishSoap, 04 June 2013 - 03:21 PM.
Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.
PARTNERS | __label__pos | 0.904006 |
How do you edit text messages?
The first part of editing text is to move the cursor to the right spot. The cursor is that blinking, vertical line where text appears. Then you can type, edit, or paste or simply marvel that you were able to move the cursor hither and thither.
Can you edit sent messages?
According to the filing, the option to edit a message would appear whenever someone long-presses a text in iMessage. … Currently, holding down a message opens up options to copy a message or react to it using an emote.
How do I customize my messaging app on Android?
Open the Messages app —> Touch the More button at the top-right of the screen —> Select the Settings option —> Choose the Backgrounds option —> Select your preferred background. If your phone is updated to Android 9 and later, the customization feature in the messaging app is probably no longer available.
Is there an app that can edit text messages?
The solution to this problem has arrived with reTXT, an app that allows users to delete and update sent text messages. But reTXT Labs co-founder and CEO Kevin Wooten said reTXT is more than just a tool for deleting drunk text messages.
How do you edit text on a PDF?
How to edit PDF files:
1. Open a file in Acrobat DC.
2. Click on the “Edit PDF” tool in the right pane.
3. Use Acrobat editing tools: Add new text, edit text, or update fonts using selections from the Format list. …
4. Save your edited PDF: Name your file and click the “Save” button.
Can I delete a text sent by mistake?
There is no way to unsend a text message or iMessage unless you cancel the message before it was sent. … In this fast-paced world, when we’re firing off emails, posting status updates, and sending messages a mile a minute, we’ve all pressed “send” or “delete” sooner than we’ve intended at one time or another.
Can you delete part of a text?
Deleting part of a text message conversation
Tap and hold on the message you want to delete. You’ll see a few things pop up, including “More…” at the bottom. … Tap that to delete the message. Tap a confirming “Delete Message” button and you’re all set.
How do I delete sent text messages on Android?
1 Delete a Message
1. Open Messages.
2. Locate the conversation that has the message you want to delete then tap on it.
3. Touch and hold the message you want to delete.
4. Tap the trash can to delete the message.
5. Tap Delete on the confirmation prompt.
How do you change your text color?
Change the font color
1. Select the text that you want to change.
2. On the Home tab, in the Font group, choose the arrow next to Font Color, and then select a color. You can also use the formatting options on the Mini toolbar to quickly format text. The Mini toolbar appears automatically when you select text.
Can I change the color of my text bubbles?
Switching the background color of the bubble behind your text isn’t possible with default apps, but free third-party apps such as Chomp SMS, GoSMS Pro and HandCent allow you to do this. In fact, you can even apply different bubble colors for incoming and outgoing messages or make them match the rest of your theme.
Which is better Samsung messages or Google messages?
Senior Member. I personally prefer Samsung messaging app, mainly because of the its UI. However, the main advantage of Google messages is the availability of RCS by default, no matter where you live or which carrier you have. You can have RCS with Samsung messages but only if your carrier supports it.
How do I stop auto delete old messages?
How to Stop Auto Deleting Text Messages on an iPhone
1. Open Settings.
2. Choose Messages.
3. Select Keep Messages.
4. Tap Forever.
Does Google messages delete old messages?
You can move old or unwanted conversations into your archives, mark all messages as read, or delete them from Messages. Touch and hold each conversation that you want to archive or delete. . Archived conversations disappear from the Home screen, but you can still read them.
Source link | __label__pos | 0.999964 |
TECHNOLOGYtech
What Are .PHP Files
what-are-php-files
Introduction
PHP, also known as Hypertext Preprocessor, is a widely-used scripting language that is primarily used for web development. It is often embedded within HTML code and executed on the server side to generate dynamic web pages. One of the key components of PHP is the .PHP file, which contains PHP code that can be interpreted and executed by the server.
PHP files play a crucial role in powering dynamic websites and web applications. They allow developers to add dynamic functionality, perform database operations, handle form submissions, and much more. In this article, we will explore the definition, structure, purpose, and common applications of .PHP files. We will also discuss the benefits and challenges associated with using PHP files in web development.
Whether you are a seasoned web developer or just starting your journey in programming, understanding .PHP files and their role in web development is essential. So, let’s dive into the world of .PHP files and discover their significance in creating dynamic and interactive web experiences.
Definition of .PHP Files
.PHP files are text files that contain PHP code. They are saved with a .php file extension and are executed on the server side. PHP files are used in web development to create dynamic web pages and applications. The PHP code within these files is processed by a PHP interpreter, which generates HTML output to be sent to the client’s web browser.
PHP, which stands for Hypertext Preprocessor, is a widely-used server-side scripting language. It is embedded within HTML code, allowing developers to mix PHP code with regular HTML markup. This combination of PHP and HTML makes it easy to create dynamic content, interact with databases, handle form submissions, perform calculations, and much more.
PHP files typically start with the closing tag. Everything within these tags is interpreted as PHP code. However, it is worth noting that the closing tag is optional in PHP files and is often omitted for better compatibility and to prevent accidental whitespace from being included in the output.
.PHP files can also contain HTML code, CSS stylesheets, JavaScript code, and other web technologies. This allows developers to create rich and interactive web pages that respond to user input and display real-time data.
In order to run PHP files, a web server with PHP installed is required. The server processes the PHP code and generates the corresponding HTML output, which is then sent to the user’s browser. The browser receives the HTML and renders it, resulting in a dynamic and interactive web page.
With their ability to combine PHP code with HTML and other web technologies, .PHP files are an essential component of modern web development. They provide a powerful tool for creating dynamic web experiences and enabling server-side processing.
Structure and Syntax of .PHP Files
The structure and syntax of .PHP files follow a specific pattern that allows developers to write PHP code and integrate it seamlessly with HTML markup. Understanding the structure and syntax of .PHP files is essential for writing clean and functional PHP code.
Here are some key elements of the structure and syntax of .PHP files:
• Opening and Closing PHP Tags: A .PHP file begins with the opening tag. These tags enclose the PHP code, allowing it to be executed and processed by the server.
• Outputting HTML: Since PHP is often used in combination with HTML, developers need a way to output HTML content. This can be done by simply including the HTML code within the PHP tags. Alternatively, the echo statement can be used to output HTML or other content to the browser. For example, echo “Hello, World!”; will display “Hello, World!” in the browser.
• Comments: Comments are used to add notes and explanations within the code. In PHP, comments can be written in two ways. Single-line comments start with //, while multi-line comments are enclosed between /* and */. Comments are not processed by the server and are only meant for developers to understand the code.
• Variables: Variables in PHP are denoted by the $ symbol followed by the variable name. PHP is a dynamically-typed language, meaning that variables can hold different types of data without explicit declaration. For example, $name = “John”; assigns the value “John” to the $name variable.
• Control Structures: .PHP files support various control structures, such as if statements, for loops, while loops, switch statements, and more. These control structures allow developers to make decisions and control the flow of the program based on certain conditions.
• Functions: PHP functions are blocks of code that perform a specific task. They can be defined using the function keyword, followed by the function name and a set of parentheses. Functions can accept parameters and return values, making them reusable and modular.
By following the proper structure and syntax of .PHP files, developers can create organized, readable, and maintainable PHP code. This facilitates collaboration, debugging, and future modifications, ensuring the smooth functioning of web applications and websites.
Purpose and Use of .PHP Files
.PHP files serve a crucial purpose in web development and are used extensively to create dynamic and interactive websites and applications. They provide developers with a wide range of features and functionalities that enhance the user experience and enable server-side processing.
Here are some key purposes and uses of .PHP files:
• Server-Side Processing: One of the primary purposes of .PHP files is to enable server-side processing. Unlike client-side scripting languages like JavaScript, which run in the user’s browser, PHP code is executed on the server. This allows developers to perform complex operations, interact with databases, handle form submissions, authenticate users, and more, without exposing sensitive information or logic to users.
• Dynamic Content Generation: .PHP files are instrumental in generating dynamic content for web pages. By embedding PHP code within HTML markup, developers can create web pages that display real-time data, such as user-specific information, database records, and dynamic calculations. This ability to generate dynamic content enhances personalization and interactivity, making websites more engaging and relevant to users.
• Database Integration: .PHP files seamlessly integrate with databases, allowing developers to connect to database servers and perform operations like querying, inserting, updating, and deleting data. This makes it possible to build robust web applications that can store, retrieve, and manipulate information from databases. Popular databases like MySQL, PostgreSQL, and SQLite are commonly used in conjunction with .PHP files.
• Form Processing: .PHP files are widely used for processing form submissions on websites. When a user submits a form, the data is sent to the server for processing. .PHP files can validate, sanitize, and store this data securely. They can also perform additional actions based on the submitted data, such as sending emails, redirecting the user to a different page, or updating database records.
• Session Management: .PHP files enable the management of user sessions, which are used to maintain state and track user interactions on a website. Sessions allow websites to remember user preferences, maintain login information, and provide personalized experiences. .PHP files facilitate session handling, making it easy to start, manage, and destroy sessions as needed.
Overall, .PHP files play a critical role in web development by providing a powerful toolset to create dynamic, interactive, and data-driven websites and applications. They enable server-side processing, integration with databases, handling of form submissions, and much more, making them a fundamental component of modern web development.
Common Applications and Examples of .PHP Files
.PHP files have a wide range of applications and are used extensively in various web development scenarios. They provide developers with the flexibility and functionality needed to create dynamic and interactive websites and applications. Here are some common applications and examples of .PHP files:
• Content Management Systems (CMS): Many popular CMS platforms, such as WordPress and Drupal, rely heavily on .PHP files to power their core functionality. .PHP files handle tasks such as rendering templates, processing user input, managing database interactions, and generating dynamic content. They enable the creation of websites with rich features, including customizable themes, user accounts, and content publishing.
• E-commerce Websites: .PHP files are frequently utilized in building e-commerce websites. They handle various aspects of online shopping, including product listings, shopping carts, payment processing, and order management. PHP frameworks like Magento and WooCommerce utilize .PHP files extensively to create robust and scalable e-commerce platforms.
• User Authentication and Authorization: .PHP files play a crucial role in managing user authentication and authorization. They handle tasks such as user registration, login, logout, and password reset. By integrating with databases and utilizing encryption techniques, .PHP files enable secure and seamless user authentication on websites.
• API Development: .PHP files are used to develop APIs (Application Programming Interfaces) that allow different software systems to communicate with each other. APIs built with PHP can retrieve and send data in various formats, such as JSON or XML. Whether it’s creating a custom API or utilizing popular frameworks such as Laravel or Slim, .PHP files serve as the backbone for building robust and scalable API endpoints.
• Web Forms and Data Processing: .PHP files are commonly used to process web forms and handle user input. They validate form data, sanitize it to prevent security breaches, and store it in databases. .PHP files can also send email notifications, perform calculations, and generate dynamic responses based on form submissions. They make it possible to build interactive and user-friendly web forms.
• Dynamic Content and Database Integration: .PHP files facilitate the integration of web pages with databases. They retrieve data from databases, format it, and present it dynamically on web pages. This allows for the creation of websites with dynamic content, such as news feeds, product listings, and user-generated content. .PHP files enable developers to fetch, filter, and display data from databases in real-time.
These are just a few examples of the many applications of .PHP files in web development. Given their versatility and power, .PHP files continue to be a popular choice for creating dynamic and interactive websites and applications across various industries and use cases.
Benefits of Using .PHP Files
.PHP files offer several benefits that make them an attractive choice for web development projects. Understanding these advantages can help developers make informed decisions when choosing the appropriate technologies for their projects. Here are some key benefits of using .PHP files:
• Easy Integration with HTML: .PHP files can be seamlessly integrated with HTML code, allowing developers to create dynamic web pages by embedding PHP code within HTML markup. This integration simplifies the process of adding dynamic functionality to websites while maintaining a clean and organized structure.
• Large Community and Support: PHP has a large and active community of developers worldwide. This means that there is a wealth of online resources, tutorials, forums, and communities available for learning and problem-solving. The community’s support and contributions ensure that PHP remains a reliable and well-maintained programming language.
• Flexibility and Scalability: .PHP files offer flexibility, allowing developers to build small-scale websites or large-scale applications. With the help of frameworks like Laravel, CodeIgniter, or Symfony, developers can leverage pre-built libraries and tools to enhance productivity and build scalable solutions that can handle increased traffic and data processing.
• Speed and Performance: PHP is known for its fast execution speed, making .PHP files an efficient choice for web development. Additionally, PHP has built-in mechanisms for caching and optimizing code, further improving performance. This allows websites and applications built with .PHP files to deliver content quickly and handle high volumes of user traffic.
• Platform Independence: .PHP files can run on various operating systems, including Windows, macOS, Linux, and more. This platform independence allows developers to work on different environments and deploy their applications on the server of their choice.
• Database Compatibility: PHP has extensive support for various database systems, including MySQL, PostgreSQL, SQLite, Oracle, and more. .PHP files can interact with databases seamlessly, allowing developers to store and retrieve data, perform complex queries, and manipulate database records.
The benefits of using .PHP files make them a versatile and reliable choice for building dynamic and interactive websites and applications. With their ease of integration, scalability, community support, speed, and compatibility with databases, .PHP files continue to be widely used and trusted by developers across the globe.
Challenges and Limitations of .PHP Files
While .PHP files offer many advantages for web development, it is important to be aware of the challenges and limitations associated with using them. Understanding these factors can help developers make informed decisions and overcome potential hurdles. Here are some key challenges and limitations of .PHP files:
• Security Vulnerabilities: Like any other programming language, PHP is not immune to security vulnerabilities. Inadequate input validation, improper handling of user data, and insecure code practices can lead to vulnerabilities such as SQL injection, cross-site scripting (XSS), and session hijacking. It is crucial for developers to follow best practices and ensure that their .PHP files are secure against potential attacks.
• Performance Scalability: Although PHP is known for its speed and performance, it may face challenges in scaling when dealing with high traffic or resource-intensive applications. Without proper optimization techniques, .PHP files can experience performance bottlenecks, leading to slower response times. Caching mechanisms, database optimization, and code profiling can help mitigate these challenges.
• Code Maintenance: As projects grow larger and more complex, .PHP files can become difficult to maintain and organize. Without proper structuring and adherence to coding standards, .PHP files can become hard to navigate, leading to decreased readability and increased development time. Consistent code documentation and adopting PHP frameworks can help with code organization and maintainability.
• Compatibility Issues: As PHP continues to evolve, backward compatibility can become a challenge. Older versions of PHP and legacy codebases may face compatibility issues with newer PHP versions and libraries. It is important for developers to keep up with PHP updates, test their .PHP files for compatibility, and plan for necessary updates and migrations.
• Learning Curve: While PHP is relatively easy to learn, mastering its advanced features and best practices requires time and practice. Novice developers may face a learning curve when working with .PHP files, especially when dealing with more complex tasks such as database integration, security measures, and performance optimization. Continuous learning and keeping up with PHP community resources can help overcome this limitation.
• Limited Support for Asynchronous Operations: One limitation of .PHP files is the lack of native support for asynchronous programming. Asynchronous operations, such as handling concurrent requests, are not easily achievable using traditional .PHP files. However, there are workarounds available, such as using PHP extensions or implementing asynchronous patterns with libraries like ReactPHP or Swoole.
Despite these challenges and limitations, .PHP files remain a popular choice for web development due to their extensive community support, ease of use, and wide range of applications. By understanding and addressing these challenges, developers can leverage the strengths of .PHP files while mitigating potential drawbacks.
Conclusion
.PHP files play a crucial role in web development, providing developers with the ability to create dynamic, interactive, and data-driven websites and applications. With their seamless integration with HTML, flexibility, and extensive community support, .PHP files have become a preferred choice for building robust and scalable web solutions.
Throughout this article, we explored the definition, structure, syntax, and purpose of .PHP files. We also discussed common applications and examples, as well as the benefits and challenges associated with using .PHP files in web development.
.PHP files offer numerous benefits, including easy integration with HTML, a large and active community, flexibility, scalability, and compatibility with databases. They enable server-side processing, dynamic content generation, database integration, form processing, and much more. The speed, performance, and platform independence of .PHP files make them a popular choice among developers.
However, it is important to be aware of the challenges and limitations of .PHP files, such as security vulnerabilities, scalability issues, code maintenance, compatibility, learning curve, and limited support for asynchronous operations. By addressing these challenges and staying up to date with best practices, developers can leverage the power of .PHP files while mitigating potential drawbacks.
Overall, .PHP files remain a reliable and versatile tool for web development. Whether you are building CMS platforms, e-commerce websites, APIs, or handling web forms, .PHP files provide the necessary features and functionalities to bring your web projects to life. With continuous learning and proper utilization of .PHP files, developers can create engaging, dynamic, and user-friendly web experiences.
Leave a Reply
Your email address will not be published. Required fields are marked * | __label__pos | 0.926407 |
Edit Article
wikiHow to Do Long Multiplication
Two Methods:Doing Standard Long MultiplicationTaking a ShortcutCommunity Q&A
Long multiplication can seem very intimidating, especially if you're multiplying two numbers that are pretty large. If you take it step by step, though, you'll be able to do long multiplication in no time. Get ready to ace those math quizzes by going to Step 1 below to get started.
1
Doing Standard Long Multiplication
1. 1
Write the larger number above the smaller number. Let's say you're going to multiply 756 and 32. Write 756 above 32, making sure that the ones and tens columns of both numbers line up, so that the 6 from 756 is above the 2 in 32 and the 5 in 756 is above the 3 in 32, and so on. This will make it easier for you to visualize the long multiplication process.
• You will essentially begin by multiplying the 2 in 32 by each of the numbers in 756, and then multiplying the 3 in 32 by each of the numbers in 756. But let's not get ahead of ourselves.
2. 2
Multiply the number in the ones place of the bottom number by the number in the ones place of the top number. Take the 2 from 32 and multiply it by the 6 in 756. The product of 6 times 2 is 12. Write the units digit, 2, under the units, and carry the 1 over the 5. Basically, you write down whatever number is in the ones digit, and if there is a number in the tens digit, you will have to carry it over the number to the left of the top number you just multiplied. You'll have a 2 directly below the 6 and the 2.
3. 3
Multiply the number in the ones place of the bottom number by the number in the tens place of the top number. Now, multiply 2 times 5 to equal 10. Add the 1 you carried over above the 5 to 10 to equal 11, and then write a 1 next to the 2 in the bottom row. You'll have to carry the extra 1 in the tens place over the 7.
4. 4
Multiply the number in the ones place of the bottom number by the number in the hundreds place of the top number. Now, just multiply 2 by 7 to equal 14. Then add the 1 that you carried over to 14 to equal 15. Don't carry the tens over this time, as there are no more numbers to multiply on this row. Just write the 15 on the bottom line.
5. 5
Draw a 0 in the units column below the first product. Now, you'll be multiplying the number in the tens place of 32, 3, by each digit in 756, so draw a zero below the 2 in 1512 before you begin so you are already starting in the tens place. If you were going to keep going and multiply a number in the hundreds place by the top number, then you'd need to draw two zeroes, and so on.
6. 6
Multiply the number in the tens place of the bottom number by the number in ones place of the top number. Now, multiply 3 by 6 to equal 18. Again, put the 8 on the line, and carry the 1 over above the 5.
7. 7
Multiply the number in the tens place of the bottom number by the number in tens place of the top number. Multiply 3 times 5. This makes 15, but you must add on the carried 1, so it equals 16. Write the 6 on the line, and carry the 1 over above the 7.
8. 8
Multiply the number in the tens place of the bottom number by the number in hundreds place of the top number. Multiply 3 times 7 to equal 21. Add the 1 you carried to equal 22. You don't need to carry the 2 in 22, as there are no more numbers to multiply on this line, so you can just write it down next to the 6.
9. 9
Add the ones digits of both products. Now, you'll have to simply add up 1512 and 22680. First, add 2 plus 0 to equal 2. Write the result in the ones column.
10. 10
Add the tens digits of both products. Now, add up 1 and 8 to equal 9. Write 9 to the left of the 2.
11. 11
Add the hundreds digits of both products. The sum of 5 and 6 is 11. Write down the 1 in the units place and carry the 1 in the tens place over 1 at the very left of the first product.
12. 12
Add the thousands digits of both numbers. Add up 1 plus 2 to equal 3 and then add on the 1 you carried over to equal 4. Write it down.
13. 13
Add the ten thousands digits of both numbers. The first number has nothing in the ten thousands place, and the second has 2 there. So, add 0 plus 2 to equal 2 and write it down. This gives you 24,192, your final answer.
14. 14
Check your answer with a calculator. If you want to double check your work, type in the problem into a calculator to see if you've done it correctly. You should get 756 times 32 equals 24,192. You're all done!
2
Taking a Shortcut
1. 1
Write down the problem. Let's say you're multiplying 325 times 12. Write it down. One number should be right next to the other, not below it.
2. 2
Split up the smaller number into tens and ones. Keep 325 and split up 12 into 10 and 2. The 1 is in the tens digit, so you should add a 0 afterward to keep its place, and since the 2 is in the ones place, you can just write down 2.
3. 3
Multiply the larger number by the number in the tens digit. Now, multiply 325 times 10. All you have to do is add a zero to the end to equal 3250.
4. 4
Multiply the larger number by the number in the ones digit. Now, just multiply 325 by 2. You can eyeball it and see that the answer is 650, since 300 times 2 is 600 and 25 times 2 is 50. Add up 600 and 50 to equal 650.
5. 5
Add up the two products. Now, just add up 3250 and 650. You can do this using the good old fashioned addition method. Just write 3250 over 650 and do all the work. You'll get 3,900. Really, this is similar to doing the standard long multiplication, but splitting up a number into ones and tens allows you to do a bit more of the math in your head and to avoid multiplying and carrying too much. Either method will yield the same results, and it all depends on which one works more quickly for you.
Community Q&A
Search
Add New Question
• What can I do if I am confused by all of the zeroes on the end of the numbers?
Set aside first the zeros (but remember how many there are). Multiply the non-zero numbers, then add all the zeros that you set aside beforehand.
• How do I do the checking in a multiplication process?
wikiHow Contributor
Use a calculator to check your answer, or if not possible, use long division to divide your answer by one of the numbers and see if you get the other number.
• How can I solve money problems without using a calculator?
wikiHow Contributor
Money problems aren't too complicated, just do the problem like a normal one and put the decimal in front of the last two numbers.
Unanswered Questions
Show more unanswered questions
Ask a Question
200 characters left
Submit
If this question (or a similar one) is answered twice in this section, please click here to let us know.
Tips
• Practice on short, easy numbers first.
• Make sure you get your numbers in the right columns!
• Don't forget to carry your tens along, or else it'll all mess up.
• Always put a 0 at the end on the tens. on the hundreds put TWO 0's and so on. Also, check your work thoroughly and use a calculator afterwards - but no cheating.
• For numbers of more than two digits, follow these steps: first multiply the top number by the units, then add a zero and multiply by the tens, then add two zeros and multiply by the hundreds, then add three zeros and multiply by the thousands, and so on. Add up all the numbers at the end.
Sources and Citations
Article Info
Categories: Multiplication and Division
In other languages:
Français: faire une longue multiplication, Español: hacer multiplicaciones largas, Deutsch: Lange Multiplikationen ausführen, Português: Fazer Multiplicações Grandes, Italiano: Eseguire la Moltiplicazione Lunga, 中文: 计算长乘法, Русский: умножить в столбик, Nederlands: Grote getallen vermenigvuldigen, Bahasa Indonesia: Menyelesaikan Perkalian Panjang, العربية: أداء القسمة المطولة, हिन्दी: बड़ी संख्याओं का गुणा करें, Tiếng Việt: Thực hiện Phép nhân dài, 日本語: 桁数の多い数字のかけ算をする, ไทย: คูณเลข, 한국어: 큰 숫자를 곱하는 방법, Čeština: Jak násobit velká čísla pod sebou
Thanks to all authors for creating a page that has been read 1,241,159 times.
Did this article help you?
| __label__pos | 0.94924 |
How are those of you handling an API project + Frontend Project?
I have a fully built app in PHP built on Wappler, but with the new integration of Capacitor, I want to change this over to a NodeJS API project and a Capacitor front-end project. My question is how are people doing this (including on Cordova) when it comes to not being able to have more than one Wappler instance open?
The idea of constantly switching between projects when I need to edit something minor is a huge pain, especially on the scale of the project I am converting where I’d constantly need to go back and forth between the front end and backend.
How are you guys working around this?
Currently there is no way of working around this but there is some discussion of making improvements for this Project structure in the future. | __label__pos | 0.989972 |
Foxit PDF SDK(Linux版)
Foxit PDF SDK(Linux版)是为Linux企业或云应用程序设计的PDF解决方案,提供强大的渲染、数字签名、表单填写、文本处理等功能。Foxit PDF SDK(Linux版)提供了实用的PDF演示代码,帮助开发人员通过我们的核心API实现强大的功能。Foxit PDF SDK(Linux版)功能丰富,对于任何想要在嵌入式Linux操作系统和云应用程序中创建一个完全可定制的PDF阅读器或后台应用的Linux开发人员来说都是非常理想的解决方案。
使用Foxit PDF SDK(Linux版)开发PDF软件
将Foxit PDF SDK(Linux版)嵌入到Linux应用程序中十分简单。只需打开任意一款Linux集成开发环境,复制您所需要的库就可以用C++或Java进行开发。同时SDK提供的文档和示例项目会指导您使用PDF SDK(Linux版)进行项目创建及开发。我们的开发库适用于32位操作系统和64位操作系统。
PDF SDK for Linux Support
功能
查看PDF
我们的核心API针对桌面和移动平台进行了优化,可以提供高保真度PDF文档渲染体验。
数字签名
无需打印文件,用户可以在其电子设备上签署文件,加速业务处理,并给用户带来舒适的体验。
PDF表单
支持使用电子设备填写数字表单,使之更高效、快捷。
权限管理
Foxit PDF SDK可以通过加密/解密服务或集成自定义数字权限管理(DRM)或信息权限管理(IRM)系统生成受保护的PDF文件。福昕的PDF SDK集成了微软权限管理服务(RMS)。
PDF注释
Foxit PDF SDK提供丰富的注释和标记功能,支持创建、编辑、导入和导出注释等。
全文搜索
采用SQLite数据库,支持对多种语言类型的PDF文档进行全文检索,提供快速、便捷的搜索体验。
FOXIT PDF SDK 7.5简介
Foxit PDF SDK在2020年最后一次发布中添加了许多新功能和改进。其中,桌面端SDK,版式识别的支持扩展到了Linux 版和 Mac版(此前Windows版已支持),自由文本注释支持富文本格式,HTML转PDF功能可直接从内存中加载Cookie,以及其他功能改进。
在移动端,通过Xamarin插件您只需两行代码即可添加多语言支持(Android版),签名功能提供了是否自动保存的选项,并且,我们还新增了用于搜索、形状、水印以及图像转PDF等功能的示例代码,帮助您的应用程序快速上市。
在Web版PDF库中,我们添加了与注释和表单相关的功能(如用于控制类型和外观的PDFControl类和Widget类),并支持对screen类型注释的设置和表单域的自动计算。最后,我们还为表单数据的导入和导出添加了CSV和TXT文件格式的支持。
FOXIT PDF SDK 6.4
PDF SDK 6.4为用户带来了全新的功能,包括备受欢迎的OCR附加组件、PDF比较工具、PDF合规性附加组件等等。除了新增这些功能外,我们还增强改进了注释功能(单个注释的旋转、扁平化)和XFA表单的签名功能,针对Cordova插件提供新的API,并更新了示例代码和开发人员指南,同时修复了若干问题。
高级技术
XFA表单
XFA表单是基于XML的表单。能够安全获取、呈现、移动、处理、输出、更新和打印与静态和动态XFA表单相关的信息。使用XFA表单能简化您的数据共享、数据和获取。
权限管理
将应用程序和文件连接到微软的权限管理服务平台,保护PDF文档的安全。Foxit PDF SDK支持集成自定义IRM和DRM解决方案。
密文处理
出于合法或安全的考虑,通过编程实现搜索和审查文档的敏感信息,确保您的客户和员工的信息安全。通过福昕强大的技术加密文档,使得文档符合通用数据保护条例(GDPR)。
优点
完整的Linux支持
得益于其强大、灵活和高效的功能,福昕可以专门为已针对硬件产品进行优化的嵌入式Linux操作系统和可扩展云应用提供强大的解决方案。
占用内存小
PDF SDK(Linux版)即使处理复杂任务也只占用很小的运行内存。此外,我们的内存溢出管理功能确保您的应用程序能够从内存异常中恢复。
功能丰富
我们的产品功能在移动端、服务器端、桌面端保持一致,使得跨平台开发更加简单顺畅。我们会不断更新功能集,欢迎关注我们的产品页面。
福昕核心技术支持
Foxit PDF SDK的核心技术已经存在多年,并且受到许多知名公司的信任。福昕强大的引擎使文档在不同平台上都可以快速查看并且保持一致。
系统要求
• Linux 32位和Linux 64位
• 测试环境:Centos 6.4 32位和Centos 6.5 64位
• PDF SDK(Linux版)包括32位和64位的版本库
在Linux中加载PDF文件或添加图像
public static void main(String[] args) throws PDFException, IOException {
createResultFolder(output_path);
int error_code = Library.initialize(sn, key);
if (error_code != e_ErrSuccess) {
System.out.println(String.format("Library Initialize Error: %d\n", error_code));
return;
}
String input_file = input_path + "AboutFoxit.pdf";
String output_file1 = output_path + "bookmark_add.pdf";
String output_file2 = output_path + "bookmark_change.pdf";
String bookmark_info_file = output_path + "bookmark_info.txt";
try {
PDFDoc doc = new PDFDoc(input_file);
error_code = doc.load(null);
if (error_code != e_ErrSuccess) {
System.out.println(String.format("The Doc [%s] Error: %d\n", input_file, error_code));
return;
}
// Show original bookmark information.
showBookmarksInfo(doc, bookmark_info_file);
//Get bookmark root node or Create new bookmark root node.
Bookmark root = doc.getRootBookmark();
if (root.isEmpty()) {
root = doc.createRootBookmark();
}
for (int i = 0; i < doc.getPageCount(); i += 2) {
Destination dest = Destination.createFitPage(doc, i);
String ws_title = String.format("A bookmark to a page (index: %d)", i);
Bookmark child = root.insert(ws_title,
e_PosLastChild);
child.setDestination(dest);
child.setColor(i * 0xF68C21);
}
doc.saveAs(output_file1, e_SaveFlagNoOriginal);
// Get first bookmark and change properties.
Bookmark first_bookmark = root.getFirstChild();
first_bookmark.setStyle(e_StyleItalic);
first_bookmark.setColor(0xFF0000);
first_bookmark.setTitle("Change bookmark title, style, and color");
// Remove next sibling bookmark
if (!first_bookmark.getNextSibling().isEmpty()) {
doc.removeBookmark(first_bookmark.getNextSibling());
}
bookmark_info_file = output_path + "bookmark_info1.txt";
showBookmarksInfo(doc, bookmark_info_file);
doc.saveAs(output_file2, e_SaveFlagNoOriginal);
System.out.println("Bookmark demo.");
} catch (Exception e) {
e.printStackTrace();
}
Library.release();
return;
}
public class pdf2image {
private static String key = "";
private static String sn = "";
private static String output_path = "../output_files/pdf2image/";
private static String input_path = "../input_files/";
private static String input_file = input_path + "AboutFoxit.pdf";
private static String[] support_image_extends = {".bmp", ".jpg", ".jpeg", ".png", ".jpx", ".jp2"};
private static String[] support_multi_image = {".tif", ".tiff"};
public static void main(String[] args) throws PDFException {
createResultFolder(output_path);
int error_code = Library.initialize(sn, key);
if (error_code != e_ErrSuccess) {
System.out.println("Library Initialize Error: " + error_code);
return;
}
PDFDoc doc = new PDFDoc(input_file);
error_code = doc.load(null);
if (error_code != e_ErrSuccess) {
System.out.println("The Doc " + input_file + " Error: " + error_code);
return;
}
Image image = new Image();
int nPageCount = doc.getPageCount();
for (int i = 0; i < nPageCount; i++) {
PDFPage page = doc.getPage(i);
// Parse page.
page.startParse(e_ParsePageNormal, null, false);
int width = (int) page.getWidth();
int height = (int) page.getHeight();
Matrix2D matrix = page.getDisplayMatrix(0, 0, width, height, page.getRotation());
// Prepare a bitmap for rendering.
Bitmap bitmap = new Bitmap(width, height, e_DIBArgb, null, 0);
bitmap.fillRect(0xFFFFFFFF, null);
// Render page
Renderer render = new Renderer(bitmap, false);
render.startRender(page, matrix, null);
image.addFrame(bitmap);
for (int j = 0; j < support_image_extends.length; j++) {
String extend = support_image_extends[j];
Save2Image(bitmap, i, extend);
}
}
for (int j = 0; j < support_multi_image.length; j++) {
String extend = support_multi_image[j];
Save2Image(image, extend);
}
Library.release();
}
private static void createResultFolder(String output_path) {
File myPath = new File(output_path);
if (!myPath.exists()) {
myPath.mkdir();
}
}
private static void Save2Image(Bitmap bitmap, int nPageIndex, String sExt) throws PDFException {
Image image = new Image();
image.addFrame(bitmap);
String s = "AboutFoxit_" + nPageIndex;
s = output_path + s + sExt;
image.saveAs(s);
System.out.println("Save page " + nPageIndex + " into a picture of " + sExt + " format.");
}
private static void Save2Image(Image image, String sExt) throws PDFException {
String s = "AboutFoxit";
s = output_path + s + sExt;
image.saveAs(s);
System.out.println("Save pdf file into a picture of " + sExt + " format.");
}
} | __label__pos | 0.93421 |
Streamlining Data Integration and Real-Time Analytics with Databricks and Delta Live Tables for Ecommerce Company
BHASKAR SHERKAR
3 min readAug 1
--
Streamlining Data Integration and Real-Time Analytics with Databricks and Delta Live Tables for Ecommerce Company
Our client operates multiple stores across Norway and Sweden. To leverage their data effectively, we onboard data from their WooCommerce Application and Marketing Data into our distributed environment, Databricks. This data is then loaded into Delta Lake Tables. Utilizing the Delta Live Tables (DLT) concept in Databricks, we consume this data in real-time, which is then used for reporting and training Machine Learning models by Data Scientists
What is Delta Live Tables (DLT)?
Delta Live Tables (DLT) is a feature of Databricks, a unified data analytics platform. DLT is designed to simplify the process of building, deploying, and maintaining data pipelines at scale.
Here are some key benefits of Delta Live Tables:
- Reliability: DLT ensures data reliability by maintaining data in a transactional and consistent manner. It uses ACID (Atomicity, Consistency, Isolation, Durability) transactions to ensure data integrity.
- Scalability: DLT can handle large volumes of data and scale as your data grows. This makes it ideal for big data processing tasks.
- Simplified Data Engineering: DLT provides a structured framework for developing data pipelines. This simplifies the process of data engineering and reduces the time and effort required to build and maintain data pipelines.
- Real-time Data Processing: DLT supports both batch and real-time data processing. This allows for real-time analytics and decision-making.
- Version Control: DLT maintains a version history of your data. This allows you to access previous versions of your data for auditing or debugging purposes.
- Schema Enforcement and Evolution: DLT enforces schema on write operations, ensuring data consistency. It also supports schema evolution, allowing you to add, delete, or change columns in your data over time.
- Integration with Machine Learning and AI: DLT integrates seamlessly with Databricks’ machine learning and AI capabilities, making it easier to build and deploy predictive models.
- Unified Batch and Streaming: DLT unifies batch and streaming data processing, simplifying the architecture and reducing the maintenance overhead of having separate systems for batch and streaming data.
By leveraging these benefits, organizations can improve their data operations, gain insights faster, and make more informed decisions.
Learn More about Delta Live Tables here
How we implemented DLT to achieve Realtime data sync?
Extraction Jobs
We handle various datasets such as Orders, OrderItems, Products, Variations, Refunds, and RefundItems for each store. These datasets are made available in Delta Tables through Extraction Jobs. These jobs, primarily scheduled to run every 5 to 10 minutes, load data based on the last modified date
We have three main extraction jobs:
- Orders
- OrderItems
- Other datasets (Products, Variations, Refunds, RefundItems, Customers)
Bronze — DLT Job:
This job retrieves data from the Delta Lake Table and loads it into a newly created Bronze DLT in real-time. We select the necessary fields from the delta table and add a few additional fields for in-house purposes.
Silver — DLT Job:
This job retrieves data from the Bronze DLT and loads it into the Silver layer, performing Change Data Capture (CDC) on top of the data and also does the job of deduplication
Gold — DLT Job:
This job retrieves the latest data from the Silver DLT and loads it into the Gold layer.
Marketing Job: We integrate data from various marketing sources such as Facebook, Snapchat, and Instagram via Hevo. This integration setup within Hevo is designed to load data into Databricks. Once loaded into Delta tables, we consume this data and load it directly into the Gold Layer.
--
-- | __label__pos | 0.630183 |
Saturday Jul 22
Joomla Info
What is Joomla?
Joomla is an award-winning content management system (CMS), which enables you to build Web sites and powerful online applications. Many aspects, including its ease-of-use and extensibility, have made Joomla the most popular Web site software available. Best of all, Joomla is an open source solution that is freely available to everyone.
What's a content management system (CMS)?
A content management system is software that keeps track of every piece of content on your Web site, much like your local public library keeps track of books and stores them. Content can be simple text, photos, music, video, documents, or just about anything you can think of. A major advantage of using a CMS is that it requires almost no technical skill or knowledge to manage. Since the CMS manages all your content, you don't have to.
What are some real world examples of what Joomla! can do?
Joomla is used all over the world to power Web sites of all shapes and sizes. For example:
* Corporate Web sites or portals
* Corporate intranets and extranets
* Online magazines, newspapers, and publications
* E-commerce and online reservations
* Government applications
* Small business Web sites
* Non-profit and organizational Web sites
* Community-based portals
* School and church Web sites
* Personal or family homepages
| __label__pos | 0.77853 |
Law of Sines Not Working Right for You?
Have you run into this? You get the “wrong answer” when you use a calculator and the Law of Sines to find an obtuse angle.
The problem isn’t that the Law of Sines doesn’t work (thanks @GMichaelGuy), but that you have to be cautious when dealing with the arcsine with an obtuse angle. Here’re the details:
I’ve concocted a triangle that’s pretty simple but has an obtuse angle. That’s the key here. The law of sines always “works” when you have all acute angles. It’s only when the angle in question is an obtuse angle that we have a problem. (and, as @GMichaelGuy pointed out, it always works, it just makes us do a little more work.)
Notice I used the arcsine. Turns out, the arcsine isn’t a function. Which means when you “undo” all the bits in the law of sines, technically you’ll get an infinite number of answers. We, as humans, know that there are
So it all boils down to the calculator not being able to determine if you want the obtuse angle when you solve for x using the law of sines!
What do you think? Any other questions on trig? Ask them in the comments.
And a big thanks to @mrlove314 for this question!
This post may contain affiliate links. When you use them, you support us so we can continue to provide free content!
9 Responses to Law of Sines Not Working Right for You?
• Thanks for the kind words, Beni!
I can probably explain it in one video because I’ve done it like your teacher has for 20+ years. After you do it poorly enough times, you start wondering why students aren’t understanding. So you start watching students and asking questions – both of the students and yourself.
After a while, you see what craziness is going on in the problem and are able to figure out not just how to do it, but how to explain it.
I know your question was rhetorical, but I think this is a real reason.
Thanks for stopping in!
1. What if the problem you are doing doesn’t say that the triangle is necessarily obtuse? How are you supposed to know whether you have one?
Leave a reply
This site uses Akismet to reduce spam. Learn how your comment data is processed. | __label__pos | 0.797788 |
clase 18 wwplus internacional
Updated: July 15, 2024
Jorge Tarulli
Summary
The video introduces session 18 of the Word Plus basic course, focusing on the use of templates in web panels and the significance of XPZ files for property and neighborhood information display. It explains importing an XPZ file 'training properties' to display transactions and setting controls for neighborhood selection in properties. The tutorial showcases applying Word with Plus to transactions, configuring controls for neighborhood selection, and categorizing data by city neighborhoods. It also covers importing new tables, running web panels to display neighborhood and property data, as well as customizing templates for different project information displays. Lastly, it delves into creating a web panel based on an SDT for dynamic data visualization and utilizing transactions and templates for data display and recording across multiple tables, hinting at upcoming topics like wizard exercises and diploma creation in the course.
Introducción al curso básico de Word Plus
Se introduce la sesión número 18 del curso básico de Word Plus y se explica el uso de plantillas en web panels y la importancia de un archivo XPZ para mostrar información de propiedades y vecindarios.
Importar un XPZ para propiedades y vecindarios
Se detalla el proceso de importación de un archivo XPZ llamado 'training properties' para mostrar transacciones y configurar un control para seleccionar barrios en propiedades.
Aplicar Word with Plus a las transacciones
Se muestra cómo aplicar Word with Plus a transacciones y configurar controles para seleccionar barrios y categorizar la información por vecindarios de ciudades.
Importar tablas nuevas y ejecutar web panels
Se explica el proceso de importar tablas nuevas y ejecutar un web panel para mostrar datos de vecindarios y propiedades, así como la carga de datos y la ejecución de objetos.
Aplicar plantillas a web panels
Se detalla el proceso de aplicar plantillas a web panels para mostrar información de proyectos utilizando una plantilla específica y mostrar visualizaciones distintas con plantillas personalizadas.
Crear web panels con SDT y variables
Se describe la creación de un web panel basado en un SDT para visualizar información de proyectos utilizando variables y datos cargados dinámicamente.
Utilizar business components y plantillas
Se explica cómo utilizar transacciones como business components y plantillas en web panels para mostrar y grabar datos en múltiples tablas. Se aborda la personalización de títulos de plantillas y la generación de facturas.
Conclusión y próximos pasos
Se mencionan los próximos temas a abordar, como el ejercicio del wizard, la creación de diplomas y la planificación para las siguientes sesiones del curso.
FAQ
Q: What is the importance of using templates in web panels?
A: Templates in web panels are important for organizing and displaying information in a structured and visually appealing manner.
Q: How is an XPZ file used to display information about properties and neighborhoods?
A: An XPZ file is imported to show transactions, set up controls for selecting neighborhoods in properties, and categorize information by city neighborhoods.
Q: Explain the process of importing a new table and running a web panel to display neighborhood and property data.
A: To display neighborhood and property data, a new table is imported, and a web panel is executed to show the data, including loading and executing objects.
Q: How can templates be applied to web panels to show project information?
A: Templates can be applied to web panels to display project information using specific templates for different visualizations.
Q: Describe the creation of a web panel based on an SDT to view project information dynamically.
A: A web panel can be created based on an SDT to show project information using dynamically loaded variables and data.
Q: In what ways can transactions and templates in web panels be utilized to handle data across multiple tables?
A: Transactions and templates in web panels can be used as business components to display and save data in multiple tables.
Q: What customization options are available for template titles, and what task involves generating invoices?
A: Template titles can be customized, and the generation of invoices is part of customizing and generating documents.
Q: What future topics are mentioned for the course, and what tasks are planned for upcoming sessions?
A: Future topics include completing a wizard exercise, creating diplomas, and planning for the content of future course sessions.
Logo
Get your own AI Agent Today
Thousands of businesses worldwide are using Chaindesk Generative AI platform.
Don't get left behind - start building your own custom AI chatbot now! | __label__pos | 0.813743 |
Oh well, at least it's
different
Everything here is my opinion. I do not speak for your employer.
April 2007
May 2007
2007-04-30 »
BarCampMontreal2: the (missing) women of tech conferences
On Saturday I went to BarCampMontreal2 where there was a presentation called "Where are all the girls?" by Martine Pagé.
I don't really have an opinion on the whole "women in technology" issue and its direct relative, the "women in tech conferences" issue, because I don't really have enough information to form a considered opinion. But with that in mind, what information do we have, anyway?
We can start with some statistics. Martine quoted an article with statistics on male vs. female speakers at tech/web/design conferences. The number of female speakers varies, but is typically about 15-20% and is as high as 30% (at only one place). Now, what do those numbers mean? A couple of things. First, while the overall human population is about 51% women, the population of women speakers at tech conferences is... less. So tech conferences are biased, right?
Well, not exactly. Everyone knows that the tech industry is itself biased. According to a Stanford University study, 32% of the IT workforce in 2004 was female. This implies that speakers at tech conferences underrepresent, but not hugely, the population of women in technology overall: 20% speaking out of 32% overall.
But one statistic that's not given is how many women attend tech conferences. That number would help break apart two stats: the number of women who are interested at all, vs. the fraction of those who are willing to make presentations. At BarCampMontreal2 the attendees were about 10% women, while the presenters were about 20% women. That means women who attended were more likely to present than men who attended. How come? Now that's something worth discussing.
Furthermore, the majority of male presenters talked about technical or business topics. The four women that I saw present (I apologize if I'm leaving someone out; I missed about half the conference) talked about WikiTravel (technical), Travelling Alone (non-technical), Lucid Dreaming (non-technical), and Women in Technology (social issues). In other words, 3/4 of the topics were "geeky but non-technical" and thus were just fine at a BarCamp, but wouldn't have been found at a normal tech conference. What does that say about the reasons women don't attend tech conferences? What does it say about the social effect of BarCamps?
Footnote
We should probably be thanking sfllaw, who I suspect was single-handedly responsible for skewing the above statistics.
Why would you follow me on twitter? Use RSS.
apenwarr-on-gmail.com | __label__pos | 0.78858 |
Reply
Member
Posts: 1
PCI Simple Communications Controller ?
Hello, upgraded from xp to 7 64 bit, now touch pad wont work, downloaded drivers ALP 7.5 for that, still wont work, downloaded value added package, still nothing. When I check device manager I have a ! with yellow triangle saying PCI Simple Communications Controller. I cannot find and drivers for this anywhere. My laptop is a protege m750. Any help would be appreciated Thanks!!! Jefff
Frequent Advisor
Posts: 8,188
Re: PCI Simple Communications Controller ?
Telling us it's a Portege M750 tells us about as much as saying you drive a Ford Car. What is the rest of the model number?
What is the second digit of the serial number? Do NOT post the complete serial number, just the second digit.
Did you download and follow the WIndow 7 upgrade guide from the Product Support Linka t the top of this page for your specific model?
Did you run the Toshiba Software Installer to see if it can find the missing drivers?
-------------------------------------------------------------------------------------
If you don't post your COMPLETE model number it's very difficult to assist you. Please try to post in complete sentences with punctuation, capitals, and correct spelling. Toshiba does NOT provide any direct support in these forums. All support is User to User in their spare time.
Member
Posts: 1
Re: PCI Simple Communications Controller ?
Apparently the additional model number info and serial number blah blah doesn't really matter because I'm running a Satelliet A505 and getting the same problem. The issue is that the Windows 7 Devices and Printers Troubleshooter says: PCI Simple Communications Controller doesn't have a driver.
What's that mean cee_64 who may or may not drive a Ford Car? Why can't the Windows Troubleshooter simply find the missing driver? Is there a mysterious device attached to my laptop that I can't see? Has McAffee failed to detect some sort of virus? Are Toshiba's services not fully integrated with Windows 7?
Frequent Advisor
Posts: 8,188
Re: PCI Simple Communications Controller ?
[ Edited ]
The need for the rest of the COMPLETE model number is due to the way Toshiba has their support download site configured. Without all of the model number there is no way to know which model to download drivers. The second digit of the serial number is to identify the year. This is important to identify what method or tools are best suited for upgrading from Vista to Win 7 and/or if Toshiba is actually supporting that specific model under Win 7 by providing drivers for it. Also, without knowing the specific model there is no way for us to know all of the hardware devices that model included. Without knowing that, how are any of us supposed to be able to figure out what specific componant is malfunctioning or not being properly detected? PCI Simple Communications Controller covers more than one item. There are definite reasons why we ask the questions that we do.
Again, without more information it's impossible to diagnose your problemm. Windows Troubleshooter isn't foolproof. It can't be relied upon to fix every problem. NO AV program can detect and deal with every malware thread, and it would be impossible to create one that could due to the nature of how they work . As for Toshiba Services being fully integrated with Windows 7, that again depends on the specific model, what Windows 7 drivers and utilities are available for it, and if they are all installed or not.
Another problem can be what other software and hardware people have connected to the laptop. A lot of multi-function devices will have various componants that don't always install correctly (printers, cell phones, and MP3 players are especially bad about this). It's quite possible that one of these could have something that isn't fully installed. This would not indicate a problem on Toshiba's part as they would have no control ove this.
Try going into Device Manager, removing any devices with an exclamation or question mark, then immediately rebooting the system to see if Windows can automatically install the necessary drivers for the device. If that doesn't work post back with the requested details and we'll see what we can come up with.
-------------------------------------------------------------------------------------
If you don't post your COMPLETE model number it's very difficult to assist you. Please try to post in complete sentences with punctuation, capitals, and correct spelling. Toshiba does NOT provide any direct support in these forums. All support is User to User in their spare time.
Member
Posts: 1
Re: PCI Simple Communications Controller ?
SOLUTION
The driver is the: Intel Management Engine Interface (HERE)
Posts: 4,350
Topics: 51
Kudos: 1,068
Solutions: 335
Registered: 05-03-2009
Re: PCI Simple Communications Controller ?
[ Edited ]
The post you just answered is almost 3 years old but thanks for the thought.
C.B.
C.B.
Toshiba Sat. C75D-B7260 Win 8.1 64 Bit--Toshiba Sat. L775D-S7132 Win 7 HP SP1 64 Bit and Win 10 PRO Technical Preview--Toshiba Sat. L305-S5921 Win Vista SP2 32 Bit | __label__pos | 0.628899 |
Buy Crypto
Markets
Exchange
Futures
Finance
Promotion
More
Newbie
Log In
CoinEx Academy
What Is Web3 Data Storage and How Does It Work?
2023-04-28 01:21:34
Nowadays, users are increasingly concerned about the privacy of their data. As a result, they are moving away from centralized storage providers and towards Web3 storage technologies to satisfy their requirements. There is no superior alternative to "Web3 Storage" for any user concerned about their files' security. In addition, it also allows you to save and back up your files.
If you want to learn more about Web3 data storage, a detailed blog post is below.
What is Web3 data storage
What is Web3 data storage?
Web3 storage is a data-holding solution that makes use of blockchain technology. This is also known as decentralized storage.
A blockchain can be conceptualized as a digital chain of blocks, each storing data. This is the most straightforward approach to understanding how a blockchain works. The data stored on blockchains is protected by hashing, which ensures that the data cannot be modified. Data stored on a blockchain is also encrypted, making it significantly more difficult for hackers to access important information.
Data storage evolution: Web1 to Web3
Web1
The earliest version of the World Wide Web (Web1) was primarily a static medium in which websites were introduced. This revolutionary development gave users a robust platform on which to enjoy media. The fundamental flaw was that it only allowed for one-way communication. In Web1, users could only view content without creating or contributing to it. As a result, web1 was an uninteresting place to work compared to the modern web. Web1 was similarly highly governed and regulated by its developers. They could also read and communicate with user data. Users were merely observers of web1 and had no control over the stuff they interacted with.
Web2
Users can both browse and create content on Web2. They can also produce blogs, video tutorials, and other content. Users' actions are restricted, though. Web2 enables its users to do more with their creativity, such as making their websites and connecting with data in new ways. They can now offer features and services that simply weren't conceivable with web1. However, such data is stored and hosted on servers owned and managed by major technology corporations. The data users generate and upload to the internet is out of their hands. Therefore, information exchange and storage on the web are centrally located.
Web3
Web3 is decentralized, meaning no single entity is operating it all. The decentralized nature of Web3 ensures that users have unrestricted access to all their data while protecting their privacy. This user-focused web implementation is powered by blockchain networks, allowing decentralized data storage and processing instead of relying on a small number of central servers. Instead of using conventional methods, they communicate with users through dApps.
How does Web3 data storage work? Why is it important?
Crypto blocks store transaction data, enabling network members to examine a distributed ledger containing a particular cryptocurrency's transaction history. Bitcoin, Dogecoin, Ethereum, and Tether are examples of cryptocurrencies that use blockchain technology. Because they do not depend on centralized authority or outside parties for their operation, these networks are sometimes called peer-to-peer or P2P networks. Its participants keep the network running, often known as miners or validators.
In Web3 storage, data is stored using a distributed model that employs blockchain technology in conjunction with this decentralized storage paradigm. User data is fragmented and spread over several nodes inside a Web3 storage network. Because of how the data is divided, it will be tough for hackers to obtain all of it. These pieces are encrypted, and duplicates are generated as a backup if something goes wrong.
Why do we need decentralized data storage?
Blockchain technology is used to develop the underlying infrastructure of web3. Because blockchains are not designed to store significant information, a blockchain needs to utilize decentralized storage. The consensus of a blockchain relies on quantities of transaction data being grouped in blocks and then rapidly distributed among nodes for validation. To begin, even though storing data in these blocks is possible, doing so comes at a very high cost.
Second, let's imagine that these blocks are used to store massive amounts of utterly random information. In that scenario, there is a significant possibility that network congestion will significantly worsen, which will likely result in higher costs for consumers to access the network because of competitive bidding for gas. This is because of the implicit time-value block, which stipulates that users that need to submit transactions to the network at a specific time must pay higher petrol prices for those transactions to be prioritized. Because of this, it is strongly suggested that the NFT underlying metadata and the picture data for dApp front-ends be stored off-chain.
Thirdly, we need decentralized data storage because censorship and content modification are also possible on centralized networks. Data can be erased intentionally or accidentally due to policy shifts implemented by the storage provider, faults in hardware, or attacks launched by third parties.
How is Web3 decentralized storage different from cloud storage?
One of the major drawbacks is that many of the most popular storage platforms are run from a single location. This indicates that the information consumers entrust the provider with is centralized in a single place. Utilizing a single central site such as this can prove troublesome, mainly because it provides a single point of failure.
"single point of failure" refers to a vulnerability or problem that can bring down a whole network and system. However, outages, hacks, and other issues are significantly less likely to occur when the network is supported by hundreds or thousands of nodes instead of just a few.
No centralized organization can access the decryption keys for the data you store using a Web3 platform. Instead, the private encryption key used to decrypt your data is stored only on your device. You are the only one who has access to this key.
One more thing that makes Web3 storage platforms unique is their use of crypto.
Web3 data storage solutions
First, it is essential to note that "decentralized data storage" is another name for Web3 storage solutions. At this point, you are already familiar with what Web3 storage solutions are. You are also aware that adopting a decentralized strategy removes the possibility of a single point of failure and the problem of a centralized institution misusing or manipulating confidential data.
In light of this, people who hope for a better future unanimously agree that decentralized data storage solutions play an essential role. The good news is that a few projects are already concentrating on covering that issue. In addition, keep in mind that each one takes a different approach to guarantee redundancy, efficiency, and the appropriate amount of decentralization. It is reasonable to assume that development is still taking place, and the optimal method for storing Web3 data has yet to be developed.
In addition to the InterPlanetary File System (IPFS), which does not make use of blockchain technology, we have the following initiatives that are expanding the frontier of "Web3 storage":
• Holo (HOT)
• Crust Network
• Sia
• Arweave (AR)
• Storj
• SONM
Benefits and limitations of Web3 data storage
On Web3 storage platforms, you can request files like on other storage platforms. On the other hand, rather than simply taking the complete file, the fragments are extracted from each node and then sent to you as a whole.
Because no single device in a decentralized storage network would ever hold the totality of a file, no one within the web can steal the file.
The users of many decentralized storage sites are given their private keys, which can then be used to access the data stored on those platforms. Without the private key, the data will continue to be inaccessible. This gives consumers complete control over their data rather than giving that control to a central body, which is consistent with the own idea of Web3.
Prev
What Is Osmosis and How to Buy OSMO?
Next
What Is Crypto Raiders (RAIDER)? | __label__pos | 0.964548 |
#include using namespace std; int main() // Note to self: for vs. while loop? { int num; cout << "what do you want to count down from?\n"; cin >> num; // #1 setup while(num > 0) // #2 check { if(num == 5) { break; } cout << num << "...\n"; num--; // num = num-1; // num -= 1; // #3 change var } cout << "BLASTOFF!\n"; } /* int main() // Note to self: same for while loop? { //for(int i=0; i < 10; i++) int i=0; while(i < 10) { if(i == 5) { break; // go directly to line 7, do not pass go or collect $200 } cout << i << endl; i++; } return 0; } */ | __label__pos | 0.999432 |
Take the 2-minute tour ×
Mathematics Stack Exchange is a question and answer site for people studying math at any level and professionals in related fields. It's 100% free, no registration required.
This is only directed towards logicians, model theorists etc.. I am reading "Model Theory" by Keisler and Chang and have encountered the following question.
Let $\Psi = \{M_1,...,M_n \}$ be a finite set of models (also known as interpretations) of a given language $L$. Let me also mention that $L$ is generated from a countably infinite alphabet $S$. Prove that $\exists$ a set $\Gamma$ of sentences (or well-formed formulas) such that $\Psi$ is the set of all models for $\Gamma$.
share|improve this question
2
I don't have the book. The assertion makes no sense for first-order logic if any of the $M_i$ is infinite, by Lowenheim-Skolem. – André Nicolas Oct 10 '12 at 5:25
I apologise for the confusion. This is in sentential or predicate logic. – user44069 Oct 10 '12 at 5:26
By first-order logic I meant the predicate calculus, what you call predicate logic. Remark about if one of the $M_i$ is infinite still stands. – André Nicolas Oct 10 '12 at 5:35
@André: I have the first edition; it has a version of this as part (i) of a starred exercise (Ex. 1.2.9) in the section on model theory for sentential logic, not predicate logic. Here a model is simply a subset of the set $\mathscr{S}$ of simple statements. – Brian M. Scott Oct 10 '12 at 6:19
add comment
2 Answers
up vote 5 down vote accepted
(Using the notation from Chang-Keisler.) Let the models be $M_1 , \ldots , M_n \subseteq \mathscr{S}$.
For each sentence symbol $S$ of $\mathscr{S}$ and each $i \leq n$, by $S_i$ denote $$ \begin{cases} S, &\text{if }S \in M_i \\ \neg S, &\text{if }S \notin M_i. \end{cases} $$ Let $\Gamma$ be the set of all sentences of the form $$ (S^1_1 \wedge \cdots \wedge S^m_1 ) \vee \cdots \vee (S^1_n \wedge \cdots \wedge S^m_n ) $$ where $S^1 , \ldots , S^m \in \mathscr{S}$.
Clearly each $M_i$ is a model of $\Gamma$.
Suppose now that $N \subseteq \mathscr{S}$ is some model distinct from each $M_i$. For each $i \leq n$ there is a sentence symbol, $S^i$ such that either $S^i \in M_i$ and $S^i \notin N$, or the opposite. It is easily seen that $N$ is not a model of the sentence $$ (S^1_1 \wedge \cdots \wedge S^n_1 ) \vee \cdots \vee (S^1_n \wedge \cdots \wedge S^n_n ) $$ ($N$ cannot model $(S^1_i \wedge \cdots \wedge S^n_i )$ since by construction it does not model $S^i_i$.)
share|improve this answer
I have a question. Does this answer presuppose that $\mathscr{S}$ is finite? Because otherwise we could always have a model $N$ such that $M_i \subset N$, no? (I'm thinking specifically of your other answer to my question about the cardinality of the set of all models for $\phi$ when $\phi$ is satisfiable and $\mathscr{S}$ is countably infinite. – Nagase Mar 24 at 0:46
@Nagase: No. What's going on above is that given sentence symbols $S^1 , \ldots , S^m \in \mathscr{S}$ I form a sentence, call it $\phi(S^1 , \ldots , S^m)$, and then my set $\Gamma$ of $\mathscr{S}$-sentences is the collection of all these $\phi(S^1,\ldots,S^m)$. Your previous question was to show that there are uncountably many models of one specific sentence provided $\mathscr{S}$ is infinite; here I am constructing an uncountable set of sentences with only finitely many (prescribed) models. – Arthur Fischer Mar 24 at 4:13
I see. I think that I was wrongly focused on the (let us call it) expressive power of a sentence, and missing the fact that we're working with a set of sentences. Missing the forest for the trees, so to speak! – Nagase Mar 24 at 13:12
Sorry to insist on this again, but I have a further question. If $\mathscr{S}$ is infinite, does your construction require infinite long formulas? I ask this because, if I understood your construction correctly, we need to negate every sentence symbol which does not appear in the model; since the models are finite, if $\mathscr{S}$ is infinite, there will be infinite many symbols which won't appear in the model. Is this correct? – Nagase yesterday
@Nagase: No, it doesn't require infinitely long formulas. I just pick some finite number of sentences from $\mathscr{S}$, and then form a sentence (of finite length) from these finitely many sentences determined by the true-false patterns in the given models. But I do this for all choices of finitely many sentences from $\mathscr{S}$, so I will end up with an infinite collection $\Gamma$ of sentences. (Also, the models themselves could be infinite, I just have finitely many of them.) – Arthur Fischer yesterday
add comment
Let $\Gamma$ be the set of sentences that are true for all of the $M_i$. If $M_i\ne M_j$, there is a sentence $\phi_{i,j}$ that is true in $M_i$ and false in $M_j$. Let $\phi_i=\phi_{i,1}\land\cdots\land\phi_{i,n}$ (with $\phi_{i,i}$ omitted). Then $\phi_i$ is true in $M_i$ and false in all $M_j$ with $j\ne i$. Let $\phi=\phi_1\lor\cdots\lor\phi_n$. Then $\phi$ holds in all $M_i$, hene $\phi\in\Gamma$.
Let $M$ be a model of $\Gamma$. Then $\phi$ is true in $M$, hence (at least) one $\phi_i$ is true in $M$. If $\psi$ is a sentence that is true in $M_i$ then $\phi_i\to \psi$ is in $\Gamma$ because $\phi_i$ is false in $M_j$ with $j\ne i$ and $\psi$ is true in $M_i$. It follows that $\phi_i\to \psi$ is true in $M$ and finally $\psi$ is true in $M$. If on the other hand, $\psi$ is false in $M_i$, then $\neg\psi$ is true in $M_i$, hence true in $M$, hence $\psi$ false in $M$. We conclude that $M=M_i$.
share|improve this answer
add comment
Your Answer
discard
By posting your answer, you agree to the privacy policy and terms of service. | __label__pos | 0.994275 |
Session 6
What does this program do?
# Guess my number
puts "I'm thinking of a number between 1 and 100."
puts "What is it?"
my_number = rand(100) + 1
guess = gets.chomp.to_i
while guess > 0 && guess <= 100
if guess == my_number
puts "You guessed it! My number is " + guess.to_s + "."
break
elsif guess < my_number
puts "Wrong, " + guess.to_s + " is too low."
else
puts "Wrong, " + guess.to_s + " is too high."
end
puts "Guess again."
guess = gets.chomp.to_i
end
Arrays
Arrays are variables that contain lists of things
my_array = ['one', 'two', 'three']
empty_array = []
tic_tac_toe = [['X', 'O', 'O'], ['X', 'O', '-'], ['-', '-', 'X']]
# the whole array
puts my_array
puts
# by index
# starts at zero
puts my_array[0]
puts my_array[1]
puts my_array[2]
puts
# what's this?
puts my_array[3]
# nil is a special object that has no value
my_array[3] = 'four'
puts my_array[3]
puts
# arrays have an 'each' method
my_array.each do |element|
puts "the next element is " + element
end
puts
# here's another iterator
3.times do
puts "hey there!"
end
# lots of array methods: google search "ruby array"
puts
# length returns the size of the array
puts my_array.length
# size does the same thing
puts my_array.size
puts
# reverse
my_array.reverse.each do |element|
puts element
end
puts
# join
puts my_array.join(', ')
puts
# first and last
puts "first: " + my_array.first
puts "last: " + my_array.last
puts
# push adds things to the end of the array
my_array.push "five"
puts my_array.join(', ')
puts
# pop removes things from the end of the array
my_array.pop
puts my_array.join(', ')
number = my_array.pop
puts my_array.join(', ')
puts
# clear empties the array
my_array.clear
puts "size: " + my_array.length.to_is
Alphabetize a bunch of words
puts "Type a bunch of words, one on each line."
puts "(empty line when you are done)"
words = []
word = gets.chomp
while word.length > 0
words.push word
word = gets.chomp
end
puts "ok, your words sorted are: "
words.sort.each do |next_word|
puts next_word
end
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License | __label__pos | 0.973526 |
Menu
STAY AT HOME
reorder with our app!
Buy online, stay safe!
Get it on Google Play
Google Play and the Google Play logo are trademarks of Google LLC
Online UPC validation tool
UPCZilla’s tool for validating UPCs which also gives you a handy explanation of how the validation was performed.
013137003196 is a valid UPC-A (though that doesn't mean it's assigned to any products, click here to see if it is: 013137003196 - 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 1 3 1 3 7 0 0 3 1 9 (6) - last digit ignored for now
0 (digit 1) + 3 (digit 3) + 3 (digit 5) + 0 (digit 7) + 3 (digit 9) + 9 (digit 11) = 18
2. Then we multiply that number (18) by 3:18 X 3 = 54 (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 1 3 1 3 7 0 0 3 1 9 (6) - last digit still ignored
1 (digit 2) + 1 (digit 4) + 7 (digit 6) + 0 (digit 8) + 1 (digit 10) = 10
4. We get the number we got in step 3 (10) and we ADD it to the number we got in step 2 (54):10 + 54 = 64
5. Now we take the number we got in step 4 (64) and work out how much we have to add to round it up to the nearest 10. In order to round 64 up to the nearest 10 (70) 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.905746 |
Geogebra Doodads
Geogebra is a great tool for communicating mathematics. In recent versions, developers have added the ability to export to HTML5 (as opposed to Java) making it even easier to share a ggb file. In addition, an animated .gif file can be created from any ggb file with a slider in it.
In the past, I have dumped my various student activities and teacher presentations in one large directory. Now, I want to start putting out my work in a little more organized fashion, by introducing them on the blog and tagging and labeling. For now, I’ve decided to call them “Doodads”. Perhaps a better vocab word is out there to represent the interactive, mathematical, and curiosity sparking nature of these creations.
Here is the first one:
Time Angles (ggb doodad)
In the spirit of Dan Meyer’s WCYDWT, what is the first question that comes into your head?
The “answer” :
Copper Tiling… classic WCYDWT
Ran across this on reddit
The smile inducing “how much does it cost?” is a great place to start.
But how about “how much area is wasted?” to touch on the packing problem of circles. http://en.wikipedia.org/wiki/Circle_packing_in_a_square
And hey, might as well kick it up into 3D… http://www.youtube.com/watch?v=uDJ3sor2oQ0
WCYDWT / 101qs: 13 Folds
Dan Meyer has morphed his “What can you do with this” edu-meme into “#101qs”: what questions pop into your head upon observing a picture, movie, or other demonstration. The more likely it is that a student will ask that question, the better.
I will present one now. For your consideration,
“13 Folds”
13 Folds
If you tossed that up in your class, what would the kids say? What’s the first question that pops into your head?
I’ll offer my own thoughts, and I welcome you to share yours in the comments.
I think this image has a lot of things going for it. It is clearly the ACT1 image. Toss it up. Don’t say anything. What will the kids ask?
What is it?
Toilet Paper.
That’s hella toilet paper! (excuse the norcal slang 😉 )
yeah! it’s a lot!
How much?
I dunno.
What do you mean you don’t know!? you’re the teacher!
Can we figure it out?
At this point, you can go to ACT2: Have the students figure out what they need. In this case, there’s a rather nice ACT2 image:
Act 2
Alternatively, you could say 5 feet by 2.5 feet on the image. Or if you’re really brave, you could estimate it by the heights of the kids in the screenshot. Ideally, you don’t have to say much else. To a stuck student I might offer only: “unfold it“.
Extensions:
1. Graph it.
2. How many rolls did they buy? What did it cost them?
3. How thick is the paper? Graph THAT.
4. How many layers are at the 13th fold? Another graph to make!
5. Why toilet paper?
6. What is preventing the 14th fold? Why did they stop?
And finally,
Act 3
Ah, but there’s a bonus: we have the actual video of them doing the folds. What a great way to end the class!
http://www.youtube.com/watch?v=vPFnIotfkXo
Why toilet paper? Try the Mythbusters episode: http://www.youtube.com/watch?v=kRAEBbotuIE
And then for those super interested kids who can access the final extension questions, you can lead them through Brittany Gallivan’s solution for arbitrary paper: http://en.wikipedia.org/wiki/Britney_Gallivan
Credit to Dr. James Tanton http://www.jamestanton.com/ for leading the actual exercise at MIT.
Toss me some comments!
WCYDWT: Displaced Water
In brainstorming about opposites and the additive inverse, I came up with an idea about justifying one step equations with this displaced water video. But, it doesn’t quite lend itself to subtracting from both sides. I’m going to try this as is, and perhaps we can come up with ideas in class about how well this lends itself to x+800=____ish.
I think this could also take a geometry route. It reminds me of the demonstrations that a cylinder of height 2h and radius h has equal volume to (a sphere of radius h + a cone of height and radius h).
But right now, the ideas are in their infancy.
P.S. what did you get? Here is the answer.
WCYDWT: Escalator
In the style of Dan Meyer’s WCYDWT… I may not have time to do a full lesson around this in my Algebra class. There are only 4 days left and we are rushing through the required tests. But inspiration hit me when I saw this view:
I
Click for video
I put it up in my small 6th period class to get a taste for how things would go. Students immediately related to it (one kid correctly named the BART station) With a little prodding — “did you see the guy with the bike who was bookin’ it?” — they talked about how fast people were going. Then they talked about trying to go down an escalator going up or up and escalator going down. We didn’t get to any sort of problem solving, but we did count that it took about 30 seconds to merely ride the escalator up.
More on this as it develops… especially if I have time to implement it fully. | __label__pos | 0.511859 |
FastDFS与Springboot集成
2018-03-21 17:06:40
710次阅读
0个评论
1、添加pom依赖
<dependency>
<groupId>com.github.tobato</groupId>
<artifactId>fastdfs-client</artifactId>
<version>1.25.2-RELEASE</version>
</dependency>
2、将Fdfs配置引入项目
我将注解配置加在springboot的入口类中:@Import(FdfsClientConfig.class)
@Import(FdfsClientConfig.class)
@SpringBootApplication
public class JingtongApplication {
public static void main(String[] args) {
SpringApplication.run(JingtongApplication.class, args);
}
}
3、在spring配置文件中加入fdfs相关配置
根据项目当中使用配置文件类型(.yml和.properties选择其中一个),加入相应的配置。
application.yml
fdfs:
soTimeout: 1500
connectTimeout: 600
thumbImage: #缩略图生成参数
width: 150
height: 150
trackerList: #TrackerList参数,支持多个
- 192.168.0.201:22122
- 192.168.0.202:22122
application.properties
fdfs.soTimeout=1500
fdfs.connectTimeout=600
fdfs.thumbImage.width=150
fdfs.thumbImage.height=150
fdfs.trackerList[0]=192.168.0.201:22122
fdfs.trackerList[1]=192.168.0.202:22122
4、在项目中使用
客户端主要包括以下接口:
TrackerClient - TrackerServer接口
GenerateStorageClient - 一般文件存储接口 (StorageServer接口)
FastFileStorageClient - 为方便项目开发集成的简单接口(StorageServer接口)
AppendFileStorageClient - 支持文件续传操作的接口 (StorageServer接口)
笔者在前一个项目当中将fdfs主要用于图片存储,基于FastFileStorageClient接口和springmvc提供的MultipartFile接口封装了一个简单的工具类,方便全局管理与调用。如下所示:
import com.digi_zones.config.AppConfig;
import com.digi_zones.contacts.AppConstants;
import com.github.tobato.fastdfs.domain.FileInfo;
import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.exception.FdfsUnsupportStorePathException;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.Charset;
/**
* <p>Description: FastDFS文件上传下载包装类</p>
*/
@Component
public class FastDFSClientWrapper {
private final Logger logger = LoggerFactory.getLogger(FastDFSClientWrapper.class);
@Autowired
private FastFileStorageClient storageClient;
@Autowired
private AppConfig appConfig; // 项目参数配置
/**
* 上传文件
* @param file 文件对象
* @return 文件访问地址
* @throws IOException
*/
public String uploadFile(MultipartFile file) throws IOException {
StorePath storePath = storageClient.uploadFile(file.getInputStream(),file.getSize(), FilenameUtils.getExtension(file.getOriginalFilename()),null);
return getResAccessUrl(storePath);
}
/**
* 将一段字符串生成一个文件上传
* @param content 文件内容
* @param fileExtension
* @return
*/
public String uploadFile(String content, String fileExtension) {
byte[] buff = content.getBytes(Charset.forName("UTF-8"));
ByteArrayInputStream stream = new ByteArrayInputStream(buff);
StorePath storePath = storageClient.uploadFile(stream,buff.length, fileExtension,null);
return getResAccessUrl(storePath);
}
// 封装图片完整URL地址
private String getResAccessUrl(StorePath storePath) {
String fileUrl = AppConstants.HTTP_PRODOCOL + appConfig.getResHost()
+ ":" + appConfig.getFdfsStoragePort() + "/" + storePath.getFullPath();
return fileUrl;
}
/**
* 删除文件
* @param fileUrl 文件访问地址
* @return
*/
public void deleteFile(String fileUrl) {
if (StringUtils.isEmpty(fileUrl)) {
return;
}
try {
StorePath storePath = StorePath.praseFromUrl(fileUrl);
storageClient.deleteFile(storePath.getGroup(), storePath.getPath());
} catch (FdfsUnsupportStorePathException e) {
logger.warn(e.getMessage());
}
}
}
除了FastDFSClientWrapper类中用到的api,客户端提供的api还有很多,可根据自身的业务需求,将其它接口也添加到工具类中即可。如下所示:
// 上传文件,并添加文件元数据
StorePath uploadFile(InputStream inputStream, long fileSize, String fileExtName, Set<MateData> metaDataSet);
// 获取文件元数据
Set<MateData> getMetadata(String groupName, String path);
// 上传图片并同时生成一个缩略图
StorePath uploadImageAndCrtThumbImage(InputStream inputStream, long fileSize, String fileExtName,
Set<MateData> metaDataSet);
// 。。。
在项目中使用FastDFSClientWrapper:
@Controller
public class MyController {
@Autowired
private FastDFSClientWrapper dfsClient;
// 上传图片
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public String upload(MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws Exception {
// 省略业务逻辑代码。。。
String imgUrl = dfsClient.uploadFile(file);
// 。。。。
return xxxx;
}
}
收藏 0 0
登录 后评论。没有帐号? 注册 一个。
admin
官方人员
• 0 回答
• 0 粉丝
• 0 关注 | __label__pos | 0.773397 |
Home My Page Projects Code Snippets Project Openings diderot
Summary Activity Tracker Tasks SCM
SCM Repository
[diderot] View of /branches/charisee_dev/src/compiler/high-to-mid/ProbeEin.sml
ViewVC logotype
View of /branches/charisee_dev/src/compiler/high-to-mid/ProbeEin.sml
Parent Directory Parent Directory | Revision Log Revision Log
Revision 3349 - (download) (annotate)
Tue Oct 27 15:16:36 2015 UTC (3 years, 11 months ago) by jhr
File size: 16837 byte(s)
making copyrights consistent for all code in the repository
(* Expands probe ein
*
* This code is part of the Diderot Project (http://diderot-language.cs.uchicago.edu)
*
* COPYRIGHT (c) 2015 The University of Chicago
* All rights reserved.
*)
structure ProbeEin = struct
local
structure E = Ein
structure DstIL = MidIL
structure DstOp = MidOps
structure P = Printer
structure T = TransformEin
structure MidToS = MidToString
structure DstV = DstIL.Var
structure DstTy = MidILTypes
in
(* This file expands probed fields
* Take a look at ProbeEin tex file for examples
*Note that the original field is an EIN operator in the form <V_alpha * H^(deltas)>(midIL.var list )
* Param_ids are used to note the placement of the argument in the midIL.var list
* Index_ids keep track of the shape of an Image or differentiation.
* Mu bind Index_id
* Generally, we will refer to the following
*dim:dimension of field V
* s: support of kernel H
* alpha: The alpha in <V_alpha * H^(deltas)>
* deltas: The deltas in <V_alpha * H^(deltas)>
* Vid:param_id for V
* hid:param_id for H
* nid: integer position param_id
* fid :fractional position param_id
* img-imginfo about V
*)
val testing=0
val testlift=1
val detflag =true
val fieldliftflag=true
val valnumflag=true
val cnt = ref 0
fun transformToIndexSpace e=T.transformToIndexSpace e
fun transformToImgSpace e=T.transformToImgSpace e
fun toStringBind e=(MidToString.toStringBind e)
fun mkEin e=Ein.mkEin e
fun mkEinApp(rator,args)=DstIL.EINAPP(rator,args)
fun testp n=(case testing
of 0=> 1
| _ =>(print(String.concat n);1)
(*end case*))
fun getRHSDst x = (case DstIL.Var.binding x
of DstIL.VB_RHS(DstIL.OP(rator, args)) => (rator, args)
| DstIL.VB_RHS(DstIL.VAR x') => getRHSDst x'
| vb => raise Fail(concat[ "expected rhs operator for ", DstIL.Var.toString x, "but found ", DstIL.vbToString vb])
(* end case *))
(* getArgsDst:MidIL.Var* MidIL.Var->int, ImageInfo, int
uses the Param_ids for the image, kernel,
and position tensor to get the Mid-IL arguments
returns the support of ther kernel, and image
*)
fun getArgsDst(hArg,imgArg,args) = (case (getRHSDst hArg, getRHSDst imgArg)
of ((DstOp.Kernel(h, i), _ ), (DstOp.LoadImage(_, _, img), _ ))=> let
in
((Kernel.support h) ,img,ImageInfo.dim img)
end
| _ => raise Fail "Expected Image and kernel arguments"
(*end case*))
(*handleArgs():int*int*int*Mid IL.Var list
->int*Mid.ILVars list* code*int* low-il-var
* uses the Param_ids for the image, kernel, and tensor
* and gets the mid-IL vars for each.
*Transforms the position to index space
*P is the mid-il var for the (transformation matrix)transpose
*)
fun handleArgs(Vid,hid,tid,args)=let
val imgArg=List.nth(args,Vid)
val hArg=List.nth(args,hid)
val newposArg=List.nth(args,tid)
val (s,img,dim) =getArgsDst(hArg,imgArg,args)
val (argsT,P,code)=transformToImgSpace(dim,img,newposArg,imgArg)
in
(dim,args@argsT,code, s,P)
end
(*createBody:int*int*int,mu list, param_id, param_id, param_id, param_id
* expands the body for the probed field
*)
fun createBody(dim, s,sx,alpha,deltas,Vid, hid, nid, fid)=let
(*1-d fields*)
fun createKRND1 ()=let
val sum=sx
val dels=List.map (fn e=>(E.C 0,e)) deltas
val pos=[E.Add[E.Tensor(fid,[]),E.Value(sum)]]
val rest= E.Krn(hid,dels,E.Sub(E.Tensor(nid,[]),E.Value(sum)))
in
E.Prod [E.Img(Vid,alpha,pos),rest]
end
(*createKRN Image field and kernels *)
fun createKRN(0,imgpos,rest)=E.Prod ([E.Img(Vid,alpha,imgpos)] @rest)
| createKRN(dim,imgpos,rest)=let
val dim'=dim-1
val sum=sx+dim'
val dels=List.map (fn e=>(E.C dim',e)) deltas
val pos=[E.Add[E.Tensor(fid,[E.C dim']),E.Value(sum)]]
val rest'= E.Krn(hid,dels,E.Sub(E.Tensor(nid,[E.C dim']),E.Value(sum)))
in
createKRN(dim',pos@imgpos,[rest']@rest)
end
val exp=(case dim
of 1 => createKRND1()
| _=> createKRN(dim, [],[])
(*end case*))
(*sumIndex creating summaiton Index for body*)
val slb=1-s
val esum=List.tabulate(dim, (fn dim=>(E.V (dim+sx),slb,s)))
in
E.Sum(esum, exp)
end
(*getsumshift:sum_indexid list* int list-> int
*get fresh/unused index_id, returns int
*)
fun getsumshift(sx,index) =let
val nsumshift= (case sx
of []=> length(index)
| _=>let
val (E.V v,_,_)=List.hd(List.rev sx)
in v+1
end
(* end case *))
val aa=List.map (fn (E.V v,_,_)=>Int.toString v) sx
val _ =testp["\n", "SumIndex" ,(String.concatWith"," aa),
"\nThink nshift is ", Int.toString nsumshift]
in
nsumshift
end
(*formBody:ein_exp->ein_exp
*just does a quick rewrite
*)
fun formBody(E.Sum([],e))=formBody e
| formBody(E.Sum(sx,e))= E.Sum(sx,formBody e)
| formBody(E.Prod [e])=e
| formBody e=e
(* silly change in order of the product to match vis branch WorldtoSpace functions*)
fun multiPs([P0,P1,P2],sx,body)= formBody(E.Sum(sx, E.Prod([P0,P1,P2,body])))
| multiPs([P0,P1],sx,body)=formBody(E.Sum(sx, E.Prod([P0,body,P1])))
| multiPs(Ps,sx,body)=formBody(E.Sum(sx, E.Prod([body]@Ps)))
fun multiMergePs([P0,P1],[sx0,sx1],body)=E.Sum([sx0],E.Prod[P0,E.Sum([sx1],E.Prod[P1,body])])
| multiMergePs e=multiPs e
(* replaceProbe:ein_exp* params *midIL.var list * int list* sum_id list
-> ein_exp* *code
* Transforms position to world space
* transforms result back to index_space
* rewrites body
* replace probe with expanded version
*)
(* fun replaceProbe(testN,y,originalb,b,params,args,index, sx)*)
fun replaceProbe(testN,(y, DstIL.EINAPP(e,args)),p ,sx)
=let
val originalb=Ein.body e
val params=Ein.params e
val index=Ein.index e
val _ = testp["\n***************** \n Replace ************ \n"]
val _= toStringBind (y, DstIL.EINAPP(e,args))
val E.Probe(E.Conv(Vid,alpha,hid,dx),E.Tensor(tid,_))=p
val fid=length(params)
val nid=fid+1
val Pid=nid+1
val nshift=length(dx)
val (dim,argsA,code,s,PArg) = handleArgs(Vid,hid,tid,args)
val freshIndex=getsumshift(sx,index)
val (dx,newsx1,Ps)=transformToIndexSpace(freshIndex,dim,dx,Pid)
val params'=params@[E.TEN(3,[dim]),E.TEN(1,[dim]),E.TEN(1,[dim,dim])]
val body' = createBody(dim, s,freshIndex+nshift,alpha,dx,Vid, hid, nid, fid)
val body' = multiPs(Ps,newsx1,body')
val body'=(case originalb
of E.Sum(sx, E.Probe _) => E.Sum(sx,body')
| E.Sum(sx,E.Prod[eps0,E.Probe _ ]) => E.Sum(sx,E.Prod[eps0,body'])
| _ => body'
(*end case*))
val args'=argsA@[PArg]
val einapp=(y,mkEinApp(mkEin(params',index,body'),args'))
in
code@[einapp]
end
val tsplitvar=true
fun createEinApp(originalb,alpha,index,freshIndex,dim,dx,sx)= let
val Pid=0
val tid=1
(*Assumes body is already clean*)
val (newdx,newsx,Ps)=transformToIndexSpace(freshIndex,dim,dx,Pid)
(*need to rewrite dx*)
val (_,sizes,e as E.Conv(_,alpha',_,dx))=(case sx@newsx
of []=> ([],index,E.Conv(9,alpha,7,newdx))
| _ => cleanIndex.cleanIndex(E.Conv(9,alpha,7,newdx),index,sx@newsx)
(*end case*))
val params=[E.TEN(1,[dim,dim]),E.TEN(1,sizes)]
fun filterAlpha []=[]
| filterAlpha(E.C _::es)= filterAlpha es
| filterAlpha(e1::es)=[e1]@(filterAlpha es)
val tshape=filterAlpha(alpha')@newdx
val t=E.Tensor(tid,tshape)
val (splitvar,body)=(case originalb
of E.Sum(sx, E.Probe _) => (false,E.Sum(sx,multiPs(Ps,newsx,t)))
| E.Sum(sx,E.Prod[eps0,E.Probe _ ]) => (false,E.Sum(sx,E.Prod[eps0,multiPs(Ps,newsx,t)]))
| _ => (case tsplitvar
of(* true => (true,multiMergePs(Ps,newsx,t)) (*pushes summations in place*)
| false*) _ => (true,multiPs(Ps,newsx,t))
(*end case*))
(*end case*))
val _ =(case splitvar
of true=> (String.concat["splitvar is true", P.printbody body])
| _ => (String.concat["splitvar is false",P.printbody body])
(*end case*))
val ein0=mkEin(params,index,body)
in
(splitvar,ein0,sizes,dx,alpha')
end
fun liftProbe(printStrings,(y, DstIL.EINAPP(e,args)),p ,sx)=let
val _=testp["\n******* Lift ******** \n"]
val originalb=Ein.body e
val params=Ein.params e
val index=Ein.index e
val _= toStringBind (y, DstIL.EINAPP(e,args))
val E.Probe(E.Conv(Vid,alpha,hid,dx),E.Tensor(tid,_))=p
val fid=length(params)
val nid=fid+1
val nshift=length(dx)
val (dim,args',code,s,PArg) = handleArgs(Vid,hid,tid,args)
val freshIndex=getsumshift(sx,index)
(*transform T*P*P..Ps*)
val (splitvar,ein0,sizes,dx,alpha')= createEinApp(originalb,alpha,index,freshIndex,dim,dx,sx)
val FArg = DstV.new ("F", DstTy.TensorTy(sizes))
val einApp0=mkEinApp(ein0,[PArg,FArg])
val rtn0=(case splitvar
of false => [(y,mkEinApp(ein0,[PArg,FArg]))]
| _ => let
val bind3 = (y,DstIL.EINAPP(SummationEin.main ein0,[PArg,FArg]))
in Split.splitEinApp(bind3,0)
end
(*end case*))
(*lifted probe*)
val params'=params@[E.TEN(3,[dim]),E.TEN(1,[dim])]
val body' = createBody(dim, s,freshIndex+nshift,alpha',dx,Vid, hid, nid, fid)
val ein1=mkEin(params',sizes,body')
val einApp1=mkEinApp(ein1,args')
val rtn1=(FArg,einApp1)
val rtn=code@[rtn1]@rtn0
val _= List.map toStringBind ([rtn1]@rtn0)
in
rtn
end
fun liftFieldMat(newvx,e)=
let
val (y, DstIL.EINAPP(ein,args))=e
val E.Probe(E.Conv(V,[c1,v0],h,dx),pos)=Ein.body ein
val index0=Ein.index ein
val index1 = index0@[3]
val body1_unshifted = E.Probe(E.Conv(V,[E.V newvx, v0],h,dx),pos)
(* clean to get body indices in order *)
val ( _ , _, body1)= cleanIndex.cleanIndex(body1_unshifted,index1,[])
val _ = testp ["\n Shifted ",P.printbody body1_unshifted,"=>",P.printbody body1]
val lhs1=DstV.new ("L", DstTy.TensorTy(index1))
val ein1 = mkEin(Ein.params ein,index1,body1)
val code1= (lhs1,mkEinApp(ein1,args))
val codeAll= (case dx
of []=> replaceProbe(1,code1,body1,[])
| _ =>liftProbe(1,code1,body1,[])
(*end case*))
(*Probe that tensor at a constant position c1*)
val param0 = [E.TEN(1,index1)]
val nx=List.tabulate(length(dx)+1,fn n=>E.V n)
val body0 = E.Tensor(0,[c1]@nx)
val ein0 = mkEin(param0,index0,body0)
val einApp0 = mkEinApp(ein0,[lhs1])
val code0 = (y,einApp0)
val _= toStringBind code0
in
codeAll@[code0]
end
fun liftFieldSum e =
let
val _=print"\n*************************************\n"
val (y, DstIL.EINAPP(ein,args))=e
val E.Sum([(vsum,0,n)],E.Probe(E.Conv(V,[c1,v0],h,dx),pos))=Ein.body ein
val index0=Ein.index ein
val index1 = index0@[3]@[3]
val shiftdx=List.tabulate(length(dx),fn n=>E.V (n+2))
val body1 = E.Probe(E.Conv(V,[E.V 0,E.V 1],h,shiftdx),pos)
val lhs1=DstV.new ("L", DstTy.TensorTy(index1))
val ein1 = mkEin(Ein.params ein,index1,body1)
val code1= (lhs1,mkEinApp(ein1,args))
val codeAll= (case dx
of []=> replaceProbe(1,code1,body1,[])
| _ =>liftProbe(1,code1,body1,[])
(*end case*))
(*Probe that tensor at a constant position c1*)
val param0 = [E.TEN(1,index1)]
val nx=List.tabulate(length(dx),fn n=>E.V n)
val body0 = E.Sum([(vsum,0,n)],E.Tensor(0,[vsum,vsum]@nx))
val ein0 = mkEin(param0,index0,body0)
val einApp0 = mkEinApp(ein0,[lhs1])
val code0 = (y,einApp0)
val _= toStringBind e
val _ =toStringBind code0
val _ = (String.concat ["\norig",P.printbody(Ein.body ein),"\n replace i ",P.printbody body1,"\nfreshtensor",P.printbody body0])
val _ =(String.concat(List.map toStringBind (codeAll@[code0])))
val _=print"\n*************************************\n"
in
codeAll@[code0]
end
(* expandEinOp: code-> code list
* A this point we only have simple ein ops
* Looks to see if the expression has a probe. If so, replaces it.
* Note how we keeps eps expressions so only generate pieces that are used
*)
fun expandEinOp( e as (y, DstIL.EINAPP(ein,args)),fieldset)=let
fun checkConst ([],a) =
(case fieldliftflag
of true => liftProbe a
| _ => replaceProbe a
(*end case*))
| checkConst ((E.C _::_),a) = replaceProbe a
| checkConst ((_ ::es),a)= checkConst(es,a)
fun rewriteBody b=(case (detflag,b)
of (true,E.Probe(E.Conv(_,[E.C _ ,E.V 0],_,[]),pos))
=> liftFieldMat (1,e)
| (true,E.Probe(E.Conv(_,[E.C _ ,E.V 0],_,[E.V 1]),pos))
=> liftFieldMat (2,e)
| (true,E.Probe(E.Conv(_,[E.C _ ,E.V 0],_,[E.V 1,E.V 2] ),pos))
=> liftFieldMat (3,e)
| (true, E.Sum([(E.V 0,0,_)],E.Probe(E.Conv(_,[E.V 0 ,E.V 0],_,[]),pos)))
=> liftFieldSum e
| (true, E.Sum([(E.V 1,0,_)],E.Probe(E.Conv(_,[E.V 1 ,E.V 1],_,[E.V 0]),pos)))
=> liftFieldSum e
| (true, E.Sum([(E.V 2,0,_)],E.Probe(E.Conv(_,[E.V 2 ,E.V 2],_,[E.V 0,E.V 1]),pos)))
=> liftFieldSum e
| (_,E.Probe(E.Conv(_,_,_,[]),_))
=> replaceProbe(0,e,b,[])
| (_,E.Probe(E.Conv (_,alpha,_,dx),_))
=> checkConst(dx,(0,e,b,[])) (*scans dx for contant*)
| (_,E.Sum(sx,p as E.Probe(E.Conv(_,_,_,[]),_)))
=> replaceProbe(0,e,p, sx) (*no dx*)
| (_,E.Sum(sx,p as E.Probe(E.Conv(_,[],_,dx),_)))
=> checkConst(dx,(0,e,p,sx)) (*scalar field*)
| (_,E.Sum(sx,E.Probe p))
=> replaceProbe(0,e,E.Probe p, sx)
| (_,E.Sum(sx,E.Prod[eps,E.Probe p]))
=> replaceProbe(0,e,E.Probe p,sx)
| (_,_) => [e]
(* end case *))
val (fieldset,var) = (case valnumflag
of true => einSet.rtnVar(fieldset,y,DstIL.EINAPP(ein,args))
| _ => (fieldset,NONE)
(*end case*))
fun matchField b=(case b
of E.Probe _ => 1
| E.Sum (_, E.Probe _)=>1
| E.Sum(_, E.Prod[ _ ,E.Probe _])=>1
| _ =>0
(*end case*))
fun toStrField b=(case b
of E.Probe _ => print (P.printbody b)
| E.Sum (_, E.Probe _)=>print (P.printbody b)
| E.Sum(_, E.Prod[ _ ,E.Probe _])=>print (P.printbody b)
| _ =>print ""
(*end case*))
val b=Ein.body ein
fun printField b=(case b
of E.Probe _ => print ("\n"^(P.printbody b))
| E.Sum (_, E.Probe _)=>print ("\n"^(P.printbody b))
| E.Sum(_, E.Prod[ _ ,E.Probe _])=>print ("\n"^(P.printbody b))
| _ => print""
(*end case*))
in (case var
of NONE=> ((rewriteBody(Ein.body ein),fieldset,matchField(Ein.body ein),0))
| SOME v=> (("\n mapp_replacing"^(P.printerE ein)^":");( [(y,DstIL.VAR v)],fieldset, matchField(Ein.body ein),1))
(*end case*))
end
end; (* local *)
end (* local *)
[email protected]
ViewVC Help
Powered by ViewVC 1.0.0 | __label__pos | 0.870444 |
Backup?
Discussion in 'iOS 5 and earlier' started by BLOND37, Nov 10, 2011.
1. BLOND37 macrumors 6502a
Joined:
Mar 1, 2008
#1
when itunes does a backup during the update process, is it BEFORE or AFTER the update is applied?
will it get me back to 5.0?
2. r2shyyou macrumors 68000
r2shyyou
Joined:
Oct 3, 2010
Location:
Paris, France
#2
I haven't plugged my iPhone in my computer in a while but, if memory serves me right, I believe the backup is before the update is applied.
Are you asking if restoring from a backup prior to updating will get you back to a previous iOS version? I believe the answer to this is no. My understanding is that backing up doesn't back up the actual iOS but rather your content and settings.
3. Stoo macrumors newbie
Joined:
Jul 21, 2011
#3
I'd think that the update procedure would take a back up BEFORE doing the iOS update... If the update caused a problem with your data then you'd have a stuffed backup surely.
However doing a backup doesn't back up iOS, the backup is only of your data.
To restore iOS back to another version you should hold down ALT and click Check for Update and select the file that is the older version of the OS. Then you can restore your data to the phone.
Share This Page | __label__pos | 0.961258 |
import os import os.cmdline import net fn main() { println('Usage: net_udp_server_and_client [-l] [-p 5000]') println(' -l - act as a server and listen') println(' -p XXXX - custom port number') println('------------------------------------------') is_server := '-l' in os.args port := cmdline.option(os.args, '-p', '40001').int() mut buf := []u8{len: 100} if is_server { println('UDP echo server, listening for udp packets on port: ${port}') mut c := net.listen_udp(':${port}')! for { read, addr := c.read(mut buf) or { continue } println('received ${read} bytes from ${addr}') c.write_to(addr, buf[..read]) or { println('Server: connection dropped') continue } } } else { println('UDP client, sending packets to port: ${port}.\nType `exit` to exit.') mut c := net.dial_udp('localhost:${port}')! for { mut line := os.input('client > ') match line { '' { line = '\n' } 'exit' { println('goodbye.') exit(0) } else {} } c.write_string(line)! read, _ := c.read(mut buf)! println('server : ' + buf[0..read].bytestr()) } } } | __label__pos | 0.999641 |
MATLAB Programming/Strings
From Wikibooks, open books for an open world
Jump to navigation Jump to search
Declaring Strings[edit]
Strings are declared using single quotes:
>> fstring = 'hello'
fstring =
hello
Including a single quote in a string is done this way:
>> fstring = ''''
fstring =
'
>> fstring = 'you''re'
fstring =
you're
Strings as a Character Array[edit]
Strings in MATLAB are an array of characters. To see this, executing the following code:
>> fstring = 'hello';
>> class(fstring)
ans = char
Because strings are arrays, many array manipulation functions work including: size, transpose, and so on. Strings may be indexed to access specific elements.
Performing arithmetic operations on character arrays converts them into doubles.
>> fstring2 = 'world';
>> fstring + fstring2
ans = 223 212 222 216 211
These numbers are from the ASCII standard for each character in the array. These values are obtained using the double function to turn the array into an array of doubles.
>> double(fstring)
ans = 104 101 108 108 111
The 'char' function can turn an array of integer-valued doubles back into characters. Attempting to turn a decimal into a character causes MATLAB to round down:
>> char(104)
ans = h
>> char(104.6)
ans = h
Special String Functions[edit]
Since MATLAB strings are character arrays, some special functions are available for comparing entire strings rather than just its components:
deblank[edit]
deblank removes white spaces from the string.
findstr[edit]
findstr(bigstring, smallstring) looks to see if a small string is contained in a bigger string, and if it is returns the index of where the smaller string starts. Otherwise it returns [].
strrep[edit]
strrep(string1, replaced, replacement) replaces all instances of replaced in string1 with replacement
strcmp[edit]
Strings, unlike rational arrays, do not compare correctly with the relational operator. To compare strings use the strcmp function as follows:
>> string1 = 'a';
>> strcmp(string1, 'a')
ans = 1
>> strcmp(string1, 'A')
ans = 0
Note that MATLAB strings are case sensitive so that 'a' and 'A' are not the same. In addition the strcmp function does not discard whitespace:
>> strcmp(string1, ' a')
ans = 0
The strings must be exactly the same in every respect.
If the inputs are numeric arrays then the strcmp function will return 0 even if the values are the same. Thus it's only useful for strings. Use the == operator for numeric values.
>> strcmp(1,1)
ans = 0.
Displaying values of string variables[edit]
If all you want to do is display the value of a string, you can omit the semicolon as is standard in MATLAB.
If you want to display a string in the command window in combination with other text, one way is to use array notation combined with either the 'display' or the 'disp' function:
>> fstring = 'hello';
>> display( [ fstring 'world'] )
helloworld
MATLAB doesn't put the space in between the two strings. If you want one there you must put it in yourself.
This syntax is also used to concatenate two or more strings into one variable, which allows insertion of unusual characters into strings:
>> fstring = ['you' char(39) 're']
fstring = you're
Any other function that returns a string can also be used in the array.
You can also use the "strcat" function to concatenate strings, which does the same thing as above when you use two strings, but it is especially useful if you are using a cell array of strings because it lets you concatenate the same thing to all of the strings at once. Unfortunately you can't use it to add white space (strcat discards what MATLAB considers extraneous whitespace). Here's the syntax for this use.
>> strCell = {'A', 'B'};
>> strcat(strCell, '_');
ans =
A_
B_
Finally, although MATLAB doesn't have a printf function you can do essentially the same thing by using 1 as your file identifier in the fprintf function. The format identifiers are essentially the same as they are in C.
>> X = 9.2
>> fprintf(1, '%1.3f\n', X);
9.200
The "9.200" is printed to the screen. fprintf is nice compared to display because you don't have to call num2str on all of the numbers in a string - just use the appropriate format identifer in the place you want it.
>> X = 9.2
>> fprintf(1, 'The value of X is %1.3f meters per second \n', X);
The value of X is 9.200 meters per second
Cell arrays of strings[edit]
In many applications (particularly those where you are parsing text files, reading excel sheets with text, etc.) you will encounter cell arrays of strings.
You can use the function "iscellstr" to tell if all of the elements in a given cell array are strings or not.
>> notStrCell = {'AA', []};
>> iscellstr(notStrCell)
ans = 0
This is useful since functions that work with cell arrays of strings will fail if provided with something that's not a cell array of strings. In particular, they all fail if any elements of the provided cell array are the empty array ( [] ) which is somewhat frustrating if the provided text file contains empty cells. You must catch this exception before calling cellstr manipulation functions.
Searching a cell array of strings can be done with the "strmatch", "strfind", and "regexp" functions. Strmatch looks for a string within a cell array of strings whose first characters exactly match the string you pass to it, and returns the index of all strings in the array for which it found a match. If you give it the 'exact' option, it will only return the indexes of elements that are exactly the same as what you passed. For example:
>> strCell = {'Aa', 'AA'};
>> strmatch('A', strCell);
ans = 1, 2
>> strmatch('A', strCell, 'exact');
ans = []
>> strmatch('Aa', strCell, 'exact');
ans = 1
Strfind looks for a specific string within a cell array of strings, but it tries to find it in any part of each string. For each element x of the given cell array of strings, it will return an empty array if there is no match found in x and the starting index (remember, strings are arrays of characters) of all matches in x if a match to the query is found.
>> strCell = {'Aa', 'AA'};
>> strfind(strCell, 'A');
ans = % answer is a cell array with two elements (same size as strCell):
1 % Index of the beginning of string "A" in the first cell
1 2 % Index of each instance of the beginning of string "A" in the second cell
>> strfind(strCell, 'a');
ans =
2
[] % 'a' is not found
The "cellfun" / "isempty" combination is very useful for identifying cases where the string was or was not found. You can use the find function in combination with these two functions to return the index of all the cells in which the query string was found.
>> strCell = {'Aa', 'AA'};
>> idxCell = strfind(strCell, 'a');
>> isFound = ~cellfun('isempty', idxCell); % Returns "0" if idxCell is empty and a "1" otherwise
>> foundIdx = find(isFound)
foundIdx = 2
The strfind function also has some other options, such as the option to only return the index of the first or last match. See the documentation for details.
The regexp function works the same way as strfind but instead of looking for strings literally, it tries to find matches within the cell array of strings using regular expressions. Regular expressions are a powerful way to match patterns within strings (not just specific strings within strings). Entire books have been written about regular expressions, so they cannot be covered in as much detail here. However, some good resources online include regular-expresions.info and the MATLAB documentation for the matlab-specific syntax. Note that MATLAB implements some, but not all, of the extended regular expressions available in other languages such as Perl.
Unfortunately, MATLAB does not innately have functions to do common string operations in some other languages such as string splitting. However, it is quite possible to find many of these functions in a google search. | __label__pos | 0.768233 |
Proofview Marshalling
A bare-bones, self-contained example of running a query and returning proofview XML. NOTE: Query justification is not supported in OpenCyc.
package com.cyc.core.examples.advanced;
/*
* #%L
* File: ProofViewMarshallerExample.java
* Project: Cyc Core API Use Cases
* %%
* Copyright (C) 2013 - 2015 Cycorp, Inc.
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import com.cyc.kb.Sentence;
import com.cyc.kb.exception.CreateException;
import com.cyc.kb.exception.KbTypeException;
import com.cyc.query.ProofViewGenerator;
import com.cyc.query.ProofViewSpecification;
import com.cyc.query.Query;
import com.cyc.query.QueryAnswer;
import com.cyc.query.exception.ProofViewException;
import com.cyc.query.exception.QueryConstructionException;
import com.cyc.session.SessionManager;
import com.cyc.session.exception.SessionCommunicationException;
import java.io.IOException;
import java.io.OutputStream;
import static com.cyc.Cyc.Constants.INFERENCE_PSC;
/**
* A bare-bones, self-contained example of running a query and returning proofview XML.
*
* @author nwinant
*/
public class ProofViewMarshallerExample {
public static void main(String args[]) {
final String exampleName = ProofViewMarshallerExample.class.getSimpleName();
try (SessionManager sessionMgr = SessionManager.getInstance()) {
System.out.println("Running " + exampleName + "...");
ProofViewMarshallerExample example = new ProofViewMarshallerExample();
example.runExample();
} catch (Exception ex) {
ex.printStackTrace(System.err);
System.exit(1);
} finally {
System.out.println("... " + exampleName + " concluded.");
System.exit(0);
}
}
/**
* Create and run a query, keeping the inference around for just long enough afterward that we can
* generate and marshal a proofview to XML. In this example we're just proving a fully-bound
* sentence (note that we can construct a query directly from a Sentence object).
* <p>
* Incidentally, this is a useful technique to create proofviews for old answers (even for
* inferences that were run days or weeks ago): for a given answer, substitute the bindings back
* into the original query that generated it, and then run a new query from the fully-bound query
* sentence. Cyc only needs to prove a single answer, and it can often do so in much less time
* than it originally took to find the answer. Just be aware that it may not be the <em>same</em>
* proof that Cyc arrived at the first time.
* <p>
* Note that we're creating the query in a try-with-resources block: it's important to close the
* inference, otherwise its problem store won't be destroyed and you'll have a memory leak.
*
* @throws KbTypeException
* @throws CreateException
*/
public void runExample() throws KbTypeException, CreateException {
try (Query query = Sentence.get("(genls Emu Bird)").toQuery(INFERENCE_PSC)) {
// Make sure to keep the inference around after it has concluded. Because we're doing this,
// we need to make sure that we clean up after it, which we've done here with a
// try-with-resources block. It's important to close the inference, otherwise its problem
// store won't be destroyed and we'll have a memory leak in Cyc.
query.retainInference();
// Get a proof view generator for the first (and in this case, only) answer.
final ProofViewGenerator proofGen
= ProofViewGenerator.get(query.getAnswer(0), ProofViewSpecification.get());
// Marshall the proof view to XML; we can use any OutputStream or Writer.
// This will cause the generator to create the proofview if it has not done so already.
proofGen.getMarshaller().marshal(OUT);
} catch (ProofViewException | QueryConstructionException | SessionCommunicationException ex) {
ex.printStackTrace(System.err);
}
}
private static final OutputStream OUT = new OutputStream() {
@Override
public void write(int b) throws IOException {
System.out.write(b);
}
};
} | __label__pos | 0.923078 |
Displaying Image in RTF-Textfield using Pybis
Dear all,
I am currently using Pybis to upload and analyze my data. I like to display for example an diagram from the analysis in a text field of the experiment automatically via the python script. I had some success using this code in a rtf:
obj.p[“result”] = str(‘’)
I got the (temporary) url for the image from the dataset: dataset.file_links.values()
This approach works until the (download/user) session is expired. A permanent (external) url works fine.
Is there another way to permanently display images from the dataset using Pybis?
I’ve had a similar problem and tried to solve it with a dataset. I created a dataset with the image and linked the result in a word processor multiline varchar. This works, but the picture is only displayed if you “load” the image by hovering over it in the dataset to see a preview.
Thus, I asked for support for a better solution. I received the following answer:
Thank you for your patience. The issue you mention is possible to achieve with Pybis, although with a little trick. What you need to do is:
1. Upload your image to a file service of the Openbis
2. Attach uploaded file to a property
I’m adding an example code on how to do it in python:
import requests
import json
# Assuming you have logged into openbis via pybis
exp = openbis_instance.get_experiment('/DEFAULT/DEFAULT/DEFAULT_EXP_1') # Experiment or sample you want to update
file = '/path/to/my/image.png'
#
url = '{url_to_openbis_instance}/openbis/openbis/file-service/eln-lims?type=Files&sessionID=' + openbis_instance.token
files = {'file': open(file, 'rb')}
r = requests.post(url, files=files, verify=False) # verify=False is required if you use self-signed certificates
if r.ok:
url = json.loads(r.text)['url'] # url is a special url to uploaded image
formatted = f'<?xml version="1.0" encoding="UTF-8"?>\n<html><head></head><body><p>\xa0</p><figure class="image"><img src="{url}" /></figure></body></html>' # you need to anchor your image in the html to be visible in the property
exp.props['$document'] = formatted # setting text with image to a example $document property
exp.save()
I hope this suits you as well! If you have any further questions, I can show you my code.
Dear Cedric,
thank you for the fast reply - your code worked perfectly.
Thank you, Mathias | __label__pos | 0.998564 |
A custom profile defines a specific configuration of an object instance. With profiles, you can determine how many instances of that object can fit in your environment, depending on the capacity remaining and the configuration of that object instance.
To determine how many instances of the object can fit in your environment, use custom profiles with projects and scenarios. Enter the profile numbers or pre-populate the values from specific VMs. Depending on the available capacity in your environment, you can add one or more instances of the object that the custom profile capacity requirements represent.
To determine how many instances of the custom profile object you can include on the parent object, you select the parent object and the Capacity tab. The custom profiles appear on the VM remaining section and indicate how many instances of the object fit in your environment. | __label__pos | 0.734358 |
Are Roulette Odds Always the Same?
Browse By
The first thing worth mentioning Roulette is that you will find both American and European versions of this classic table game. The main difference between them is that the American variant has two zero pockets instead of one (0 and 00). This means that the roulette table odds are lower in European games. Making the decision to play European versions one of our top casino rules.
The second factor to take into account is that the odds vary according to the bet that you choose. If you choose a single number. Then the chances of winning are 36 to 1 in European-style games. And 37 to 1 if you play an American version. The payout, in either case, is 35 to 1.UFABET
Yet, if you decide to put your stake on red or black, the odds of the right colour coming up are close to 50%. And the payout is on a 1:1 basis. It is the presence of the zero, or zeros in American games. That stops this being a straight 50% chance of coming up.
Therefore, you should consider, first of all, how adventurous you want to be. Do you want a bet that has the best chance of winning you a small amount. Or would you prefer to look for higher roulette odds on a type of wager that is less likely to come up?
To help you make your decision, we can now look at all the roulette payouts and how they are different on a variety of bets. | __label__pos | 0.875578 |
Possible security issue when choosing encrypted install of EOS
Hi,
when installing EndeavourOS from current live cd (Endeavouros_Cassini_Nova-03-2023_R1.iso) and using the encrypted install option in the installer, it creates an installation using only a LUKS v1 header for the encryption key and PBKDF2 for key derivation. Whereas as LUKS v2 header and argon2id should be used to match current cryptographic standards. When choosing to encrypt drives in GNOME Disks later on a LUKS2 header and argon2id is automatically used.
Source (GER): https://blog.fefe.de/?ts=9ac0aab7
(ENG) https://mjg59.dreamwidth.org/66429.html
Is this an issue to report directly to calamares or is this an issue that should be fixed within the distributions liveCD?
P.S.: I converted my LUKS header after installation on two different devices and it works without problems for me, but the mentioned settings should be the default settings instead of the outdated ones.
There already is an issue open at Calamares.
There just isn’t a lot we can do about. The problem is that grub does not support argon2id.
1 Like
Mhm, I see. I have a slightly adjusted setup where /boot is unencrypted and only / is encrypted. So GRUB loads just fine and I guess the kernel handles the decryption with argon2id then.
I hope someone will find the time and has the knowledge to write a patch for GRUB. | __label__pos | 0.656929 |
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. 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 have a custom field attatched to a post that contains the following array of post titles...
a:6:{i:0;s:21:"Strawberry Cheesecake";i:1;s:15:"Flapjack";i:2;s:14:"Chocolate Muffin";i:3;s:27:"Apple Turnover";i:4;s:13:"Chocolate Cookie";i:5;s:13:"Shortbread";}
I am then outputing those post titles, searching for the related permalink and echoing them out using....
<?php
$speakerarray = get_post_meta($post->ID, 'cpt_food', true);
$arrlength=count($foodarray);
for($x=0;$x<$arrlength;$x++)
{
$foodname = $foodarray[$x];
$posts = get_posts(array('name' => $foodname, 'post_type' => 'food'));
$post = $posts[0];
$permalink = get_permalink($post->ID);
echo '<a href="';
echo $permalink;
echo '">';
echo $foodname;
echo '</a>';
echo "<br>";
}
?>
Everything works fine apart from the last result, I have duplicated the issue with numerous items in the array etc.. and its always the last one that fails. It returns the permalink for the page I am currently on instead.
Can anyone see why?
share|improve this question
You should use a foreach loop instead, as the count index isn't the best way to walk over an array.
<?php
$speakerarray = get_post_meta($post->ID, 'cpt_food', true);
foreach($speakerarray as $foodname) :
$posts = get_posts(array('name' => $foodname, 'post_type' => 'food'));
$post = $posts[0];
echo '<a href="' . get_permalink( $post->ID ) . '>' . $foodname . '</a><br>';
endforeach;
?>
I used a online tool for unserialize your data and it returned an error ?
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.916755 |
come cambiare la password per l’account utente, con il codice c #?
come cambiare la password per l’account utente, con il codice c #?
Utilizzando la directory triggers:
// Connect to Active Directory and get the DirectoryEntry object. // Note, ADPath is an Active Directory path pointing to a user. You would have created this // path by calling a GetUser() function, which searches AD for the specified user // and returns its DirectoryEntry object or path. See http://www.primaryobjects.com/CMS/Article61.aspx DirectoryEntry oDE; oDE = new DirectoryEntry(ADPath, ADUser, ADPassword, AuthenticationTypes.Secure); try { // Change the password. oDE.Invoke("ChangePassword", new object[]{strOldPassword, strNewPassword}); } catch (Exception excep) { Debug.WriteLine("Error changing password. Reason: " + excep.Message); }
Qui hai un esempio per cambiarlo nell’account utente locale:
http://msdn.microsoft.com/en-us/library/ms817839
Altre alternative potrebbero utilizzare l’interoperabilità e chiamare il codice non gestito: netapi32.dll
http://msdn.microsoft.com/en-us/library/aa370650(VS.85).aspx
Ecco un modo più semplice per farlo, tuttavia è necessario fare riferimento a System.DirectoryServices.AccountManagement da .Net 4.0
namespace PasswordChanger { using System; using System.DirectoryServices.AccountManagement; class Program { static void Main(string[] args) { ChangePassword("domain", "user", "oldpassword", "newpassword"); } public static void ChangePassword(string domain, string userName, string oldPassword, string newPassword) { try { using (var context = new PrincipalContext(ContextType.Domain, domain)) using (var user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, userName)) { user.ChangePassword(oldPassword, newPassword); } } catch (Exception ex) { Console.WriteLine(ex); } } } }
DirectoryEntry AD = new DirectoryEntry("WinNT://" + Environment.MachineName + ",computer"); DirectoryEntry grp; grp = AD.Children.Find("test", "user"); if (grp != null) { grp.Invoke("SetPassword", new object[] { "test" }); } grp.CommitChanges(); MessageBox.Show("Account Change password Successfully");
“esegui l’amministratore per cambiare tutti gli utenti
Funziona sia per gli account AD che per quelli locali.
Se si desidera richiamare questa API tramite C #, è ansible utilizzare questa firma per importare API NetUserChangePassword sul codice C #:
[DllImport("netapi32.dll", CharSet=CharSet.Unicode, CallingConvention=CallingConvention.StdCall,SetLastError=true )] static extern uint NetUserChangePassword ( [MarshalAs(UnmanagedType.LPWStr)] string domainname, [MarshalAs(UnmanagedType.LPWStr)] string username, [MarshalAs(UnmanagedType.LPWStr)] string oldpassword, [MarshalAs(UnmanagedType.LPWStr)] string newpassword); | __label__pos | 0.975686 |
3D Sound distortion and UpdateWorld()
Archives Forums/Blitz3D Bug Reports/3D Sound distortion and UpdateWorld()
lo-tekk(Posted 2006) [#1]
I've learned today about syncing animations with UpdateWorld(delta#). The animations runs well now, but certain 3D Sounds go wild. A shoot sound loaded as 3D gets distorted, whereas all the other 3D sounds seem fine. Changing the sound produces the same result. Only loading as a regular sound would play it as usual or removing the delta parameter in UpdateWorld(). Anyone else encountered this ? I guess it's difficuilt to reproduce since this sound is loaded within a bunch of others that behaves okay.
Thank you
Michael
---------------------------------------------------------
[Edit]
Doesn't matter anymore. Animating manually. | __label__pos | 0.72522 |
SciPy
scipy.stats.boltzmann
scipy.stats.boltzmann = <scipy.stats._discrete_distns.boltzmann_gen object at 0x2b2318ef6cd0>[source]
A Boltzmann (Truncated Discrete Exponential) random variable.
As an instance of the rv_discrete class, boltzmann object inherits from it a collection of generic methods (see below for the full list), and completes them with details specific for this particular distribution.
Notes
The probability mass function for boltzmann is:
boltzmann.pmf(k) = (1-exp(-lambda_)*exp(-lambda_*k)/(1-exp(-lambda_*N))
for k = 0,..., N-1.
boltzmann takes lambda_ and N as shape parameters.
The probability mass function above is defined in the “standardized” form. To shift distribution use the loc parameter. Specifically, boltzmann.pmf(k, lambda_, N, loc) is identically equivalent to boltzmann.pmf(k - loc, lambda_, N).
Examples
>>> from scipy.stats import boltzmann
>>> import matplotlib.pyplot as plt
>>> fig, ax = plt.subplots(1, 1)
Calculate a few first moments:
>>> lambda_, N = 1.4, 19
>>> mean, var, skew, kurt = boltzmann.stats(lambda_, N, moments='mvsk')
Display the probability mass function (pmf):
>>> x = np.arange(boltzmann.ppf(0.01, lambda_, N),
... boltzmann.ppf(0.99, lambda_, N))
>>> ax.plot(x, boltzmann.pmf(x, lambda_, N), 'bo', ms=8, label='boltzmann pmf')
>>> ax.vlines(x, 0, boltzmann.pmf(x, lambda_, N), colors='b', lw=5, alpha=0.5)
Alternatively, the distribution object can be called (as a function) to fix the shape and location. This returns a “frozen” RV object holding the given parameters fixed.
Freeze the distribution and display the frozen pmf:
>>> rv = boltzmann(lambda_, N)
>>> ax.vlines(x, 0, rv.pmf(x), colors='k', linestyles='-', lw=1,
... label='frozen pmf')
>>> ax.legend(loc='best', frameon=False)
>>> plt.show()
(Source code)
../_images/scipy-stats-boltzmann-1_00_00.png
Check accuracy of cdf and ppf:
>>> prob = boltzmann.cdf(x, lambda_, N)
>>> np.allclose(x, boltzmann.ppf(prob, lambda_, N))
True
Generate random numbers:
>>> r = boltzmann.rvs(lambda_, N, size=1000)
Methods
rvs(lambda_, N, loc=0, size=1, random_state=None) Random variates.
pmf(k, lambda_, N, loc=0) Probability mass function.
logpmf(k, lambda_, N, loc=0) Log of the probability mass function.
cdf(k, lambda_, N, loc=0) Cumulative distribution function.
logcdf(k, lambda_, N, loc=0) Log of the cumulative distribution function.
sf(k, lambda_, N, loc=0) Survival function (also defined as 1 - cdf, but sf is sometimes more accurate).
logsf(k, lambda_, N, loc=0) Log of the survival function.
ppf(q, lambda_, N, loc=0) Percent point function (inverse of cdf — percentiles).
isf(q, lambda_, N, loc=0) Inverse survival function (inverse of sf).
stats(lambda_, N, loc=0, moments='mv') Mean(‘m’), variance(‘v’), skew(‘s’), and/or kurtosis(‘k’).
entropy(lambda_, N, loc=0) (Differential) entropy of the RV.
expect(func, args=(lambda_, N), loc=0, lb=None, ub=None, conditional=False) Expected value of a function (of one argument) with respect to the distribution.
median(lambda_, N, loc=0) Median of the distribution.
mean(lambda_, N, loc=0) Mean of the distribution.
var(lambda_, N, loc=0) Variance of the distribution.
std(lambda_, N, loc=0) Standard deviation of the distribution.
interval(alpha, lambda_, N, loc=0) Endpoints of the range that contains alpha percent of the distribution
Previous topic
scipy.stats.binom
Next topic
scipy.stats.dlaplace | __label__pos | 0.830633 |
%'phys': transforms image (px) to real world (phys) coordinates using geometric calibration parameters % DataOut=phys(Data,CalibData) , transform one input field % [DataOut,DataOut_1]=phys(Data,CalibData,Data_1,CalibData_1), transform two input fields % OUTPUT: % DataOut: structure representing the first field in phys coordinates % DataOut_1: structure representing the second field in phys coordinates %INPUT: % Data: structure of input data % with fields .A (image or scalar matrix), AX, AY % .X,.Y,.U,.V, .DjUi % .ZIndex: index of plane in multilevel case % .CoordType='phys' or 'px', The function ACTS ONLY IF .CoordType='px' % CalibData: structure containing calibration parameters or a subtree Calib.GeometryCalib =calibration data (tsai parameters) % Data_1, CalibData_1: same as Data, CalibData for the second field. function DataOut=phys(DataIn,XmlData,DataIn_1,XmlData_1) % A FAIRE: 1- verifier si DataIn est une 'field structure'(.ListVarName'): % chercher ListVarAttribute, for each field (cell of variables): % .CoordType: 'phys' or 'px' (default==phys, no transform) % .scale_factor: =dt (to transform displacement into velocity) default=1 % .covariance: 'scalar', 'coord', 'D_i': covariant (like velocity), 'D^i': contravariant (like gradient), 'D^jD_i' (like strain tensor) % (default='coord' if .Role='coord_x,_y..., % 'D_i' if '.Role='vector_x,...', % 'scalar', else (thenno change except scale factor) %% set GUI config DataOut=[]; DataOut_1=[]; %default second output field if strcmp(DataIn,'*') if isfield(XmlData,'GeometryCalib')&& isfield(XmlData.GeometryCalib,'CoordUnit') DataOut.CoordUnit=XmlData.GeometryCalib.CoordUnit; end return end %% analyse input and set default output DataOut=DataIn;%default first output field if nargin>=2 % nargin =nbre of input variables if isfield(XmlData,'GeometryCalib') Calib{1}=XmlData.GeometryCalib; else Calib{1}=[]; end if nargin>=3 %two input fields DataOut_1=DataIn_1;%default second output field if nargin>=4 && isfield(XmlData_1,'GeometryCalib') Calib{2}=XmlData_1.GeometryCalib; else Calib{2}=Calib{1}; end end end %% get the z index defining the section plane if isfield(DataIn,'ZIndex')&&~isempty(DataIn.ZIndex)&&~isnan(DataIn.ZIndex) ZIndex=DataIn.ZIndex; else ZIndex=1; end %% transform first field iscalar=0;% counter of scalar fields if ~isempty(Calib{1}) if ~isfield(Calib{1},'CalibrationType')||~isfield(Calib{1},'CoordUnit') return %bad calib parameter input end if ~(isfield(DataIn,'CoordUnit')&& strcmp(DataIn.CoordUnit,'pixel')) return % transform only fields in pixel coordinates end DataOut=phys_1(DataIn,Calib{1},ZIndex);% transform coordiantes and velocity components %case of images or scalar: in case of two input fields, we need to project the transform on the same regular grid if isfield(DataIn,'A') && isfield(DataIn,'AX') && ~isempty(DataIn.AX) && isfield(DataIn,'AY')&&... ~isempty(DataIn.AY) && length(DataIn.A)>1 iscalar=1; A{1}=DataIn.A; end end %% document the selected plane position and angle if relevant if isfield(Calib{1},'SliceCoord')&&size(Calib{1}.SliceCoord,1)>=ZIndex DataOut.PlaneCoord=Calib{1}.SliceCoord(ZIndex,:);% transfer the slice position corresponding to index ZIndex if isfield(Calib{1},'SliceAngle') % transfer the slice rotation angles if isequal(size(Calib{1}.SliceAngle,1),1)% case of a unique angle DataOut.PlaneAngle=Calib{1}.SliceAngle; else % case of multiple planes with different angles: select the plane with index ZIndex DataOut.PlaneAngle=Calib{1}.SliceAngle(ZIndex,:); end end end %% transform second field if relevant if ~isempty(DataOut_1) if isfield(DataIn_1,'ZIndex') && ~isequal(DataIn_1.ZIndex,ZIndex) DataOut_1.Txt='different plane indices for the two input fields'; return end if ~isfield(Calib{2},'CalibrationType')||~isfield(Calib{2},'CoordUnit') return %bad calib parameter input end if ~(isfield(DataIn_1,'CoordUnit')&& strcmp(DataIn_1.CoordUnit,'pixel')) return % transform only fields in pixel coordinates end DataOut_1=phys_1(DataOut_1,Calib{2},ZIndex); if isfield(Calib{1},'SliceCoord') if ~(isfield(Calib{2},'SliceCoord') && isequal(Calib{2}.SliceCoord,Calib{1}.SliceCoord)) DataOut_1.Txt='different plane positions for the two input fields'; return end DataOut_1.PlaneCoord=DataOut.PlaneCoord;% same plane position for the two input fields if isfield(Calib{1},'SliceAngle') if ~(isfield(Calib{2},'SliceAngle') && isequal(Calib{2}.SliceAngle,Calib{1}.SliceAngle)) DataOut_1.Txt='different plane angles for the two input fields'; return end DataOut_1.PlaneAngle=DataOut.PlaneAngle; % same plane angle for the two input fields end end if isfield(DataIn_1,'A')&&isfield(DataIn_1,'AX')&&~isempty(DataIn_1.AX) && isfield(DataIn_1,'AY')&&... ~isempty(DataIn_1.AY)&&length(DataIn_1.A)>1 iscalar=iscalar+1; Calib{iscalar}=Calib{2}; A{iscalar}=DataIn_1.A; end end %% transform the scalar(s) or image(s) if iscalar~=0 [A,AX,AY]=phys_Ima(A,Calib,ZIndex);%TODO : introduire interp2_uvmat ds phys_ima if iscalar==1 && ~isempty(DataOut_1) % case for which only the second field is a scalar DataOut_1.A=A{1}; DataOut_1.AX=AX; DataOut_1.AY=AY; else DataOut.A=A{1}; DataOut.AX=AX; DataOut.AY=AY; end if iscalar==2 DataOut_1.A=A{2}; DataOut_1.AX=AX; DataOut_1.AY=AY; end end % subtract fields if ~isempty(DataOut_1) DataOut=sub_field(DataOut,[],DataOut_1); end %------------------------------------------------ %--- transform a single field function DataOut=phys_1(Data,Calib,ZIndex) %------------------------------------------------ %% set default output DataOut=Data;%default DataOut.CoordUnit=Calib.CoordUnit;% the output coord unit is set by the calibration parameters %% transform X,Y coordinates for velocity fields (transform of an image or scalar done in phys_ima) if isfield(Data,'X') &&isfield(Data,'Y')&&~isempty(Data.X) && ~isempty(Data.Y) [DataOut.X,DataOut.Y]=phys_XYZ(Calib,Data.X,Data.Y,ZIndex); Dt=1; %default if isfield(Data,'dt')&&~isempty(Data.dt) Dt=Data.dt; end if isfield(Data,'Dt')&&~isempty(Data.Dt) Dt=Data.Dt; end if isfield(Data,'U')&&isfield(Data,'V')&&~isempty(Data.U) && ~isempty(Data.V) [XOut_1,YOut_1]=phys_XYZ(Calib,Data.X-Data.U/2,Data.Y-Data.V/2,ZIndex); [XOut_2,YOut_2]=phys_XYZ(Calib,Data.X+Data.U/2,Data.Y+Data.V/2,ZIndex); DataOut.U=(XOut_2-XOut_1)/Dt; DataOut.V=(YOut_2-YOut_1)/Dt; end % if ~strcmp(Calib.CalibrationType,'rescale') && isfield(Data,'X_tps') && isfield(Data,'Y_tps') % [DataOut.X_tps,DataOut.Y_tps]=phys_XYZ(Calib,Data.X,Data.Y,ZIndex); % end end %% suppress tps list_tps={'Coord_tps' 'U_tps' 'V_tps' 'SubRange' 'NbSites'}; ind_remove=[]; for ilist=1:numel(list_tps) ind_tps=find(strcmp(list_tps{ilist},Data.ListVarName)); if ~isempty(ind_tps) ind_remove=[ind_remove ind_tps]; DataOut=rmfield(DataOut,list_tps{ilist}); end end if isfield(DataOut,'VarAttribute')&&isfield(DataOut.VarAttribute{3},'VarIndex_tps') DataOut.VarAttribute{3}=rmfield(DataOut.VarAttribute{3},'VarIndex_tps'); end if ~isempty(ind_remove) DataOut.ListVarName(ind_remove)=[]; DataOut.VarDimName(ind_remove)=[]; DataOut.VarAttribute(ind_remove)=[]; end %% transform of spatial derivatives: TODO check the case with plane angles if isfield(Data,'X') && ~isempty(Data.X) && isfield(Data,'DjUi') && ~isempty(Data.DjUi) % estimate the Jacobian matrix DXpx/DXphys for ip=1:length(Data.X) [Xp1,Yp1]=phys_XYZ(Calib,Data.X(ip)+0.5,Data.Y(ip),ZIndex); [Xm1,Ym1]=phys_XYZ(Calib,Data.X(ip)-0.5,Data.Y(ip),ZIndex); [Xp2,Yp2]=phys_XYZ(Calib,Data.X(ip),Data.Y(ip)+0.5,ZIndex); [Xm2,Ym2]=phys_XYZ(Calib,Data.X(ip),Data.Y(ip)-0.5,ZIndex); %Jacobian matrix DXpphys/DXpx DjXi(1,1)=(Xp1-Xm1); DjXi(2,1)=(Yp1-Ym1); DjXi(1,2)=(Xp2-Xm2); DjXi(2,2)=(Yp2-Ym2); DjUi(:,:)=Data.DjUi(ip,:,:); DjUi=(DjXi*DjUi')/DjXi;% =J-1*M*J , curvature effects (derivatives of J) neglected DataOut.DjUi(ip,:,:)=DjUi'; end DataOut.DjUi = DataOut.DjUi/Dt; % min(Data.DjUi(:,1,1))=DUDX end %%%%%%%%%%%%%%%%%%%% function [A_out,Rangx,Rangy]=phys_Ima(A,CalibIn,ZIndex) xcorner=[]; ycorner=[]; npx=[]; npy=[]; dx=ones(1,length(A)); dy=ones(1,length(A)); for icell=1:length(A) siz=size(A{icell}); npx=[npx siz(2)]; npy=[npy siz(1)]; Calib=CalibIn{icell}; xima=[0.5 siz(2)-0.5 0.5 siz(2)-0.5];%image coordinates of corners yima=[0.5 0.5 siz(1)-0.5 siz(1)-0.5]; [xcorner_new,ycorner_new]=phys_XYZ(Calib,xima,yima,ZIndex);%corresponding physical coordinates dx(icell)=(max(xcorner_new)-min(xcorner_new))/(siz(2)-1); dy(icell)=(max(ycorner_new)-min(ycorner_new))/(siz(1)-1); xcorner=[xcorner xcorner_new]; ycorner=[ycorner ycorner_new]; end Rangx(1)=min(xcorner); Rangx(2)=max(xcorner); Rangy(2)=min(ycorner); Rangy(1)=max(ycorner); test_multi=(max(npx)~=min(npx)) || (max(npy)~=min(npy)); %different image lengths npX=1+round((Rangx(2)-Rangx(1))/min(dx));% nbre of pixels in the new image (use the finest resolution min(dx) in the set of images) npY=1+round((Rangy(1)-Rangy(2))/min(dy)); x=linspace(Rangx(1),Rangx(2),npX); y=linspace(Rangy(1),Rangy(2),npY); [X,Y]=meshgrid(x,y);%grid in physical coordiantes vec_B=[]; A_out={}; for icell=1:length(A) Calib=CalibIn{icell}; % rescaling of the image coordinates without change of the image array if strcmp(Calib.CalibrationType,'rescale') && isequal(Calib,CalibIn{1}) A_out{icell}=A{icell};%no transform Rangx=[0.5 npx-0.5];%image coordiantes of corners Rangy=[npy-0.5 0.5]; [Rangx]=phys_XYZ(Calib,Rangx,[0.5 0.5],ZIndex);%case of translations without rotation and quadratic deformation [xx,Rangy]=phys_XYZ(Calib,[0.5 0.5],Rangy,ZIndex); else % the image needs to be interpolated to the new coordinates zphys=0; %default if isfield(Calib,'SliceCoord') %.Z= index of plane SliceCoord=Calib.SliceCoord(ZIndex,:); zphys=SliceCoord(3); %to generalize for non-parallel planes if isfield(Calib,'InterfaceCoord') && isfield(Calib,'RefractionIndex') H=Calib.InterfaceCoord(3); if H>zphys zphys=H-(H-zphys)/Calib.RefractionIndex; %corrected z (virtual object) end end end [XIMA,YIMA]=px_XYZ(CalibIn{icell},X,Y,zphys);% image coordinates for each point in the real space grid XIMA=reshape(round(XIMA),1,npX*npY);%indices reorganized in 'line' YIMA=reshape(round(YIMA),1,npX*npY); flagin=XIMA>=1 & XIMA<=npx(icell) & YIMA >=1 & YIMA<=npy(icell);%flagin=1 inside the original image testuint8=isa(A{icell},'uint8'); testuint16=isa(A{icell},'uint16'); if numel(siz)==2 %(B/W images) vec_A=reshape(A{icell},1,npx(icell)*npy(icell));%put the original image in line %ind_in=find(flagin); ind_out=find(~flagin); ICOMB=((XIMA-1)*npy(icell)+(npy(icell)+1-YIMA)); ICOMB=ICOMB(flagin);%index corresponding to XIMA and YIMA in the aligned original image vec_A %vec_B(ind_in)=vec_A(ICOMB); vec_B(flagin)=vec_A(ICOMB); vec_B(~flagin)=zeros(size(ind_out)); % vec_B(ind_out)=zeros(size(ind_out)); A_out{icell}=reshape(vec_B,npY,npX);%new image in real coordinates elseif numel(siz)==3 for icolor=1:siz(3) vec_A=reshape(A{icell}(:,:,icolor),1,npx*npy);%put the original image in line % ind_in=find(flagin); ind_out=find(~flagin); ICOMB=((XIMA-1)*npy+(npy+1-YIMA)); ICOMB=ICOMB(flagin);%index corresponding to XIMA and YIMA in the aligned original image vec_A vec_B(flagin)=vec_A(ICOMB); vec_B(~flagin)=zeros(size(ind_out)); A_out{icell}(:,:,icolor)=reshape(vec_B,npy,npx);%new image in real coordinates end end if testuint8 A_out{icell}=uint8(A_out{icell}); end if testuint16 A_out{icell}=uint16(A_out{icell}); end end end | __label__pos | 0.982644 |
Difference between revisions of "YaCy"
From Free Software Directory
Jump to: navigation, search
(Created page with "{{Entry |Name=YaCy |Short description= YaCy is a distributed search engine |Full description= YaCy peers crawl the internet and share the results. This decentralized network d...")
(Updated version)
(One intermediate revision by one other user not shown)
Line 1: Line 1:
{{Entry
{{Entry
|Name=YaCy
|Name=YaCy
|Short description= YaCy is a distributed search engine
+
|Short description=YaCy is a distributed search engine
|Full description= YaCy peers crawl the internet and share the results. This decentralized network does not store search queries and makes censorship impossible.
+
|Full description=YaCy peers crawl the internet and share the results. This decentralized network does not store search queries and makes censorship impossible.
|User level= intermediate
+
|Homepage URL=http://yacy.net
|Extension of=
+
|User level=intermediate
|Component programs=
+
|Computer languages=Java
|Homepage URL=
+
|Documentation note=http://www.yacy-websuche.de/wiki/index.php/En:Start
|VCS checkout command=
+
|Keywords=search, internet, peer-to-peer, p2p
|Computer languages= Java
+
|Version identifier=1.64
|Documentation note=http://www.yacy-websuche.de/wiki/index.php/En:Start
+
|Version date=2013/10/26
|Paid Support=
+
|Version status=stable
|Microblog=
+
|Version download=http://yacy.net/release/yacy_v1.64_20131026_9201.tar.gz
|IRC help=
+
|Submitted by=mviinama
|IRC general=
+
|Submitted date=2013-03-31
|IRC development=
+
|Status=
|Related projects=
+
|Is GNU=No
|Software categories=
+
|Paid Support=
|Keywords= search, internet, peer-to-peer, p2p
+
|Software categories=
|Is GNU= no
|GNU package identifier=
|Version identifier= 1.4
|Version date= 2013-03-15
|Version status=
|Version download= http://yacy.net/release/yacy_v1.4_20130315_9000.tar.gz
|Version comment=
|Status
|Last review by=
|Last review date=
|Submitted by= mviinama
|Submitted date= 2013-03-31
}}
}}
+
{{Project license
+
|License=GPLv2orlater
+
|License verified by=Jgay
+
|License verified date=2013/04/19
+
}}
+
{{Software category
+
|Programming-language=java
+
|Use=internet-application
+
}}
+
{{Software prerequisite
+
|Prerequisite kind=Required to use
+
|Prerequisite description=OpenJDK
+
}}
+
{{Featured}}
Revision as of 17:39, 22 November 2013
[edit]
YaCy
http://yacy.net
YaCy is a distributed search engine
YaCy (Yet another Cyberspace) peers crawl the internet and share the results. This decentralized network does not store search queries and makes censorship impossible.
Documentation
http://www.yacy-websuche.de/wiki/index.php/En:Start
Download
v1.64 20131026 9201.tar.gz Download version 1.64 (stable)
released on 26 October 2013
Categories
Licensing
LicenseVerified byVerified onNotes
GPLv2orlaterJgay19 April 2013
Leaders and contributors
Resources and communication
AudienceResource typeURI
DeveloperBug Trackinghttp://bugs.yacy.net
DeveloperVCS Repository Webviewhttps://gitorious.org/yacy
Software prerequisites
KindDescription
Required to useOpenJDK
Entry
Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or any later version published by the Free Software Foundation; with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts. A copy of the license is included in the page “GNU Free Documentation License”.
The copyright and license notices on this page only apply to the text on this page. Any software or copyright-licenses or other similar notices described in this text has its own copyright notice and license, which can usually be found in the distribution or license text itself. | __label__pos | 0.707987 |
How to: View or Change the Properties of a Database (SQL Server Management Studio)
This topic describes how to view a database by using Object Explorer in SQL Server Management Studio.
To view a database
1. In Object Explorer, connect to an instance of the SQL Server Database Engine, and then expand that instance.
2. Expand Databases, right-click the database to view, and then click Properties.
3. In the Database Properties dialog box, select a page to view the corresponding information. For example, select the Files page to view data and log file information.
For a description of each option, see Setting Database Options.
Community Additions
ADD
Show: | __label__pos | 0.990218 |
Reusable VS Non Reusable & Properties of Sequence Generator Transformation
We will see the difference of reusable and non reusable sequence generator transformation along with the properties of the transformation.
Sequence Generator Transformation Properties:
You have to configure the following properties of a sequence generator transformation:
Start Value:
Specify the Start Value when you configure the sequence generator transformation for Cycle option. If you configure the cycle, the integration service cycles back to this value when it reaches the End Value. Use Cycle to generate a repeating sequence numbers, such as numbers 1 through 12 to correspond to the months in a year. To cycle the integration service through a sequence:
• Enter the lowest value in the sequence to use for the Start Value.
• Enter the highest value to be used for End Value.
• Select Cycle option.
Increment By:
The Integration service generates sequence numbers based on the Current Value and the Increment By properties in the sequence generator transformation. Increment By is the integer the integration service adds to the existing value to create the new value in the sequence. The default value of Increment By is 1.
End Value:
End value is the maximum value that the integration service generates. If the integration service reaches the end value and the sequence generator is not configured for cycle option, then the session fails with the following error message:
TT_11009 Sequence Generator Transformation: Overflow error.
If the sequence generator is configured for cycle option, then the integration service cycles back to the start value and starts generating numbers from there.
Current Value:
The integration service uses the Current Value as the basis for generated values for each session. Specify the value in "Current Value" you want the integration service as a starting value to generate sequence numbers. If you want to cycle through a sequence of numbers, then the current value must be greater than or equal to the Start Value and less than the End Value.
At the end of the session, the integration service updates the current value to the last generated sequence number plus the Increment By value in the repository if the sequence generator Number of Cached Values is 0. When you open the mapping after a session run, the current value displays the last sequence value generated plus the Increment By value.
Reset:
The reset option is applicable only for non reusable sequence generator transformation and it is disabled for reusable sequence generator. If you select the Reset option, the integration service based on the original current value each time it starts the session. Otherwise the integration service updates the current value in the repository with last value generated plus the increment By value.
Number of Cached Values:
The Number of Cached Values indicates the number of values that the integration service caches at one time. When this value is configured greater than zero, then the integration service caches the specified number of values and updates the current value in the repository.
Non Reusable Sequence Generator:
The default value of Number of Cached Values is zero for non reusable sequence generators. It means the integration service does not cache the values. The integration service, accesses the Current Value from the repository at the start of the session, generates the sequence numbers, and then updates the current value at the end of the session.
When you set the number of cached values greater than zero, the integration service caches the specified number of cached values and updates the current value in the repository. Once the cached values are used, then the integration service again accesses the current value from repository, caches the values and updates the repository. At the end of the session, the integration service discards any unused cached values.
For non-reusable sequence generator setting the Number of Cached Values greater than zero can increase the number of times the Integration Service accesses the repository during the session. And also discards unused cache values at the end of the session.
As an example when you set the Number of Cached Values to 100 and you want to process only 70 records in a session. The integration service first caches 100 values and updates the current value with 101. As there are only 70 rows to be processed, only the first 70 sequence number will be used and the remaining 30 sequence numbers will be discarded. In the next run the sequence numbers starts from 101.
The disadvantage of having Number of Cached Values greater than zero are: 1) Accessing the repository multiple times during the session. 2) Discarding of unused cached values, causing discontinuous sequence numbers
Reusable Sequence Generators:
The default value of Number of Cached Values is 100 for reusable sequence generators. When you are using the reusable sequence generator in multiple sessions which run in parallel, then specify the Number of Cache Values greater than zero. This will avoid generating the same sequence numbers in multiple sessions.
If you increase the Number of Cached Values for reusable sequence generator transformation, the number of calls to the repository decreases. However there is chance of having highly discarded values. So, choose the Number of Cached values wisely.
Recommended Reading:
Sequence Generator Transformation
Follow Us on Facebook | __label__pos | 0.804896 |
GED Math – Magoosh GED Blog https://magoosh.com/ged Everything you need to know about the GED Exam Wed, 17 Apr 2019 13:44:55 +0000 en-US hourly 1 https://magoosh.com/ged/files/2021/04/cropped-magoosh-favicon-32x32.png GED Math – Magoosh GED Blog https://magoosh.com/ged 32 32 GED Math: Fraction Fluency https://magoosh.com/ged/ged-math-fraction-fluency/ https://magoosh.com/ged/ged-math-fraction-fluency/#comments Sat, 04 Aug 2018 00:38:44 +0000 https://magoosh.com/ged/?p=703 On the GED Math section, Fraction fluency is fundamental! You have to be familiar with the standard operations on fractions (adding, subtracting, multiplying, and dividing). Moreover, it’s important to know what fractions mean in the context of a word problem. Interpreting Fractions What is a fraction? The simple answer (probably the same one your teacher […]
The post GED Math: Fraction Fluency appeared first on Magoosh GED Blog.
]]>
On the GED Math section, Fraction fluency is fundamental! You have to be familiar with the standard operations on fractions (adding, subtracting, multiplying, and dividing). Moreover, it’s important to know what fractions mean in the context of a word problem.
Fraction in a cake
A fraction is a part of the whole — piece of cake!
Interpreting Fractions
What is a fraction? The simple answer (probably the same one your teacher gave you in first grade) is that a fraction measures a part of the whole. But what does that really mean?
If you shot a basketball 20 times during a game, but only made 15 of the shots into the basket, then you could say that 15/20 (fifteen-twentieths) of your shots were on target.
You might also say that you were successful 75% of the time. That’s because when you divide, 15/20 = 15 ÷ 20, you get 0.75, which is the decimal equivalent for 75%.
Furthermore, you could say that you made 3 out of every 4 shots, or 3/4 of your total shots were good. This is because 15/20 and 3/4 are equivalent fractions. Multiplying or dividing both the numerator (top number) and the denominator (bottom number) by the same amount gives you a fraction with the same value as the original. In this case, 15 ÷ 5 = 3, and 20 ÷ 5 = 4 implies that 15/20 = 3/4.
Improper Fractions and Mixed Numbers
Sometimes a fraction has a larger numerator than denominator. In that case we say that the fraction is improper. It’s harder to think of an imporper fraction as a “part out of the whole.” Instead, just interpret the fraction as a division.
For example, 10/4 is improper. But 10/4 = 10 ÷ 4 = 2.5.
Mixed numbers combine whole numbers and fractions together. For example, 10/4 = 2.5 = 2 ½. (You can also do long division to find the quotient and remainder. The quotient would be the whole number part, and the remainder is the numerator of the fractional part.)
Fraction Arithmetic
Believe it or not, it’s much easier to multiply fractions than to add or subtract them! But let’s go in the usual order and talk about addition first.
Adding and Subtracting
Adding two fractions requires a common denominator. First check to see whether the two fractions have the same denominator — if they do, then you can just add the numerators together. But if the denominators are different, you have to find the least common denominator and re-express each fraction.
Let’s see how it works by example. Notice that 36 is the least common denominator for 12 and 9, since it’s the first multiple of both numbers. Check out GED Math: Factors, Multiples, and Primes for more info!
ged math fraction -magoosh
Subtracting works exactly the same way, except that the numerators will be subtracted instead. Here’s an example.
subtracting fractions
Multiplying and Dividing
To multiply two fractions, simply multiply the numerators and multiply the denominators. Check for cancellation (common factors) before multiplying to save some time.
multiplying fractions
Dividing is just as easy. You just have to convert the problem into multiplication! The rule is
• When dividing by a fraction, multiply by its reciprocal instead.
In other words,
rule for dividing fractions
Here’s an example of the division rule in practice.
Example
How many 3/4 foot long pieces can be cut from a 9 foot board, assuming no waste due to cutting?
Solution
We are asking how many times one quantity (3/4) will go into another (9). This calls for division. Remember that any whole number can be made into a fraction by dividing by 1.
dividing fractions example
Conclusion
Interpreting fractions and knowing how to add, subtract, multiply, and divide them are important skills to master for the GED Mathematics section. With these fundamentals in place, you build up to more advanced topics. Good luck!
The post GED Math: Fraction Fluency appeared first on Magoosh GED Blog.
]]>
https://magoosh.com/ged/ged-math-fraction-fluency/feed/ 3
GED Math: Evaluating Functions https://magoosh.com/ged/ged-math-evaluating-functions/ https://magoosh.com/ged/ged-math-evaluating-functions/#comments Tue, 10 Jul 2018 04:55:41 +0000 https://magoosh.com/ged/?p=719 What are functions? What do they mean when they ask you to evaluate a function at a given number? In this article, we’ll see what functions are all about and how to work with them. These skills will help you to succeed on the GED Mathematics section. Functions — Input and Output Let’s start with […]
The post GED Math: Evaluating Functions appeared first on Magoosh GED Blog.
]]>
What are functions? What do they mean when they ask you to evaluate a function at a given number? In this article, we’ll see what functions are all about and how to work with them. These skills will help you to succeed on the GED Mathematics section.
functions as machines
A function is like a machine. If you feed input into it, then the function will do something to that input and generate an output.
Functions — Input and Output
Let’s start with a simple example to help explain the terms and concepts. Consider the following function:
f(x) = 3x + 1
You can tell that we’re dealing with a function because of the notation “f(x).” This notation tells you that the function name is f and the input variable is x. The expression that follows, 3x + 1, is the function definition or rule. That tells you what the function does to its input.
When you evaluate a function at a given number, you simply replace the input variable with that number and work out the numerical value. (This is often called plugging in.)
The notation tells you what to plug in. If you see f(2), then that means you have to substitute 2 in place of x in the function and work out the output value.
For example, let’s find f(2) if f(x) = 3x + 1.
f(2) = 3(2) + 1 = 6 + 1 = 7.
Pretty easy, right?
Tables and Graphs of Functions
We often use the variable y to stand for the output of a function. So we might write y = f(x).
Suppose you want to evaluate a function at multiple input values. You might set up a table to keep track of all of the input and output.
For example, let’s evaluate f(x) = 3x + 1 at -2, -1, 0, 1, and 2.
xy
-23(-2) + 1 = -5
-13(-1) + 1 = -2
03(0) + 1 = 1
13(1) + 1 = 4
23(2) + 1 = 7
Now that we have a table a values, we can go one step further and draw a graph of the function. A graph is a visual display of the input and output values. When you plot the points of a graph, always be sure that your coordinates are in the order (x, y), or in other words, (x, f(x)).
graph of 3x+1
The graph of the function f(x) = 3x + 1. The five points from the table above are labelled. The graph “connects the dots,” providing a more complete picture of the function.
Using the Graph to Evaluate a Function
In fact, the graph can be used to evaluate a function even if you don’t have the function definition explicitly given.
For example, the graph below represents a function y = g(x). What is the value of g(5)?
Graph of a function
This time, we can’t plug x = 5 into anything, because there’s no function definition provided. To solve this, just look for the y coordinate when x = 5. Based on the graph, we find that g(5) = 4.
graph of a function with a point labelled
We see that g(5) = 4 because the point (5, 4) is on the graph.
Graphing is a key topic that shows up in a number of forms on the GED Math section. Check out the following article for a discussion of graphing from a different perspective: GED Math: Data Analysis Questions.
Evaluating Functions at Variable Quantities
Sometimes a problem will ask you to evaluate an expression like f(a + 1) or f(x2). These are more difficult because it’s no longer just “plug in and determine a value.” Instead, you’ll have to use your Algebra skills to simplify the expression. Let’s see how this works by example.
Evaluate f(d – 4) if f(x) = 3x2x + 9.
The first step is similar to what we did above. Replace x by the input quantity. However, instead of a number, you have to “plug in” a variable expression, (d – 4) in this case. Be sure to put parentheses around the expression everywhere in the function.
f(d – 4) = 3(d – 4)2 – (d – 4) + 9
Next, carefully simplify the result. Start by squaring the binomial in the first term.
= 3(d2 – 8d + 16) – (d – 4) + 9
Then use the Distributive Property. Be careful with that minus!
= 3d2 – 24d + 48 – d + 4 + 9
Finally combine like terms.
= 3d2 – 25d + 61
Although it might seem complicated at first, this is just an extension of what you already know from Algebra.
Setting up Functions
Sometimes in a word problem, you may have to set up a function and then evaluate it. For example, suppose that your smartphone provider charges you $25 per month plus $15 per each gigabyte of data used. Write the function that represents the total monthly bill when x gigabytes of data are used.
First think it out! If you didn’t use any data in a given month then you’d still have to pay the monthly fee of $25. Using one gigabyte would raise that bill to $25 + $15 = $40. Two gigabytes would cost $25 + $15 · 2 = $55, and three would cost $25 + $15 · 3 = $70, etc.
So the pattern is: $25 + $15 · (gigabytes used). Or, in function notation, with x = gigabytes of data, you would write your answer as follows:
f(x) = 25 + 15x
That’s all there is to it!
Practice Problems
Ok, are you ready to work a few problems yourself? The following problems are modeled from actual GED Math questions. Good luck!
1. Find the value of h(-2) if h(x) = 3x2 – 2x + 5.
2. A. -11 B. -3 C. 13 D. 21
3. A car sales representative gets paid $800 per week plus 10% of any sales she makes during that week. Set up a function that calculates the sales representative’s weekly pay, using s for the total sales (in dollars).
4. A. 800 + 0.1s B. 0.1 + 800s C. 800s0.1 D. 800.1s
5. Evaluate g(t3) if g(t) = t4 – 5t
6. A. t3 – 5t B. t12 – 5t3 C. t7 – 5t3 D. (t4 – 5t)(t3)
7. Which function best represents the ordered pairs of data shown in the table?
table of function values
A. f(x) = 2x – 1 B. f(x) = 5x – 7 C. f(x) = x2 – 1 D. f(x) = ½(x + 1)2
bubble sheet
Ready to check your answers?
Answer Key
1. D 2. A 3. B 4. C
The post GED Math: Evaluating Functions appeared first on Magoosh GED Blog.
]]>
https://magoosh.com/ged/ged-math-evaluating-functions/feed/ 4
GED Math: Factoring Polynomials https://magoosh.com/ged/ged-math-factoring-polynomials/ https://magoosh.com/ged/ged-math-factoring-polynomials/#respond Sat, 02 Jun 2018 00:23:03 +0000 https://magoosh.com/ged/?p=711 Factoring is a method for “un-multiplying” a polynomial. In other words, factoring is the method of breaking down a polynomial into smaller parts (called factors) whose product is equal to the original polynomial. Factoring is just one topic in algebra. For more, check out: GED Algebra Prep. Greatest Common Factors When you need to factor […]
The post GED Math: Factoring Polynomials appeared first on Magoosh GED Blog.
]]>
Factoring is a method for “un-multiplying” a polynomial. In other words, factoring is the method of breaking down a polynomial into smaller parts (called factors) whose product is equal to the original polynomial.
Factoring is just one topic in algebra. For more, check out: GED Algebra Prep.
Greatest Common Factors
When you need to factor a polynomial, first look for a greatest common factor (GCF). The GCF of a polynomial is an expression that divides into every term (with no remainder), and such that no greater such term exists. It’s made up of two parts:
1. The GCF of the numerical coefficients. This could be 1 if there are no larger factors common to all coefficients.
2. Variable factor with the least power among all variable powers showing up in the polynomial. This would be 1 if there is a constant term.
For example, the polynomial 12x7 + 18x3 has GCF = 6x3. On the other hand, the GCF of the polynomial 3x2 – 7x + 10 is simply 1, because there are no nontrivial numeric or variable factors common to all three terms.
After finding the GCF, if it’s greater 1, then you should factor out by it (When GCF=1, factoring out by it doesn’t change the polynomial). Divide each term by the GCF to determine what remains.
So you would factor the first example as follows: 12x7 + 18x3 = 6x3( 2x4 + 3).
Difference of Squares
There is a famous and very useful formula in Algebra called Difference of Squares.
Difference of squares factoring rule
It’s easy to apply, but only works in specific situations: two-term polynomials in which both terms are perfect squares.
For example, 4x2 – 81 can be factored by Difference of Squares. The result is: (2x – 9)(2x + 9). (This is because (2x)2 = 4x2 and 92 = 81.)
However, 3x2 – 12 doesn’t quite fit the rule… yet. On the other hand, there is a GCF. Let’s first factor out by the GCF of 3.
3x2 – 12 = 3(x2 – 4)
Now we can use Difference of Squares on the remaining polynomial.
… = 3(x – 2)(x + 2)
Don’t Make up Your Own Rules
It’s very important to use the rules correctly. For example, there is no “Sum of Squares” factoring rule.
So don’t try to factor something like x2 + 16 into factors such as (x – 4) or (x + 4). It just doesn’t work that way. (In fact, sums of squares do not generally factor down any further.)
Perfect Square Trinomials
There are two related rules involving polynomials that factor into a pair of the same factors — in other words, polynomials that are themselves perfect squares. This rule applies only to trinomials, polynomials with exactly three terms.
Perfect square trinomials
In practice, these might be tricky to spot. But first look at the constant term as a clue. If the constant term is a perfect square, then you just have to check the middle term to see if it fits the pattern.
For example, consider x2 – 22x + 121. We can see that 121 = 112. So there’s a chance that we’re dealing with a perfect square trinomial with a = x and b = 11. Check the middle term against 2ab.
2ab = 2(x)(11) = 22x
That’s exactly what shows up in our middle term, so we can use the rule! Check the sign on the middle term — it’s negative. Therefore,
x2 – 22x + 121 = (x – 11)2
Trinomial Factoring
Most trinomials are not perfect squares, so we need to have a general method for factoring them. There are two cases:
• Leading coefficient = 1. That is, the polynomial looks like: x2 + bx + c.
• Leading coefficient > 1. In other words, the polynomial has the form: ax2 + bx + c, where a > 1.
Leading Coefficient = 1
This is the case in which the polynomial has the form x2 + bx + c. Because the first term is just x2, we know that the factors must look like this:
(x + __)(x + __)
Your job is to fill in the blanks. We need to find two numbers that multiply to give you c and add up to b.
Let’s try it with a simple example. Factor x2 + 7x + 12.
Here, b = 7 and c = 12. What are the factors of 12? Write them in pairs and then put their sums in the third column of a table. (By the way, if you need a refresher on finding factors of a number, check out: GED Math: Factors, Multiples, and Primes.)
Factor 1Factor 2Sum
11213
268
347
We can see that 3 and 4 do the trick because 3 × 4 = 12 and 3 + 4 = 7. Therefore,
x2 + 7x + 12 = (x + 3)(x + 4).
The method also works when b and/or c are negative.
• If c > 0, then the two factors must have the same sign. They are both positive if b > 0, and both negative if b < 0.
• If c < 0, then the two factors must have opposite signs. In this case, if b > 0, then the larger factor (in absolute value) has the positive sign, while if b < 0, then the larger factor has the negative sign.
For example, let’s factor x2x – 20.
We need the factors of 20. Because c = -20 is negative, and b = -1 is also negative, the signs of the two factors will be opposite, with the minus on the larger factor.
Factor 1Factor 2Sum
1-20-19
2-10-8
4-5-1
It looks like 4 and -5 do the job. Therefore,
x2x – 20 = (x + 4)(x – 5).
Leading Coefficient > 1
Now if the leading coefficient is larger than 1, the process is more involved. We have to keep track of much more information, and there are more combinations to consider.
One method that seems to keep everything organized is the so-called box method. Here’s how it works.
To factor trinomials of the form ax2 + bx + c, in which there is no GCF:
1. First multiply a × c.
2. Next, find two numbers that will multiply to ac and add to b. (This step is just as in the coefficient=1 case, except that we use ac in place of c.)
3. Build a 2 by 2 box. Place the term ax2 in the upper left and c in the lower right. Then fill the other two boxes with the two terms that would add to get the middle term bx (using your numbers from step 2). It doesnt’t matter which order you put the last two terms in.
4. Factor out the GCF of each row, placing the result outside the box on the left.
5. Factor out the GCF of each column, placing the result outside the box below.
6. The terms to the left of the box form one factor, and the terms below the box form the second factor. Just be sure to put plus signs between the terms.
Let’s see how it works in practice.
Factor 4x2 + 5x – 6.
Here, we have ac = 4 × (-6) = -24. Since the result is negative, we need our factors to have opposition sign. But since the middle term is positive, the minus goes onto the smaller factor.
Factor 1Factor 2Sum
-12423
-21210
-385
-462
We can see that -3 and 8 will add to 5. That means that 5x = -3x + 8x.
Now let’s build the box.
box method illustration
Here, the black terms were filled in first. 4x2 is the leading term of the polynomial (upper left), -6 is the constant term (lower right). Then with our splitting of 5x into -3x and 8x, you should place those terms into the other boxes as shown.
The GCF of the first row is x, and the GCF of the second row is 2. Those terms are in red on the left side. Working down the columns, the corresponding GCFs are 4x and -3, shown below the main table.
Therefore, reading the factors off of the table, we have:
4x2 + 5x – 6 = (x + 2)(4x – 3).
Factoring by Grouping
So far, we’ve seen factoring of binomials and trinomials. What about polynomials with four or more terms? There are not a lot of options available in those cases. Certainly look for a GCF. In fact, that should be your initial step in every factoring problem. But as a last resort, you might try factoring by grouping.
To factor by grouping:
1. First factor out a GCF if there is one.
2. Group the terms in pairs.
3. Find a GCF and factor each pair.
4. If the expressions in parentheses match, then that expression can be factored out.
5. Determine if there is any further factoring that can be done in the resulting expression.
For example, we can use factoring by grouping on the following polynomial:
4x3 + 12x2x – 3
First, look for a GCF. The GCF is 1, meaning that there is nothing to factor out from all of the terms at once.
Next, group into pairs and factor each pair. Be careful with negatives!
(4x3 + 12x2) + ( –x – 3) = 4x2(x + 3) + (-1)(x + 3)
We’re in luck! Both pairs have the expression (x + 3) in common. That means we can continue the factoring process. Pull out this common factor from both terms.
… = (4x2 – 1)(x + 3)
Finally, look for further factoring. The first group can be broken down by Difference of Squares.
… = (2x – 1)(2x + 1)(x + 3)
Practice Problems
Now’s your chance to check your progress! Factor each of the following polynomials. Answers will be given below.
1. x2 – 8x – 9
2. t2 – 25
3. t2 + 25
4. 2y2 + 8y4
5. 32x2 – 98
6. x2 + 12x + 36
7. z3 + 11z2 – 4z – 44
8. 2x2 + 2x – 4
9. x3 – 4x2 – 21x
10. 6x2 – 7x – 3
doing practice problems
Are you ready to check your answers?
Answers
1. (x + 1)(x – 9)
2. (t – 5)(t + 5)
3. t2 + 25 (does not factor further)
4. 2y2(1 + 4y2)
5. 2(4x – 7)(4x + 7)
6. (x + 6)2
7. (z – 2)(z + 2)(z + 11)
8. 2(x – 1)(x + 2)
9. x(x + 3)(x – 7)
10. (3x + 1)(2x – 3)
The post GED Math: Factoring Polynomials appeared first on Magoosh GED Blog.
]]>
https://magoosh.com/ged/ged-math-factoring-polynomials/feed/ 0
GED Math: Radical Exponents https://magoosh.com/ged/ged-math-radical-exponents/ https://magoosh.com/ged/ged-math-radical-exponents/#respond Fri, 23 Mar 2018 23:22:32 +0000 https://magoosh.com/ged/?p=681 In this article, we’ll learn all about exponents and radicals. We’ll also get a chance to practice these concepts on problems similar to those you might see on the GED Math Section. (For more information about what’s on the test, check out: What’s on the GED Math Test?) What are Exponents? Let’s start with the […]
The post GED Math: Radical Exponents appeared first on Magoosh GED Blog.
]]>
In this article, we’ll learn all about exponents and radicals. We’ll also get a chance to practice these concepts on problems similar to those you might see on the GED Math Section.
(For more information about what’s on the test, check out: What’s on the GED Math Test?)
What are Exponents?
Let’s start with the basics. Whole number Exponents, or powers, are shorthand for repeated multiplication.
For example, 43 = 4 × 4 × 4 = 16 × 4 = 64. (Be careful: This is not the same thing as 4 × 3, which equals 12.)
Exponents make it quicker and more efficient to write algebraic expressions involving lots of factors of the same kind. So, instead of writing an expression like this…
3 × 3 × 3 × 3 × x × x × x × x × x × y × y
… you would write it instead like this:
34x5y2
Of course this works the other way around too. If you need to evaluate (-2)3, for example, then first write it as repeated multiplication: (-2)3 = (-2)(-2)(-2). Then work through the products to get (-2)(-2)(-2) = (4)(-2) = -8. (This is really important for the no-calculator section of the test!)
What if the exponent is 1? Well think about it… if there’s only one factor, then there’s nothing else to multiply to it. So x1 = x for any number x.
We’ll talk about other kinds of exponents below, including zero, negative, and fractional.
Order of Operations
According to standard order of operations, evaluating exponents comes before any multiplications, divisions, additions or subtractions. Keep in mind that grouping symbols always take precedence though.
Just remember “PEMDAS” (Please Excuse My Dear Aunt Sally).
• P — Parentheses and other grouping symbols must be worked out as a self-contained group first.
• E — Exponents come next.
• M and D — Multiplication and Division occur next, going left to right.
• A and S — Addition and Subtraction are done last, again going from left to right.
For example,
• 6 – 23 = 6 – 8 = -2. (NOT 6 – 23 = 43 = 64.)
• 5 · 22 = 5 · 4 = 20. (NOT 5 · 22 = 102 = 100.)
• (2 + 3)2 = 52 = 25. (Parentheses take precedence over powers.)
The Basic Rules of Exponents
There are three basic rules. Other rules will build upon these.
basic rules of exponents
The three fundamental rules of exponents
Negative Exponents
Now if powers stands for repeated multiplication, then what do negative powers mean? What about fractional powers? How do you multiply something by itself -3 times or 1/2 of a time?
The key is that we can interpret the expressions in ways that make the rules of algebra consistent.
For example, there is a rule that states “anything to the zero power is equal to 1.” Why should that be true? Well, it follows from the quotient rule for exponents:
1 = x1 / x1 = x1 – 1 = x0
In a similar way, you can interpret negative powers at fractions:
x – a = x0 – a = x0 / xa = 1 / xa
So, 5 – 3 = 1 / (53) = 1/125.
Note: A negative exponent does not mean that the result is a negative number!
Fractional Powers
Fractional powers are trickier. For example, we have a rule that states: half power of x is the square root of x. In other words, a fractional power is the same as a radical (or root)!
The reason for this strange rule is that it’s what we need to do to keep all of the fundamental rules consistent. If x1/2 equals something, then consider what happens when you square both sides:
proof that the half-power is a square root
So if something squared equals x, then that “something” must be the square root of x.
Similarly, if n is a whole number, then the fractional power x1/n is the same thing as the nth root of x.
More Rules!
All of the exponent rules for negative and fractional powers are a consequence of keeping things consistent algebraically. Here is the full list of the rules for zero, negative, and fractional powers.
Rules for zero, negative, and fractional powers
The rules can be combined. For example, let’s work out 27-4/3.
27^(-4/3) = 1/81
Furthermore, there are algebraic rules that define how exponents and radicals interact with multiplication and division. These are very important when breaking down complicated expressions into simpler forms.
Rules for products and quotients
The following example will show how a few rules work together to simplify a very complex expression.
Simplify: example - simplify radicals.
First combine the radicals using the product property.
Step 1 in radicals example
Then combine factors. The coefficients should be multiplied together directly. But use the exponent rules to deal with the variables and powers.
Step 2 in radicals example
Next, split the radical once again over the products. For the variable factors, it may help to rewrite the radicals as powers using the rules for fractional exponents.
Step 3 in radicals example
The square root of 36 is 6. Multiply powers to simplify the variable factors. Finally, we have our simplified expression!
= 6x3yz3
Practice Problems
Now let’s see if we can apply what we’ve learned to the following GED Math practice problems! Answers and explanation will be given at the end. Good luck!
1. Solve 64.
• A. 24
• B. 36
• C. 216
• D. 1,296
2. Find the value of 4 + 25 – 6 · 32.
• A. -288
• B. -18
• C. 219
• D. 7,452
3. Simplify (2x3)(5x2).
• A. 7x6
• B. 10x6
• C. 10x5
• D. 7x5
4. What is the value of 3y4 – 8x – 1 if x = 2 and y = 1?
• A. -1
• B. -13
• C. 77
• D. 65
5. Choose the correct value for 1003/2
• A. 10
• B. 100
• C. 150
• D. 1000
6. Simplify: (2x) – 2 (12x3)
• A. 6x2
• B. 3x
• C. 48x5
• D. 6x
Answers and Explanations
1. Answer: D. A whole number exponent stands for repeated multiplication. 64 = 6 × 6 × 6 × 6 = 1,296.
2. Answer: B. Follow the correct order of operations. Powers first. Then multiplication. Then addition and subtraction.
4 + 25 – 6 · 32
= 4 + 32 – 6 · 9
= 4 + 32 – 54
= 46 – 54
= -18
3. Answer: C. Use the rules to rewrite the expression. Remember, when you multiply two factors that have the same base, you have to add the powers.
(2x3)(5x2) = (2 × 5) x3 + 2 = 10x5.
4. Answer: A. First, plug in x = 2 and y = 1. Then work out the powers, following proper order of operations. Keep in mind that a negative exponent stands for a fractional value.
3(1)4 – 8(2) – 1 = 3 × 1 – 8 × (1/2) = 3 – 4 = -1.
5. Answer: D. Here we have to interpret the fractional power as an appropriate radical.
100^(3/2) = 1000
6. Answer: B. Pay special attention to the grouping. In the first group, the exponent applies to both the 2 and the x.
Answer to practice problem 5
The post GED Math: Radical Exponents appeared first on Magoosh GED Blog.
]]>
https://magoosh.com/ged/ged-math-radical-exponents/feed/ 0
GED Math: Factors, Multiples, and Primes https://magoosh.com/ged/ged-math-factors-multiples-primes/ https://magoosh.com/ged/ged-math-factors-multiples-primes/#respond Fri, 23 Feb 2018 18:30:02 +0000 https://magoosh.com/ged/?p=675 Factors, Multiples, and Primes, Oh My! What are these strange beasts? By the end of this article, you’ll learn how to find the factors and multiples of a whole number. You’ll also discover prime numbers and what role they play in factorization. These concepts provide important fundamentals for succeeding on the GED Math section. For […]
The post GED Math: Factors, Multiples, and Primes appeared first on Magoosh GED Blog.
]]>
Factors, Multiples, and Primes, Oh My! What are these strange beasts? By the end of this article, you’ll learn how to find the factors and multiples of a whole number. You’ll also discover prime numbers and what role they play in factorization. These concepts provide important fundamentals for succeeding on the GED Math section.
For more information about what to expect, check out What’s on the GED Math Test?
Dorothy from the Wizard of Oz - factors, multiples, and primes, oh my!
I’ve a feeling we’re not in Kansas anymore!
Factors
The whole numbers, 1, 2, 3, 4, 5, …, are fascinating! Each one has unique qualities and properties, much like the various chemicals and minerals in our world display different characteristics. And just as physical materials can be broken down into simpler components (elements), so too numbers can be broken down into factors.
A factor of a number is any number that divides into it with zero remainder. For example, the factors of 6 are: 1, 2, 3, 6. Factors are always less than or equal to the number.
The quickest way to find all factors of a number is to start from the smallest and work your way up. Keep in mind that factors come in pairs. If a is a factor of n, then there must be another number b such that a × b = n. That means that b would also be a factor.
Let’s find the factors of 36. I like to build a table with two columns. Start with 1 (which is always a factor), and keep going up, testing each number to see if it’s a factor. Put the factor partner in the other column.
136
218
312
49
66
Notice the bottom line: 6 is a factor, but its factor partner is also 6. This is because 36 is a perfect square (36 = 62). So the factors of 36 are: 1, 2, 3, 4, 6, 9, 12, 18, 36.
Can you find the factors of 120? (The answer will be at the end.)
Multiples
Multiples are numbers that have the original number as a factor. In other words, a multiple of n is simply the result of multiplying n by another whole number k (that is, n × k).
Multiples are always greater than or equal to the original number. Moreover, there’s an infinite number of them for any given whole number! But don’t worry; there’s a very easy way to generate multiples. Think multiplication table!
For example, let’s list the first ten multiples of the number 6.
6 × 1 =6
6 × 2 =12
6 × 3 = 18
6 × 4 = 24
6 × 5 = 30
6 × 6 =36
6 × 7 =42
6 × 8 =48
6 × 9 =54
6 × 10 =60
The multiples are: 6, 12, 18, 24, 30, 36, 42, 48, 54, 60, etc.
Now you try it out. Find the first ten multiples of 9.
Primes
Some numbers have a ton of factors while others don’t seem to have many at all. Any number that has precisely two distinct factors, 1 and itself, is called prime. Numbers that have more than two factors are composite. The lonely number 1 is neither prime nor composite.
The first ten primes are: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29.
Primes are important because they are the building blocks of every whole number. All composite numbers have a unique prime factorization, that is, a list of the primes or prime powers that are factors of the number. The easiest way to find the prime factorization of a number is to use a factor tree.
Starting with 2, the smallest prime, divide into the original number until it can’t be divided further. Then go to the next prime and do the same. Keep going until the last quotient is itself prime.
Let’s see how it works for the number 168.
prime factorization of 168
The numbers on the “leaves” of the tree form the prime factorization. Then we would write:
168 = 23 × 3 × 7.
Now you try your hand at it! Find the prime factorization of 1980.
Summary
• The factors of a number are numbers that divide evenly into the given number.
• The multiples of a number are numbers found by multiplying the original number by any whole number.
• Primes are numbers with only two distinct factors. They are useful in finding the prime factorization of a number.
Answers
• Factors of 120 are: 1, 2, 3, 4, 5, 6, 8, 10, 12, 15, 20, 24, 30, 40, 60, 120.
• Multiples of 9 are: 9, 18, 27, 36, 45, 54, 63, 72, 81, 90, …
• Prime factorization: 1980 = 22 × 32 × 5 × 11.
The post GED Math: Factors, Multiples, and Primes appeared first on Magoosh GED Blog.
]]>
https://magoosh.com/ged/ged-math-factors-multiples-primes/feed/ 0
GED Study Guide: Math-Focused https://magoosh.com/ged/ged-study-guide-math-focused/ https://magoosh.com/ged/ged-study-guide-math-focused/#comments Thu, 10 Aug 2017 19:05:27 +0000 https://magoosh.com/ged/?p=442 The GED Math test is approaching. You’ve studied and mastered the material, now it’s time to master the exam with this GED study guide.
The post GED Study Guide: Math-Focused appeared first on Magoosh GED Blog.
]]>
The GED Math test is approaching. You’ve studied and taken every practice test available. You’ve mastered the material, now it’s time to master the exam. This GED study guide has some great math strategies that can help you do your best and keep your cool on test day.
Backsolving
Solving an equation by isolating a variable can be time-consuming. If you make a mistake and don’t see your solution among the answer choices, you will waste more time reworking the problem (as well as stressing over your mistakes). To avoid all the complications that come with actually doing the algebra on a math test, often it is quicker and easier to backsolve.
Backsolving is plugging the answer choices into the equation. This works for questions that have numbers as the answer choices (not variables). If you are solving for x, then you can substitute each value provided in the answer choices for x in the equation. The answer choice that makes the equation true is the correct response.
Example:
Find the value of x in the following equation:
2x-11=7x+4
A) -1
B) -2
C) -3
D) -4
Answer choices are usually presented in ascending order, so a good strategy it so begin with B or C, and work your way out to A and D.
So, start with B. Substitute -2 for x in the equation:
2x-11=7x+4
2(-2)-11=7(-2)+4
-4-11=-14+4
-15=-10
That’s not true, so you can eliminate B.
Now try C. Substitute -3 for x in the equation:
2x-11=7x+4
2(-3)-11=7(-3)+4
-6-11=-21+4
-17=-17
Success! This equation is true. So, you know that C is the correct answer.
Estimation
Estimation is the art of rounding values to figures you can calculate mentally. Estimating allows you to see which answer choices are unreasonable, thereby eliminating possibilities. Reducing the number of possible answers increases your odds of choosing correctly. If you’re lucky, you can eliminate all of the answer choices except for the correct one.
Example:
A man-made pond is in the shape of a perfect circle. The diameter of the pond is 19.75 feet. What is the circumference of the pond, rounded to the nearest hundredth of a foot?
A) 62.02 feet
B) 124.03
C) 306.20 feet
D) 1,224.80 feet
To find the circumference of a circle, you can use the equation C=πd, where d is the diameter of the circle. Round 19.75 to 20, and round π to 3, and you can estimate that the circumference of the pond is about 60 feet. The only answer choice close to this is A, so you can eliminate all the other choices.
Calculator Use
You are allowed to use a calculator for the second portion of the GED math exam. Make sure you are familiar with how to use a scientific calculator before taking the test. You don’t want to waste time learning how to use the calculator when you should be focused on calculating answers.
The onscreen calculator the GED offers is a TI-30XS, and you can take a tutorial to learn about all of its available functions. Practice using this calculator when studying and taking practice exams for the exam. You can also bring your own hand-held calculator if you want, but it MUST be this model (TI-30XS). No other calculators are allowed.
During the test, don’t overly rely on the calculator. It is easy to think of it as a crutch or security blanket, but it should be neither. You need to know how to make calculations without it; the calculator is not a substitute for preparing and studying. You also need the confidence to make a quick computation and move on. Don’t waste time keying in calculations you can do mentally. Have faith that you know what you’re doing without needing the calculator to prove it.
It is much easier to accidentally hit a wrong key on a calculator than it is to write an incorrect number on a piece of paper. It’s therefore best to use mental math or pencil and paper when you can do so quickly. Save the calculator for calculations that are too complicated to compute mentally, or those which take a long time to work out using pencil and paper, such as long division, square roots, or multiplication involving numbers or decimals with many digits.
Pacing
You have 115 minutes to complete approximately 46 questions on the GED math exam. If you pace yourself evenly, that’s 2.5 minutes per question; however, you need to keep a few things in mind before trying to keep up this pace:
Section 1
The first section has 5 questions. That means you should spend 12.5 minutes on this section. This section tests your skills in arithmetic and operations, and does NOT allow you to use a calculator. Stick to 2.5 minutes per question as an average. You may be able to quickly complete some questions mentally. Others you may need to spend more time on. Complete the easy questions first, then recalculate how much time you have left for the remaining questions.
Once you complete the first section, you cannot return to it, and so it may be difficult for you to leave it behind. Be confident! Try to leave yourself a minute to check your answers, but try your best to stick to spending only 12.5 minutes on this section.
Section 2
The second section has 41 questions. If you spent more or less time on the first section, recalculate how much time you have per question on this section. Divide the number of minutes left by 41, which is the number of questions in this section.
Skim through section 2 and complete the easy questions first. Then, recalculate how much time you have per each question remaining on the test.
Consider multiplying your per-question time limit by 5. This will give you the amount of time you have per every 5 questions, allowing you to spend more time on some questions and less on others while still keeping pace.For example, if you have 2.5 minutes per question, that means you have 12.5 minutes for every group of 5 questions.
Save time for review and brain breaks. After completing a group of 5 questions, check your work and take a quick break. Check your work quickly, but don’t second-guess yourself. Take a break by tightening and relaxing all the muscles in your body. Close your eyes and take a few deep breaths. Be confident and you are more likely to succeed.
The post GED Study Guide: Math-Focused appeared first on Magoosh GED Blog.
]]>
https://magoosh.com/ged/ged-study-guide-math-focused/feed/ 1
GED Math Practice Test https://magoosh.com/ged/ged-math-practice-test/ https://magoosh.com/ged/ged-math-practice-test/#comments Fri, 26 May 2017 18:58:19 +0000 https://magoosh.com/ged/?p=420 Prep for the Mathematical Reasoning subject test with this GED math practice test).
The post GED Math Practice Test appeared first on Magoosh GED Blog.
]]>
GED Math Practice Test
Prep for the Mathematical Reasoning subject test with this GED math practice test (answers at the end of the post).
Need more practice? Check out these other question sets:
GED Math Practice Test
1. Which choice shows numbers in order from least to greatest?
A) .71, 710, 7 × 10-2, 7 99100
B) 7 × 10-2, 7 99100, 710, .71
C) .71, 7 × 10-2, 7 99100, 710
D) 7 × 10-2, 7⁄10, .71, 7 99100
2. A start-up beverage company sold 32,138 bottles of cherry soda last year. Each bottle of soda was sold for $2.79. Which figure below is the best estimate for how much revenue the company earned from its cherry soda?
A) $69,000
B) $80,000
C) $90,000
D) $99,000
3. Which choice shows the correct factorization of the following expression?
15x2-45x
A) 15x(x-3)
B) 15(x-3x)
C) 15x(x2-3x)
D) 15(x2-3)
4. Simplify the following expression.
(7-3)2÷4+5-4×2
A) 1
B) 6
C) 8
D) 10
5. Find the value of x in the following equation.
2(x2-5)=8
A) 1
B) 2
C) 3
D) 4
6. What is the value of x given the following system of equations?
y-2x=2
7x-5=2y
A) 8
B) 6
C) 4
D) 3
7. Solve the following inequality.
4x > 2(-15 + 1)
A) x < -7
B) x > -7
C) x < 7
D) x > 7
8. Which choice shows the sum of the following two polynomials?
(2x2-4x+3)+ (-6x2+7x-4)
A) -4x2+3x-1
B) -8x2-11x-7
C) 4x2-3x+1
D) 8x2+11x+7
9. Oliver pays $519.20 on a computer that is on sale. The computer is regularly priced at $649. What was the percent discount Oliver received on the computer?
A) 15%
B) 20%
C) 25%
D) 30%
Use the following table to answer questions 10-12.
Jack keeps track of the number of birds who visit his backyard feeder each week. Last week he recorded the following species and their number of visits.
Bird Visits the Week of March 13
MondayTuesdayWednesdayThursdayFridaySaturdaySunday
juncos23211720121822
sparrows35424348313746
finches1213111691118
cardinals4211012
woodpeckers2012001
starlings7258357
10. What fraction of the birds who visited the feeder on Tuesday were sparrows?
A) 2140
B) 16
C) 2119
D) 15
11. What fraction of the birds who visited Jack’s feeder last Saturday and Sunday were juncos?
A) 70111
B) 516
C) 521
D) 911
12. What was the ratio of finches to cardinals that visited Jack’s feeder last week?
A) 90:101
B) 11:90
C) 11:101
D) 90:11
13. Clara goes trick-or-treating and gets 24 pieces of chocolate, 12 pieces of gum, 5 pieces of licorice, and 18 suckers. If she randomly pulls a piece of candy from her trick-or-treat bag, what is the probability of her pulling out a piece of gum?
A) 12 out of 47
B) 1 out of 4
C) 12 out of 59
D) 1 out of 12
14. Luna and Alex are choosing a menu for their reception. They have 4 choices of appetizers, 6 choices of entrees, 5 choices of side dishes, and 3 choices of cake. How many different menu combinations are possible?
A) 6
B) 18
C) 150
D) 360
15. The area of a circle is 81π cm. What is the length of its radius?
A) 3 centimeters
B) 9 centimeters
C) 18 centimeters
D) 81 centimeters
16. Theodore needs to cover a bulletin board with paper. The bulletin board is 6 feet by 4 feet. He has 8 square feet of paper. How many more square feet of paper does he need to cover the bulletin board?
A) 24 square feet
B) 20 square feet
C) 16 square feet
D) 12 square feet
17. A triangle has a base measuring 15 centimeters and a height measuring 13 centimeters. How long is its hypotenuse?
A) 195 centimeters
B) √394 centimeters
C) √28 centimeters
D) 784 centimeters
18. A swimming pool holds 2,450 cubic feet of water. The swimming pool is 35 feet long and 14 feet wide. How deep is the swimming pool?
A) 4 feet
B) 5 feet
C) 6 feet
D) 7 feet
Use the following table to answer questions 19-21.
An ice cream shop surveyed 10 customers, asking them to rate chocolate flavors on a scale of 1 to 10, with 10 being the best possible taste.
Customers' Chocolate Flavor Preference
Fudge Swirl RatingBrownie Chunk RatingClassic Rating
Customer 11079
Customer 2 6710
Customer 31098
Customer 4789
Customer 59810
Customer 67108
Customer 7865
Customer 8678
Customer 91097
Customer 10976
19. Rank the flavors from the flavor with the highest mean rating to the flavor with the lowest mean rating.
A) Fudge Swirl, Classic, Brownie Chunk
B) Classic, Brownie Chunk, Fudge Swirl
C) Brownie Chunk, Fudge Swirl, Classic
D) Fudge Swirl, Brownie Chunk, Classic
20. What was the median rating for Fudge Swirl?
A) 10
B) 9
C) 8.5
D) 7.5
21. What was the mode of the ratings for Classic?
A) 7
B) 8
C) 9
D) 10
22. What is the slope-intercept form of a line having a slope of 12 and a y-intercept of 4?
A) 4= 12x+b
B) 12=4y+x
C) x=4y+12
D) y=12x+4
23. Solve the following inequality.
-4y+8>-12
A) y<5
B) y>5
C) y<1
D) y>1
24. Find the difference of the following two polynomials:
(2x2-4x+5)-(-6x2-7x+4)
A) -4x2+3x+1
B) 4x2+11x-9
C) 8x2+3x+1
D) -8x2+11x-9
25. Amelia has spends $462 on groceries in the month of February. She spent $205 on fresh produce. About what percentage of her grocery money went to fresh produce?
A) 2.25%
B) 44%
C) 56%
D) 80%
Answer Key
1. D
7 ×10-2=7100
710=70100
.71=71100
7 99100=799100
2. C
32,138 rounds down to 30,000; $2.79 rounds up to 3. 30,000 ×3=90,000. The exact amount is $89,665.02, so $90,000 is the closest estimate among the answer choices.
3. A
The terms in the expression have a greatest common factor of 15x.
4. A
(7-3)2÷4+5-4×2
42÷4+5-4×2
16÷4+5-4×2
4+5-8
9-8=1
5. C
2(x2-5)=8
x2-5=4
x2=9
x=3
6. D
Isolate the y in the first equation:
y-2x=2
y=2+2x
Substitute the expression of y into the second equation and solve for x:
7x-5=2y
7x-5=2(2+2x)
7x-5=4+4x
7x=9+4x
3x=9
x=3
7. B
4x>2(-15+1)
4x>2(-14)
4x>-28
x>-7
8. A
(2x2-4x+3)+ (-6x2+7x-4)
2x2-6x2-4x+7x+3-4
-4x2-4x+7x+3-4
-4x2+3x+3-4
-4x2+3x-1
9. B
Find the discount.
649-519.20=129.80
Find what percent of the total price the discount is.
129.80÷649=.2=20%
10. A
42 sparrows that visited on Tuesday. Find the number of sparrows to the number of all birds who visited, including sparrows:
21+42+13+2+2 = 80
4280=2140
11. C
Find the number of juncos that visited on Saturday and Sunday.
18+22=40
Find the number of juncos on both days to the number of all birds who visited on both days, including juncos:
18+22+37+46+11+18+1+2+1+5+7=168
40168=521
12. D
90 finches visited the feeder last week, and 11 cardinals visited the feeder last week. The ratio is 90 finches per every 11 cardinals: 90:11.
13. C
The bag contains 12 pieces of gum. There are 59 possible pieces of candy she could randomly pull from the bag. 12 out of 59 times, she will pull out a piece of gum.
14. D
Use the fundamental counting principle to multiply the number of choices together:
4(6)(5)(3)=360
15. B
Use the formula for the area of a circle:
A=πr2
81π=πr2
81=r2
9=r
16. C
Find the area of the bulletin board:
A=lw
A=6(4)
A=24
Subtract the paper Theodore already has:
24-8=16
17. B
Use the Pythagorean Theorem to solve:
a2+b2=c2
152+132=c2
225+169=c2
394=c2
394=c
18. B
Use the formula for the volume of a rectangular prism:
V=lwh
2,450=35(14)h
2,450=490h
5=h
19. A
Mean rating for Fudge Swirl:
10+6+10+7+9+7+8+6+10+10=82
82÷10=8.2
Mean rating for Classic:
9+10+8+9+10+8+5+8+7+6=80
80÷10=8
Mean rating for Brownie Chunk:
7+7+9+8+8+10+6+7+9+7=78
78÷10=7.8
20. C
The median is the middle term:
6,6,7,7,8,9,9,10,10,10
8+9=17
17÷2=8.5
21. B
The mode is the number that appears most frequently:
5,6,7,8,8,8,9,9,10,10
22. D
The formula for slope-intercept form is y=mx+b, where m is the slope, and b is the y-intercept.
23. A
You must flip the sign when dividing or multiplying by a negative number.
-4y+8>-12
-4y>-20
y<5
24. C
Change the signs of the polynomial being subtracted, then add:
2x2-4x+5+6x2+7x-4
2x2+6x2-4x+7x+5-4
8x2+3x+1
25. B
205÷462=0.4437=44%
The post GED Math Practice Test appeared first on Magoosh GED Blog.
]]>
https://magoosh.com/ged/ged-math-practice-test/feed/ 4
Challenging GED Algebra Word Problems https://magoosh.com/ged/challenging-ged-algebra-word-problems/ https://magoosh.com/ged/challenging-ged-algebra-word-problems/#comments Fri, 19 May 2017 19:35:41 +0000 https://magoosh.com/ged/?p=403 Some algebra problems on the GED just ask you to solve equations. More challenging GED algebra word problems will make you write the equation AND solve it.
The post Challenging GED Algebra Word Problems appeared first on Magoosh GED Blog.
]]>
Some algebra problems on the GED Mathematical Reasoning test are straightforward: Solve a given equation for x. Once you know the basic rules for solving, these are pretty simple. Things get a little more complicated in algebra when it comes to word problems, however. Sometimes, you’ll be given a word problem that requires you to WRITE the equation first and THEN solve it. You’ll need to translate English into “mathematical language” in order to make sure you set up your equations correctly, including variables and operations. To help you practice, here are five challenging GED algebra word problems. The answer key at the end of the post has detailed explanations to help you see the relationship between words and math in these types of questions.
Challenging GED Algebra Word Problems
1. The sum of three consecutive positive integers is 111. You need to determine what the three integers are. Which equation shows how you could solve the problem?
A) 111÷3=3x
B) 3x+3=111
C) 111-3=x
D) 3x=111
2. Levi sells his old car for $5,000. He buys a new car that is $2,600 less than five times the selling price of his old car. How much did Levi spend on his new car?
A) $22,400
B) $27,600
C) $12,000
D) $13,000
3. Audrey earns money each week by tutoring and by babysitting. She charges $30 an hour for tutoring, and $15 an hour for babysitting. In one week, she makes $120 in total. She works 5 hours each week. How many hours does she tutor, and how many hours does she babysit?
A) She tutors for 1 hour and babysits for 4 hours.
B) She tutors for 4 hours and babysits for 1 hour.
C) She tutors for 2 hours and babysits for 3 hours.
D) She tutors for 3 hours and babysits for 2 hours.
4. Oliver needs 340 grams of flour to make one batch of his biscuit recipe. He buys a bag of flour that is 2.27 kilograms. If he makes three batches of biscuits, how many grams of flour will he have left?
A) 1,020 grams
B) 1,190 grams
C) 1,250 grams
D) 1,930 grams
5. Iris is selling jewelry at a craft fair. She sells twice as many rings as bracelets. She sells three more necklaces than bracelets. She sells necklaces for $15, bracelets for $5, and rings for $10. She makes $245 at the craft fair. How many necklaces, bracelets, and rings did Iris sell?
A) 8 necklaces, 5 bracelets, and 10 rings
B) 5 necklaces, 10 bracelets, and 8 rings
C) 10 necklaces, 8 bracelets, and 5 rings
D) 5 necklaces, 8 bracelets, and 10 rings
Answer Key
1. B
You need to find three numbers that will add up to 111. The term “consecutive positive integers” essentially means three whole numbers in a row, such as 1, 2, and 3. You can let the first number in the series be x. Since the numbers are consecutive, the second number in the series will be 1 more than x, and the third number in the series will be 2 more than x, so the three consecutive integers are x, x+1, and x+2. The sum of these three terms needs to be 111, so your equation will be:
(x)+(x+1)+(x+2)=111
You can simplify the expression by combining like terms—in this example, adding the variables and then adding the constants.
(x)+(x+1)+(x+2)=111
3x+1+2=111
3x+3=111
If you wanted to solve for x, you would isolate the variable by subtracting 3 from both sides, then dividing by 3:
3x+3=111
3x=108
x=36
So, the 3 consecutive integers are 36, 37, and 38.
2. A
Challenging GED Algebra Word Problems
This problem involves translating the words into mathematical expressions.
PhraseMathematical Expression Explanation
five times5xThe phrase "five times" tells you that you will multiply some amount by 5. Use x to represent the unknown value.
Levi sells his old car for $5,000. 5(5000)Since you are looking for an amount that is five times the selling price of his old car, and you know that he sold his old car for 5,000, x, the amount you are multiplying by 5, is equal to 5,000.
$2,600 less-2600This phrase tells you that you will subtract 2600 from some amount.
$2,600 less than five times the selling price of his old car5(5000)-2600You know that you are looking for $2,600 less than five times the selling price of his old car, which is the term you found previously.
How much did Levi spend on his new car? yYou are trying to find out how much Levi paid for his new car. This is your unknown variable.
He buys a new car that is $2,600 less than five times the selling price of his old car. y=5(5,000)-2,600This sentence tells you that the price of his new car equals the expression you found previously.
Now, you just need to solve for y:
y=5(5,000)-2,600
y=25,000-2,600
y=22,400
3. D
This problem involves a system of equations, since you have multiple unknown variables.
• Let x be the number of hours Audrey tutors each week.
• Let y be the number of hours she babysits each week.
The first equation is quite simple to set up, since you know that she works 5 hours each week:
x+y=5
Use the information about the money Audrey earns to set up the second equation.
You know she makes $30 an hour tutoring, and you already stated that the number of hours she tutors each week is x. So, the expression describing how much she makes each week tutoring is 30x.
You also know that she makes $15 an hour babysitting, and you already stated that the number of hours she babysits each week is y. So, the expression describing how much she makes each week babysitting is 15y.
Altogether, she makes $120 a week. So, your second equation tells you how to calculate the amount of money she earns weekly:
30x+15y=120
You can simplify this equation by dividing each term by 15:
2x+y=8
So, you now have your two equations and can solve:
x+y=5
2x+y=8
Isolate the x variable in the first equation:
x+y=5
x=5-y
Now, substitute this expression ofx into the second equation and solve for y:
2x+y=8
2(5-y)+y=8
10-2y+y=8
10-y=8
-y=-2
y=2
So, she babysits for 2 hours each week. Now, you can use this information to solve for x using the first equation:
x+y=5
x+2=5
x=3
So, she tutors for 3 hours each week.
4. C
Challenging GED Algebra Word Problems
Your first step is to find out how many grams of flour Oliver uses. He uses 340 grams per batch of biscuits, and he makes three batches. So, you need to calculate:
3(340)=1,020
He uses 1,020 grams. But, you cannot simply subtract this from the total mass of the bag of flour, because the bag of flour is stated in kilograms. Since the question asks for the amount of flour left in grams, you should convert the total mass of the bag of flour to grams. 1,000 grams are equal to 1 kilogram. To convert, multiply 2.27 by 1000.
2.27(1000)= 2270 grams
Now, subtract the amount of grams of flour Oliver used from the total grams in the bag of flour:
2,270-1,020=1,250
5. A
This seems like a system of equations because there are multiple unknown amounts, and you COULD solve it that way, but you would need three equations so it would get a little complicated. In this case, though, there’s an easier way. Since the number of rings and necklaces Iris sells is given in terms relative to the number of bracelets she sells, you really only have one unknown variable: the number of bracelets Iris sells.
Let the number of bracelets Iris sells be x. You know she sells each bracelet for $5. So, the amount of money she makes from bracelets is given by the expression 5x. Iris sells twice as many rings as bracelets. So, the number of rings she will sell is 2x. You know she sells each ring for $10. So, the amount of money she makes from rings is given by the expression 10(2x). Iris sells three more necklaces than bracelets. So, the number of necklaces she sells is x+3. You know she sells each necklace for $15. So, the amount of money she makes from necklaces is given by the expression
It might help to make a table to help you organize all of the information in this problem. Fill out the table as you parse each piece of information in the problem.
Information Mathematical Expression
number of bracelets sold x
price of each bracelet$5
money received for bracelets5x
number of rings sold 2x
price of each ring $10
money received for rings 10(2x) = 20x
number of necklaces sold x+3
price of each necklace$15
money received for necklaces 15(x+3)=15x+45
You know that in total she made $245 at the craft fair. So, the sum of the money received for bracelets, rings, and necklaces, will equal 245:
5x+20x+15x+45=245
So, you have one equation that you can solve for x, which is the number of bracelets sold:
5x+20x+15x+45=245
40x+45=245
40x=200
x=5
Remember that x equals the number of bracelets sold. The problem asks you to find the number of bracelets, rings, and necklaces sold. Since the number of each type of jewelry sold is given in relative terms, once you know the number of bracelets sold, you can find the number of rings and necklaces sold.
The number of rings sold is 2x, so 2x=2(5)=10.
The number of necklaces sold is x+3, so x+3=5+3=8.
The post Challenging GED Algebra Word Problems appeared first on Magoosh GED Blog.
]]>
https://magoosh.com/ged/challenging-ged-algebra-word-problems/feed/ 2
GED Algebra Prep https://magoosh.com/ged/ged-algebra-prep/ https://magoosh.com/ged/ged-algebra-prep/#respond Tue, 18 Apr 2017 20:52:32 +0000 https://magoosh.com/ged/?p=355 Today, we’re covering the basics for GED algebra prep. Algebra makes up a large portion of the GED Mathematical Reasoning exam.
The post GED Algebra Prep appeared first on Magoosh GED Blog.
]]>
Today, we’re covering the basics for GED algebra prep. Algebra makes up a large portion of the GED Mathematical Reasoning exam, so you’ll want to make sure you have a handle on it going in to test day.
Algebra deals with formulas and unknown values. An unknown value is represented by a variable. Often you will see the variables x and y, but any letter or symbol can be a variable.
Solving Basic Equations (1 variable)
Solving an algebraic equation means to find the values of the variables. The simplest types of equations to solve are those with only one variable.
To solve an equation with one variable, your goal is to isolate the variable. This means to get the variable alone on one side of the equation. How do you do this? By using inverse operations to undo what is being done in the equation.
You might think of inverse operations as being opposites. Each inverse operation undoes whatever its partner does. There are two sets of inverse operations:
• addition and subtraction
• multiplication and division
Solving One-Step Equations
Let’s see how these inverse operations work to isolate the variable in a very basic algebra equation:
x-4=0
This equation is saying that some unknown amount (x), minus 4, is equal to 0. To find the value of x, you need to isolate it, or get it on one side of the equation by itself. Right now it is on the same side as minus 4. To get rid of that minus 4, you need to add 4. But:
• IMPORTANT! Whatever you do to one side of an equation, you must also do to the other side.
If you add 4 to the left side of the equation, you also need to add 4 to the right side of the equation:
x-4+4=0+4
Here’s what adding 4 does to both sides of the equation:
• On the left side, if you add 4 to a negative 4, you get 0, which is nothing, which means you have met your goal of isolating the variable.
• On the right side, if you add 4 to 0, you get 4.
So, you end up with:
x=4
And the equation is solved.
Solving Two-Step Equations
A two-step equation still only has one variable, but it involves two steps to isolate the variable. Here’s an example:
3x+2=14
Isolating x in this equation involves two steps:
1. Eliminating the plus 2 on the left side.
2. Eliminating the coefficient 3 on the left side. (A coefficient is the number a variable is being multiplied by.)
Step 1
To eliminate the plus 2, you need to subtract 2 from both sides of the equation. Here’s what that looks like:
3x+2=14
3x+2-2=14-2
3x=12
Step 2
To eliminate the coefficient 3, you need to divide each side of the equation by 3. Here’s what that looks like:
3x=12
3x÷3=12÷3
x=4
You’ve now isolated the variable, and so the equation is solved.
Solving Basic Inequalities (1 variable)
Inequalities are used to compare quantities. There are 4 basic inequality signs:
>Greater than
Greater than or equal to
<Less than
Less than or equal to
Inequalities are solved similarly to equations, with one very important exception:
• IMPORTANT! Whenever you multiply or divide by a negative number, you must flip the inequality sign.
Otherwise, complete the same steps to solve an inequality as you would an equation.
Here’s an example:
2-7x>16
Solving this inequality has three steps:
1. Eliminating the 2 on the left side
2. Eliminating the -7 on the left side
3. Flipping the inequality sign
Step 1
To eliminate the 2, you need to subtract 2 from both sides of the equation:
2-7x>16
2-2-7x>16-2
-7x>14
Step 2
To eliminate the -7, you need to divide both sides of the equation by -7:
-7x>14
(-7x)÷(-7)>14÷(-7)
x>-2
Step 3
Since you divided by a negative number in the previous step, you need to flip the inequality sign:
x>-2
x<-2
Solving System of Equations (2 variables)
A system of equations is a set of related equations that you work simultaneously to solve. The equations will contain two variables, for example, x and y. Since you can’t find two unknown variables in one equation, a system of equations is such that you need both equations to find both variables.
Solving a system of equations with two variables involves three steps:
1. Isolate x in the first equation, finding an expression that describes it.
2. Substitute the expression of x into the second equation, solving for y.
3. Substitute the value of y into either equation, finding the value of x.
Here’s an example:
4y+8=4x
2y+9=3x
Step 1
To isolate x in the first equation, divide both sides by 4 (remember to divide EVERY term by 4):
4y+8=4x
y+2=x
Step 2
Now, substitute the expression describing x into the second equations:
2y+9=3x
2y+9=3(y+2)
To solve for y, first use the distributive property to remove the parentheses:
2y+9=3y+6
Then, subtract 9 from both sides:
2y+9=3y+6
2y=3y-3
Next, subtract 3y from both sides:
2y=3y-3
-y=-3
Finally, divide both sides by -1:
-y=-3
y=3
Step 3
Now that you know the value of y, you can substitute this value into either equation and solve for x:
4y+8=4x
4(3)+8=4x
12+8=4x
20=4x
5=x
Now you know the value of both variables, and the system of equations is solved.
Working with Polynomials
Polynomials are expressions with more than one term. A term can be a variable, number, or exponent. You can add, subtract, multiply, and divide polynomials. You will also have occasions when you will need to factor polynomials.
Adding Polynomials
Follow two steps to add polynomials:
1. Rearrange the polynomials by like terms.(Like terms are terms that have the same variable and exponent.)
2. Combine like terms by adding them.
When adding (and also when subtracting, multiplying, or dividing) polynomials, the goal is not to find the value of variables, but to combine the two polynomials into one simplified polynomial.
For example:
(3x2-5x+4)+ (-5x2+9x-3)
Step 1
Rearrange the two polynomials into one polynomial, grouping like terms together:
3x2-5x+4 -5x2+9x-3
3x2-5x2-5x+9x+4-3
Step 2
Simplify the expression by combining like terms:
3x2-5x2-5x+9x+4-3
-2x2-5x+9x+4-3
-2x2+4x+4-3
-2x2+4x+1
Subtracting Polynomials
Subtracting polynomials is similar to the adding process, except for one important difference in the first step:
1. Reverse the signs in the polynomial you are subtracting. This means turning positive signs into negative signs, and vice versa.
2. Rearrange the polynomials by like terms.
3. Combine like terms by adding them.
For example, to subtract these polynomials, follow the steps below:
(3x2-5x+4)- (-5x2+9x-3)
3x2-5x+4+5x2-9x+3
3x2+5x2-5x-9x+4+3
8x2-5x-9x+4+3
8x2-14x+4+3
8x^2 -14x +7
Multiplying Polynomials
To multiply polynomials, you need to multiply each term of the first polynomial by each term of the second polynomial. One most common type of polynomial multiplication you’ll see on the GED is the multiplication of binomials, which you do using these 5 steps:
1. Multiply the first terms of each binomial.
2. Multiply the outer terms of each binomial. This means the first term in the first binomial, and the second term in the second binomial.
3. Multiply the inner terms of each binomial. This means the second term in the first binomial, and the first term in the second binomial.
4. Multiply the last terms of each binomial.
5. Combine like terms.
ALGEBRA TIP: Use the acronym FOIL (first, outer, inner, last) to help you remember the order of multiplication when multiplying binomials.
For example:
(2x+3)(3x-5)
Step 1
Multiply the first terms of each binomial:
(2x+3)(3x-5)
(2x)(3x)=6x2
Step 2
Multiply the outer terms of each binomial:
(2x+3)(3x-5)
(2x)(-5)=-10x
Step 3
Multiply the inner terms of each binomial:
(2x+3)(3x-5)
(3)(3x)=9x
Step 4
Multiply the last terms of each binomial:
(2x+3)(3x-5)
(3)(-5)=-15
Step 5
Combine like terms to simplify the expression.
6x2-10x+9x-15
6x2-x-15
Dividing Polynomials
Dividing polynomials usually involves two steps:
1. Split the numerator. This will result in multiple fractions instead of one. Each fraction will have the same denominator. Each numerator will be one of the terms in the numerator.
2. Simplify each fraction.
For example:
GED Algebra Prep- Dividing polynomials- Magoosh
Step 1
Split the numerator. Each term will become a separate numerator. Each fraction will have a denominator of 5x:
GED Algebra Prep- Dividing polynomials step 1- Magoosh
Step 2
Simplify the first fraction:
GED Algebra Prep- Dividing polynomials step 2a- Magoosh
Then, simplify the second fraction.
GED Algebra Prep- Dividing polynomials step 2b- Magoosh
Factoring Polynomials
There are numerous methods for factoring the numerous types of polynomials. The most basic method, however, is to find the greatest common factor (GCF) of all the terms in the polynomial.
• IMPORTANT! The GCF must be common to each term in the polynomial, including terms without variables. For example, 4x is not a factor of 4. On the other hand, 4 IS a factor of 4x.
Factoring a polynomial in this way has three steps:
1. Identify the GCF for ALL terms.
2. Pull out the GCF.
3. Put the remaining factors in parentheses.
For example:
12x3-8x2+4x
Step 1
The greatest common factor is 4x, since 4x divides evenly into each term.
Step 2
To set up the factorization, pull out the GCF, and set it outside a set of parentheses:
4x( )
Step 3
Go through the polynomial term-by-term, determining which factor remains after pulling out 4x. In other words, ask yourself, what do I have to multiply by 4x to get the original term in the polynomial?
For the first term:(4x)(3x2)=12x3
For the second term:(4x)(-2x)=-8x2
For the third term:(4x)(1)=4x
Put these three terms into the parentheses with the GCF out front: 4x(3x2-2x+1)
Next Steps
Learn more about what’s on the GED math test.
Put your algebra skills to the test with some math practice questions.
Try tackling another math topic, such as geometry, probability, or data analysis.
The post GED Algebra Prep appeared first on Magoosh GED Blog.
]]>
https://magoosh.com/ged/ged-algebra-prep/feed/ 0
Top 10 GED Practice Questions https://magoosh.com/ged/top-10-ged-practice-questions/ https://magoosh.com/ged/top-10-ged-practice-questions/#comments Fri, 31 Mar 2017 16:49:22 +0000 https://magoosh.com/ged/?p=388 Here are 10 GED practice questions, taken from each of the four GED subject tests, that cover some of the most commonly-tested topics.
The post Top 10 GED Practice Questions appeared first on Magoosh GED Blog.
]]>
Top 10 GED Practice Questions
Need a little practice with every area of the GED? Here are 10 questions, taken from each of the four GED subject tests, that cover some of the most commonly-tested topics. Give these GED practice questions a try (answer key at the end of the post).
GED Practice Questions
Reasoning Through Language Arts
Questions 1-2 are based on the following passage, which is adapted from the autobiography A Backward Glance by Edith Wharton (1934).
Years ago I said to myself: “There’s no such thing as old age; there is only sorrow.”
I have learned with the passing of time that this, though true, is not the whole truth. The other producer of old age is habit: the deathly process of doing the same thing in the same way at the same hour day after day, first from carelessness, then from inclination, at last from cowardice or inertia. Luckily the inconsequent life is not the only alternative; for caprice is as ruinous as routine. Habit is necessary; it is the habit of having habits, of turning a trail into a rut, that must be incessantly fought against if one is to remain alive.
In spite of illness, in spite even of the arch-enemy sorrow, one CAN remain alive long past the usual date of disintegration if one is unafraid of change, insatiable in intellectual curiosity, interested in big things, and happy in small ways. In the course of sorting and setting down of my memories I have learned that these advantages are usually independent of one’s merits, and that I probably owe my happy old age to the ancestor who accidentally endowed me with these qualities.
1. One of the author’s secrets to longevity is
A) maintaining a regimented schedule.
B) avoiding unnecessary risks.
C) accepting change without fear.
D) living capriciously.
2. Wharton’s overall attitude toward her own aging can best be described as
A) resignation.
B) contentment.
C) resentment.
D) cowardice.
3. Choose the option that correctly completes the sentence.
_________________ how to create an effective advertising campaign.
A) Jason knows because of his background in marketing
B) With his background in marketing, Jason knows
C) Having a background in marketing, this is why Jason knows
D) With having a background in marketing Jason knows
Mathematical Reasoning
4. The area of a circle is 289π cm2. What is the diameter of the circle? ______ cm2
5. A pair of jeans originally priced at $60.00 is on sale for 30% off. If there is 5% sales tax, what is the final price of the jeans?
A) $18.90
B) $39.00
C) $39.90
D) $44.10
6. What is the slope of the line with the equation y + 3x=2?
A) -3
B) -2
C) 2
D) 3
Social Studies
Questions 7-8 are based on the following excerpt adapted from the fourth inaugural address of President Franklin D. Roosevelt. Roosevelt delivered this speech in January 1945, as the United States entered what would be the final year of World War II.
“We Americans of today, together with our allies, are passing through a period of supreme test. It is a test of our courage, of our resolve, of our wisdom—our essential democracy. If we meet that test—successfully and honorably—we shall perform a service of historic importance which men and women and children will honor throughout all time.
In the days and in the years that are to come we shall work for a just and honorable peace, a durable peace, as today we work and fight for total victory in war. We can and we will achieve such a peace. We shall strive for perfection. We shall not achieve it immediately, but we still shall strive. We may make mistakes, but they must never be mistakes which result from faintness of heart or abandonment of moral principle.
Our Constitution of 1787 was not a perfect instrument; it is not perfect yet. But it provided a firm base upon which all manner of men, of all races and colors and creeds, could build our solid structure of democracy. And so today, in this year of war, 1945, we have learned lessons—at a fearful cost—and we shall profit by them.
We have learned that we cannot live alone, at peace; that our own well-being is dependent on the well-being of other nations far away. We have learned that we must live as men, not as ostriches, nor as dogs in the manger. We have learned to be citizens of the world, members of the human community. We have learned the simple truth, as Emerson said, that “The only way to have a friend is to be one.” We can gain no lasting peace if we approach it with suspicion and mistrust or with fear. We can gain it only if we proceed with the understanding, the confidence, and the courage which flow from conviction.”
7. Roosevelt argues that peace
A) is currently being negotiated.
B) is inevitable in near future.
C) must be worked for over time.
D) is impossible to achieve in the long term.
8. According to Roosevelt, World War II showed America that
A) alliances with other nations should be avoided.
B) isolationism is not a sustainable policy.
C) it should avoid involvement in foreign conflicts.
D) the Constitution is an imperfect document.
Science
Questions 9-10 are based on the following information and diagram.
Food chains describe the way energy moves through an ecosystem. Plants act as producers, using photosynthesis to make their own food using light from the sun and nutrients from the soil. Animals are known as consumers because instead of producing their own food, they consume other organisms. Those that eat producers are called primary consumers. Animals that eat primary consumers are called secondary consumers, those that eat secondary consumers are called tertiary consumers, and so on. When organisms die, decomposers (e.g., worms) eat their remains and help return nutrients to the soil so that the cycle can begin again.
GED Practice Questions- Food chain- Magoosh
Image by LadyofHats.
9. Which organism in the food chain is a tertiary consumer?
A) Hawk
B) Frog
C) Plant
D) Snake
10. Which type of organism is missing from the ecosystem shown in the food chain diagram?
A) Producer
B) Primary consumer
C) Secondary consumer
D) Decomposer
Answer Key
1. C
In the last paragraph, the author lists ways that a person “can remain alive long past the usual date of disintegration.” Among these is being “unafraid of change.”
2. B
In the last paragraph, Wharton speaks of her “happy old age.” It seems she has found contentment in aging and is satisfied with her life.
3. B
Choice B correctly joins a dependent clause with a comma to an independent clause.
4. 34
Work backwards from the area formula.
A=π r2
289π=π r2
289=r2
17=r
Now that you have the radius, multiply by 2 to find the diameter.
17(2)=34
5. D
The jeans were originally $60.00 and are now 30% off. 30% of $60.00 is 60(.30) = 18. Subtract from $60.00 to find the sale price before tax.
60.00 – 18.00 = $42.00
Now you need to figure out and add in the sales tax.
42.00(.05) = $2.10
This is the amount of the tax. Add it to $42.00 to find the total price of the jeans.
$42.00 + $2.10 = $44.10
6. A
Rearrange the equation into y=mx+b form.
y+3x=2
y=-3x+2
When an equation is in this form, the slope is equal to m (the coefficient of x). Therefore, the slope is -3.
7. C
In the second paragraph, Roosevelt speaks of peace as something that Americans will work for “in the days and years to come.” He views it as achievable, but it will be a long, difficult process.
8. B
In the last paragraph, Roosevelt speaks to the importance of international cooperation. He states that Americans have learned that they cannot behave like ostriches—hiding their heads in the sand, oblivious to the outside world. America tried to follow an isolationist policy and stay out of World War II, but eventually found itself drawn into the conflict. Roosevelt says that the lesson is that nations must work together and not merely focus on their own self-interests.
9. B
Starting at the bottom, the first organism (the plant) is a producer, and the rest are consumers, listed in numerical order. The tertiary (third) consumer is the frog.
10. D
There is no decomposer in the diagram. A decomposer’s role is to consume and digest dead organisms, returning nutrients to the soil through their waste.
The post Top 10 GED Practice Questions appeared first on Magoosh GED Blog.
]]>
https://magoosh.com/ged/top-10-ged-practice-questions/feed/ 1 | __label__pos | 0.989432 |
summaryrefslogtreecommitdiff
blob: a56c09092f914e558ff7629566c2d164baa1f6a4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
# Copyright 1999-2021 Gentoo Authors
# Distributed under the terms of the GNU General Public License v2
EAPI=7
CMAKE_ECLASS=cmake
inherit cmake-multilib systemd
DESCRIPTION="Software real-time synthesizer based on the Soundfont 2 specifications"
HOMEPAGE="https://www.fluidsynth.org"
SRC_URI="https://github.com/FluidSynth/${PN}/archive/v${PV}.tar.gz -> ${P}.tar.gz"
LICENSE="LGPL-2.1+"
SLOT="0/2"
KEYWORDS="~alpha ~amd64 ~arm ~arm64 ~hppa ~ppc ~ppc64 ~sparc ~x86"
IUSE="alsa dbus debug examples ipv6 jack ladspa lash network oss portaudio pulseaudio +readline sdl +sndfile systemd threads"
BDEPEND="
virtual/pkgconfig
"
DEPEND="
dev-libs/glib:2[${MULTILIB_USEDEP}]
alsa? (
media-libs/alsa-lib[${MULTILIB_USEDEP}]
lash? ( media-sound/lash[${MULTILIB_USEDEP}] )
)
dbus? ( sys-apps/dbus[${MULTILIB_USEDEP}] )
jack? ( virtual/jack[${MULTILIB_USEDEP}] )
ladspa? (
media-libs/ladspa-sdk[${MULTILIB_USEDEP}]
media-plugins/cmt-plugins[${MULTILIB_USEDEP}]
)
portaudio? ( media-libs/portaudio[${MULTILIB_USEDEP}] )
pulseaudio? ( media-sound/pulseaudio[${MULTILIB_USEDEP}] )
readline? ( sys-libs/readline:0=[${MULTILIB_USEDEP}] )
sdl? ( media-libs/libsdl2[${MULTILIB_USEDEP}] )
sndfile? ( media-libs/libsndfile[${MULTILIB_USEDEP}] )
"
RDEPEND="${DEPEND}"
DOCS=( AUTHORS ChangeLog README.md THANKS TODO doc/fluidsynth-v20-devdoc.txt )
src_configure() {
local mycmakeargs=(
-Denable-alsa=$(usex alsa)
-Denable-aufile=ON
-Denable-dbus=$(usex dbus)
-Denable-debug=$(usex debug)
-Denable-dsound=OFF # Windows
-Denable-floats=OFF # loat instead of double for DSP samples
-Denable-fpe-check=$(usex debug)
-Denable-ipv6=$(usex ipv6)
-Denable-jack=$(usex jack)
-Denable-ladspa=$(usex ladspa)
-Denable-libinstpatch=ON # https://github.com/swami/libinstpatch
-Denable-midishare=OFF # http://midishare.sourceforge.net/
-Denable-network=$(usex network)
-Denable-opensles=OFF
-Denable-oboe=OFF # requires OpenSLES and/or AAudio
-Denable-oss=$(usex oss)
-Denable-libsndfile=$(usex sndfile)
-Denable-pkgconfig=ON
-Denable-portaudio=$(usex portaudio)
-Denable-profiling=$(usex debug)
-Denable-pulseaudio=$(usex pulseaudio)
-Denable-readline=$(usex readline)
-Denable-sdl2=$(usex sdl)
-Denable-systemd=$(usex systemd)
-Denable-threads=$(usex threads)
-Denable-trap-on-fpe=$(usex debug)
-Denable-ubsan=OFF # compile and link against UBSan (for debugging fluidsynth internals)
-Denable-waveout=OFF # Windows
-Denable-winmidi=OFF # Windows
)
if use alsa; then
mycmakeargs+=( -Denable-lash=$(usex lash) )
else
mycmakeargs+=( -Denable-lash=OFF )
fi
if use systemd; then
mycmakeargs+=( -DFLUID_DAEMON_ENV_FILE="/etc/fluidsynth.conf" )
fi
cmake-multilib_src_configure
}
install_systemd_files() {
if multilib_is_native_abi; then
systemd_dounit "${BUILD_DIR}/fluidsynth.service"
insinto /etc
doins "${BUILD_DIR}/fluidsynth.conf"
fi
}
src_install() {
cmake-multilib_src_install
docinto pdf
dodoc doc/*.pdf
if use examples; then
docinto examples
dodoc doc/examples/*.c
fi
if use systemd; then
multilib_foreach_abi install_systemd_files
elog "When using fluidsynth as a systemd service, make sure"
elog "to configure your fluidsynth settings globally in "
elog "/etc/fluidsynth.conf or per-user in ~/.config/fluidsynth"
fi
} | __label__pos | 0.546513 |
Great vSphere API ever: Part -I : placevm() API which places the VM on best possible host and datastore
This is the vSphere API personally I was waiting for since long days, I believe this is one of the powerful vSphere APIs ever. The API I am talking about is introduced as part of vSphere 6.0 i.e. placevm(). Here is the API reference for the same.
Why this API is so powerful?
-Basically this API helps to place the VM on appropriate host and datastore. Placing the VM can be as part of creating the VM, relocating the VM, cloning the VM or re-configuring the existing VM.
-How does this API achieves the best host from CPU and Memory perspective and datastore from storage perspective? As per API reference, this API can be invoked to ask DRS (Distributed resource scheduler) for a set of recommendations for placing a virtual machine and its virtual disks into a DRS cluster.
-This API offers so much flexibility that, from storage perspective, it can take input as set of datastores of our choice as well as set of SDRS (Storage DRS) PODs, we can even specify one particular datastore of our choice. From compute perspective, it takes set of hosts or particular host as input. How cool is that when DRS is involved and SDRS POD(s)?
-It also gives us flexibility on not to specify any hosts as well as datastores, in that case, it automatically picks all the hosts inside the DRS cluster and all the datastores connected to hosts inside the cluster.
– Another beauty of this API is, it works perfectly with SPBM (Storage Policy Based Management) as well as across vCenter server. is not it something great capability into single API?
Lets learn now how to use this API in real time. For the sake simplicity I have divided this post into 2 parts.
Part I: How to relocate a Powered ON VM from a DRS enabled cluster to another DRS enabled cluster (One SDRS POD as input) within single vCenter
Part II: How to relocate a Powered ON VM from a DRS enabled cluster to another DRS enabled cluster (Multiple SDRS PODs as input) across vCenter.
Below is the placeVM API sample that achieves the Part I where we invoke placeVM API to get the set of recommendations for VM (cpu, mem, storage) and then we invoke RelocateVM API to apply one of the first recommendations.
Same sample is available on my git hub repository as well as on VMware Sample exchange
//:: # Author: Vikas Shitole
//:: # Website: www.vThinkBeyondVM.com
//:: # Product/Feature: vCenter Server/DRS
//:: # Reference:
//:: # Description: Tutorial: PlaceVM API: Live relocate a VM from one DRS cluster to another DRS cluster (in a Datacenter or across Datacenter)
//:: # How cool is it when DRS takes care of placement from cpu/mem perspective and at the same time SDRS take care of storage placement
//::# How to run this sample: http://vthinkbeyondvm.com/getting-started-with-yavi-java-opensource-java-sdk-for-vmware-vsphere-step-by-step-guide-for-beginners/
package com.vmware.yavijava;
import java.net.MalformedURLException;
import java.net.URL;
import com.vmware.vim25.ClusterAction;
import com.vmware.vim25.ClusterRecommendation;
import com.vmware.vim25.ManagedObjectReference;
import com.vmware.vim25.PlacementAction;
import com.vmware.vim25.PlacementResult;
import com.vmware.vim25.PlacementSpec;
import com.vmware.vim25.VirtualMachineMovePriority;
import com.vmware.vim25.VirtualMachineRelocateSpec;
import com.vmware.vim25.mo.ClusterComputeResource;
import com.vmware.vim25.StoragePlacementSpecPlacementType;
import com.vmware.vim25.mo.Datacenter;
import com.vmware.vim25.mo.Datastore;
import com.vmware.vim25.mo.Folder;
import com.vmware.vim25.mo.HostSystem;
import com.vmware.vim25.mo.InventoryNavigator;
import com.vmware.vim25.mo.ManagedEntity;
import com.vmware.vim25.mo.ResourcePool;
import com.vmware.vim25.mo.ServiceInstance;
import com.vmware.vim25.mo.StoragePod;
import com.vmware.vim25.mo.VirtualMachine;
public class PlaceVMRelocate {
public static void main(String[] args) throws Exception {
if(args.length!=3)
{
System.out.println("Usage: PlaceVMRelocate url username password");
System.exit(-1);
}
URL url = null;
try
{
url = new URL(args[0]);
} catch ( MalformedURLException urlE)
{
System.out.println("The URL provided is NOT valid. Please check it...");
System.exit(-1);
}
String username = args[1];
String password = args[2];
String SourceClusterName = "Cluster1"; //Source cluster Name, It is not required to have DRS enabled
String DestinationClusterName="Cluster2"; //Destination cluster with DRS enabled
String SDRSClusterName1="POD_1"; //SDRS POD
String VMTobeRelocated="VM2"; //VM Name to be relocated to other cluster
ManagedEntity[] hosts=null;
// Initialize the system, set up web services
ServiceInstance si = new ServiceInstance(url, username,
password, true);
if(si==null){
System.out.println("ServiceInstance Returned NULL, please check your vCenter is up and running ");
}
Folder rootFolder = si.getRootFolder();
ManagedObjectReference folder=rootFolder.getMOR();
StoragePod pod1=null;
//Getting datacenter object
Datacenter dc=(Datacenter) new InventoryNavigator(rootFolder)
.searchManagedEntity("Datacenter", "vcqaDC");
//Getting SDRS POD object
pod1=(StoragePod) new InventoryNavigator(rootFolder)
.searchManagedEntity("StoragePod", SDRSClusterName1);
ManagedObjectReference podMor1=pod1.getMOR();
ManagedObjectReference[] pods={podMor1};
//Getting source cluster object, It is NOT needed to enable DRS on source cluster
ClusterComputeResource cluster1 = null;
cluster1 = (ClusterComputeResource) new InventoryNavigator(rootFolder)
.searchManagedEntity("ClusterComputeResource", SourceClusterName);
//Getting VM object to be relocated
VirtualMachine vm=null;
vm=(VirtualMachine) new InventoryNavigator(cluster1)
.searchManagedEntity("VirtualMachine", VMTobeRelocated);
ManagedObjectReference vmMor=vm.getMOR();
//Getting destination cluster object, DRS must be enabled on the destination cluster
ClusterComputeResource cluster2 = null;
cluster2 = (ClusterComputeResource) new InventoryNavigator(rootFolder)
.searchManagedEntity("ClusterComputeResource", DestinationClusterName);
ManagedObjectReference cluster2Mor=cluster2.getMOR();
//Getting all the host objects from destination cluster.
hosts = new InventoryNavigator(cluster2).searchManagedEntities("HostSystem");
System.out.println("Number of hosts in the destination cluster::" + hosts.length);
ManagedObjectReference[] hostMors=new ManagedObjectReference[hosts.length];
int i=0;
for(ManagedEntity hostMor: hosts){
hostMors[i]=hostMor.getMOR();
i++;
}
//Building placement Spec to be sent to PlaceVM API
PlacementSpec placeSpec=new PlacementSpec();
placeSpec.setPlacementType(StoragePlacementSpecPlacementType.relocate.name());
placeSpec.setPriority(VirtualMachineMovePriority.highPriority);
// placeSpec.setDatastores(dss); //We can pass array of datastores of choice as well
placeSpec.setStoragePods(pods); // Destination storage SDRS POD (s)
placeSpec.setVm(vmMor); //VM to be relocated
placeSpec.setHosts(hostMors); //Destination DRS cluster hosts/ We can keep this unset as well
placeSpec.setKey("xvMotion placement");
VirtualMachineRelocateSpec vmrelocateSpec=new VirtualMachineRelocateSpec();
vmrelocateSpec.setPool(cluster2.getResourcePool().getMOR()); //Destination cluster root resource pool
vmrelocateSpec.setFolder(dc.getVmFolder().getMOR()); //Destination Datacenter Folder
placeSpec.setRelocateSpec(vmrelocateSpec);
PlacementResult placeRes= cluster2.placeVm(placeSpec);
System.out.println("PlaceVM() API is called");
//Getting all the recommendations generated by placeVM API
ClusterRecommendation[] clusterRec=placeRes.getRecommendations();
ClusterAction[] action= clusterRec[0].action;
VirtualMachineRelocateSpec vmrelocateSpecNew=null;
vmrelocateSpecNew=((PlacementAction) action[0]).getRelocateSpec();
vm.relocateVM_Task(vmrelocateSpecNew, VirtualMachineMovePriority.highPriority);
si.getServerConnection().logout();
}
}
Notes:
– For the sake of simplicity I have hardcoded some variables, you can change as per your environment
– We can leverage this sample either within a single vCenter datacenter or across vCenter datacenters.
– All the required documentation is added inside the sample itself. Source cluster need not to be DRS enabled.
-Same Sample can used not only for relocate ops but also clone, create and reconfigure VM Ops.
If you have still not setup your YAVI JAVA Eclipse environment:Getting started tutorial
Important tutorials to start with: Part I & Part II
Leave a Reply
Your email address will not be published. | __label__pos | 0.537945 |
View Javadoc
1 /**
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements. See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership. The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License. You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 */
18 package org.apache.hadoop.hbase.zookeeper;
19
20 import java.io.IOException;
21 import java.io.InterruptedIOException;
22 import java.io.UnsupportedEncodingException;
23 import java.net.URLDecoder;
24 import java.net.URLEncoder;
25 import java.util.List;
26
27 import org.apache.commons.logging.Log;
28 import org.apache.commons.logging.LogFactory;
29 import org.apache.hadoop.fs.FileSystem;
30 import org.apache.hadoop.fs.Path;
31 import org.apache.hadoop.hbase.HConstants;
32 import org.apache.hadoop.hbase.classification.InterfaceAudience;
33 import org.apache.hadoop.hbase.exceptions.DeserializationException;
34 import org.apache.hadoop.hbase.shaded.protobuf.generated.ClusterStatusProtos.RegionStoreSequenceIds;
35 import org.apache.zookeeper.KeeperException;
36
37 /**
38 * Common methods and attributes used by {@link org.apache.hadoop.hbase.master.SplitLogManager}
39 * and {@link org.apache.hadoop.hbase.regionserver.SplitLogWorker}
40 * running distributed splitting of WAL logs.
41 */
42 @InterfaceAudience.Private
43 public class ZKSplitLog {
44 private static final Log LOG = LogFactory.getLog(ZKSplitLog.class);
45
46 /**
47 * Gets the full path node name for the log file being split.
48 * This method will url encode the filename.
49 * @param zkw zk reference
50 * @param filename log file name (only the basename)
51 */
52 public static String getEncodedNodeName(ZooKeeperWatcher zkw, String filename) {
53 return ZKUtil.joinZNode(zkw.znodePaths.splitLogZNode, encode(filename));
54 }
55
56 public static String getFileName(String node) {
57 String basename = node.substring(node.lastIndexOf('/') + 1);
58 return decode(basename);
59 }
60
61 static String encode(String s) {
62 try {
63 return URLEncoder.encode(s, "UTF-8");
64 } catch (UnsupportedEncodingException e) {
65 throw new RuntimeException("URLENCODER doesn't support UTF-8");
66 }
67 }
68
69 static String decode(String s) {
70 try {
71 return URLDecoder.decode(s, "UTF-8");
72 } catch (UnsupportedEncodingException e) {
73 throw new RuntimeException("URLDecoder doesn't support UTF-8");
74 }
75 }
76
77 public static String getRescanNode(ZooKeeperWatcher zkw) {
78 return ZKUtil.joinZNode(zkw.znodePaths.splitLogZNode, "RESCAN");
79 }
80
81 /**
82 * @param name the last part in path
83 * @return whether the node name represents a rescan node
84 */
85 public static boolean isRescanNode(String name) {
86 return name.startsWith("RESCAN");
87 }
88
89 /**
90 * @param zkw
91 * @param path the absolute path, starts with '/'
92 * @return whether the path represents a rescan node
93 */
94 public static boolean isRescanNode(ZooKeeperWatcher zkw, String path) {
95 String prefix = getRescanNode(zkw);
96 if (path.length() <= prefix.length()) {
97 return false;
98 }
99 for (int i = 0; i < prefix.length(); i++) {
100 if (prefix.charAt(i) != path.charAt(i)) {
101 return false;
102 }
103 }
104 return true;
105 }
106
107 public static boolean isTaskPath(ZooKeeperWatcher zkw, String path) {
108 String dirname = path.substring(0, path.lastIndexOf('/'));
109 return dirname.equals(zkw.znodePaths.splitLogZNode);
110 }
111
112 public static Path getSplitLogDir(Path rootdir, String tmpname) {
113 return new Path(new Path(rootdir, HConstants.SPLIT_LOGDIR_NAME), tmpname);
114 }
115
116
117 public static String getSplitLogDirTmpComponent(final String worker, String file) {
118 return worker + "_" + ZKSplitLog.encode(file);
119 }
120
121 public static void markCorrupted(Path rootdir, String logFileName,
122 FileSystem fs) {
123 Path file = new Path(getSplitLogDir(rootdir, logFileName), "corrupt");
124 try {
125 fs.createNewFile(file);
126 } catch (IOException e) {
127 LOG.warn("Could not flag a log file as corrupted. Failed to create " +
128 file, e);
129 }
130 }
131
132 public static boolean isCorrupted(Path rootdir, String logFileName,
133 FileSystem fs) throws IOException {
134 Path file = new Path(getSplitLogDir(rootdir, logFileName), "corrupt");
135 boolean isCorrupt;
136 isCorrupt = fs.exists(file);
137 return isCorrupt;
138 }
139
140 /*
141 * Following methods come from SplitLogManager
142 */
143
144 /**
145 * check if /hbase/recovering-regions/<current region encoded name>
146 * exists. Returns true if exists and set watcher as well.
147 * @param zkw
148 * @param regionEncodedName region encode name
149 * @return true when /hbase/recovering-regions/<current region encoded name> exists
150 * @throws KeeperException
151 */
152 public static boolean
153 isRegionMarkedRecoveringInZK(ZooKeeperWatcher zkw, String regionEncodedName)
154 throws KeeperException {
155 boolean result = false;
156 String nodePath = ZKUtil.joinZNode(zkw.znodePaths.recoveringRegionsZNode, regionEncodedName);
157
158 byte[] node = ZKUtil.getDataAndWatch(zkw, nodePath);
159 if (node != null) {
160 result = true;
161 }
162 return result;
163 }
164
165 /**
166 * @param bytes - Content of a failed region server or recovering region znode.
167 * @return long - The last flushed sequence Id for the region server
168 */
169 public static long parseLastFlushedSequenceIdFrom(final byte[] bytes) {
170 long lastRecordedFlushedSequenceId = -1l;
171 try {
172 lastRecordedFlushedSequenceId = ZKUtil.parseWALPositionFrom(bytes);
173 } catch (DeserializationException e) {
174 lastRecordedFlushedSequenceId = -1l;
175 LOG.warn("Can't parse last flushed sequence Id", e);
176 }
177 return lastRecordedFlushedSequenceId;
178 }
179
180 public static void deleteRecoveringRegionZNodes(ZooKeeperWatcher watcher, List<String> regions) {
181 try {
182 if (regions == null) {
183 // remove all children under /home/recovering-regions
184 LOG.debug("Garbage collecting all recovering region znodes");
185 ZKUtil.deleteChildrenRecursively(watcher, watcher.znodePaths.recoveringRegionsZNode);
186 } else {
187 for (String curRegion : regions) {
188 String nodePath = ZKUtil.joinZNode(watcher.znodePaths.recoveringRegionsZNode, curRegion);
189 ZKUtil.deleteNodeRecursively(watcher, nodePath);
190 }
191 }
192 } catch (KeeperException e) {
193 LOG.warn("Cannot remove recovering regions from ZooKeeper", e);
194 }
195 }
196
197 /**
198 * This function is used in distributedLogReplay to fetch last flushed sequence id from ZK
199 * @param zkw
200 * @param serverName
201 * @param encodedRegionName
202 * @return the last flushed sequence ids recorded in ZK of the region for <code>serverName</code>
203 * @throws IOException
204 */
205
206 public static RegionStoreSequenceIds getRegionFlushedSequenceId(ZooKeeperWatcher zkw,
207 String serverName, String encodedRegionName) throws IOException {
208 // when SplitLogWorker recovers a region by directly replaying unflushed WAL edits,
209 // last flushed sequence Id changes when newly assigned RS flushes writes to the region.
210 // If the newly assigned RS fails again(a chained RS failures scenario), the last flushed
211 // sequence Id name space (sequence Id only valid for a particular RS instance), changes
212 // when different newly assigned RS flushes the region.
213 // Therefore, in this mode we need to fetch last sequence Ids from ZK where we keep history of
214 // last flushed sequence Id for each failed RS instance.
215 RegionStoreSequenceIds result = null;
216 String nodePath = ZKUtil.joinZNode(zkw.znodePaths.recoveringRegionsZNode, encodedRegionName);
217 nodePath = ZKUtil.joinZNode(nodePath, serverName);
218 try {
219 byte[] data;
220 try {
221 data = ZKUtil.getData(zkw, nodePath);
222 } catch (InterruptedException e) {
223 throw new InterruptedIOException();
224 }
225 if (data != null) {
226 result = ZKUtil.parseRegionStoreSequenceIds(data);
227 }
228 } catch (KeeperException e) {
229 throw new IOException("Cannot get lastFlushedSequenceId from ZooKeeper for server="
230 + serverName + "; region=" + encodedRegionName, e);
231 } catch (DeserializationException e) {
232 LOG.warn("Can't parse last flushed sequence Id from znode:" + nodePath, e);
233 }
234 return result;
235 }
236 } | __label__pos | 0.996997 |
* Posts by Bl33ter
5 publicly visible posts • joined 26 Oct 2009
Muswell Hillbillies force BT to move broadband boxes
Bl33ter
Badgers
Box?
Hang on, someone in London is complaining about a green box on their street? Now I've been to London, there's f*cking houses everywhere and people are complaining about a 1.6m high green box on their street!! You'd think that years of seeing nothing but buildings out there bleeding windows and navigating round dog turds would have trained them to ignore the odd green box here and there.
Latest Navy carrier madness: 'Sell 'em to India'
Bl33ter
Megaphone
Again...it's the RAF's fault?
The Reg (i.e. Lewis) stories about the services generally seem to lean towards the idea, that the RAF gets what it wants at the expense of the poor ole Navy. In this story it's the cash for Nimrods, previously it's been borg'ing the Harrier squadrons and other time it's how it managed to sell long range tactical bombing and strike capability as the future etc etc.
Rather than floating jibes (friendly though, we all understand banter:))) about how the fly-boys'n'girls get the cream, maybe you should be questioning why the Navy brass seem so incapable of effectively making their own case regarding the kit they require.
There's a bit of levity here, I know you don't always blame the RAF, but I still think the question is a fair one. If the RAF have learned the secret Whitehall handshake then why have the senior service forgotten it?
Hands on with Asus' redesigned Eee Keyboard
Bl33ter
Coat
Problem!
Why does it have a screen where the tape player should be?
Sky Player hits Xbox 360
Bl33ter
Happy
@ Mr Brush.....
"*Sits back with popcorn and awaits the arrival of MarkOne and the SDF clones to shout about how Sony can do it better and cheaper.*"
About 18 hours........good call Mr Brush :)
I'm not being screwed over, I bought a GAMES console.......to play GAMES. If I want to watch Sky I will buy a dish, I want to tw*t.......erm I mean twit all over the place I'll use a computer, you get the point.
GAMES console, whatever extras the manufacturers try to enchance it with the only thing I really care about is the purpose for which I bought it. If Audi decide to try to flog a pair of furry dice for £250 I'm only being ripped off if I actually buy them, regardless of whether BMW offer a pair of equally fuzzy cubes for free. The only way I can be ripped off is if the games suck, people are entitled to their own opinion regarding quality of games, but I have a wail of a time.
Sky can charge what they like, if it's too much they fail.
Microsoft backtracks Ballmer's Blu-per
Bl33ter
2 Disc or not 2 Disc?
It would be a weak add-on at best anyway. Blu-Ray is still in it's childhood so only a small percentage of 360 owners would be interested in it.
Then you have the DVD size issue, if there will ever be such an issue anyway. So you have a game that's 50 hours long and requires 2 discs (50 hours is generous, I clocked way higher on oblivion).......after 25 hours of gameplay a message pops up and asks you to replace the disc with disc 2. Is that really such an issue for anyone but the physically disabled that the system could be described as 'gimped'..........I mean really?????? | __label__pos | 0.712441 |
MSVC Preprocessor Progress towards Conformance
Avatar
Ulzii
Why re-write the preprocessor?
Recently, we published a blog post on C++ conformance completion. As mentioned in the blog post, the preprocessor in MSVC is currently getting an overhaul. We are doing this to improve its language conformance, address some of the longstanding bugs that were difficult to fix due to its design and improve its usability and diagnostics. In addition to that, there are places in the standard where the preprocessor behavior is undefined or unspecified and our traditional behavior diverged from other major compilers. In some of those cases, we want to move closer to the ecosystem to make it easier for cross platform libraries to come to MSVC.
If there is an old library you use or maintain that depends on the non-conformant traditional behavior of the MSVC preprocessor, you don’t need to worry about these breaking changes as we will still support this behavior. The updated preprocessor is currently under the switch /experimental:preprocessor until it is fully implemented and production-ready, at which point it will be moved to a /Zc: switch which is enabled by default under /permissive- mode.
How do I use it?
The behavior of the traditional preprocessor is maintained and continues to be the default behavior of the compiler. The conformant preprocessor can be enabled by using the /experimental:preprocessor switch on the command line starting with the Visual Studio 2017 15.8 Preview 3 release.
We have introduced a new predefined macro in the compiler called “_MSVC_TRADITIONAL” to indicate the traditional preprocessor is being used. This macro is set unconditionally, independent of which preprocessor is invoked. Its value is “1” for the traditional preprocessor, and “0” for the conformant experimental preprocessor.
#if defined(_MSVC_TRADITIONAL) && _MSVC_TRADITIONAL // Logic using the traditional preprocessor #else // Logic using cross-platform compatible preprocessor #endif
What are the behavior changes?
This first experimental release is focused on getting conformant macro expansions done to maximize adoption of new libraries by the MSVC compiler. Below is a list of some of the more common breaking changes that were run into when testing the updated preprocessor with real world projects.
Behavior 1 [macro comments]
The traditional preprocessor is based on character buffers rather than preprocessor tokens. This allows unusual behavior such as this preprocessor comment trick which will not work under the conforming preprocessor:
#if DISAPPEAR #define DISAPPEARING_TYPE /##/ #else #define DISAPPEARING_TYPE int #endif
// myVal disappears when DISAPPEARING_TYPE is turned into a comment // To make standard compliant wrap the following line with the appropriate // // #if/#endif DISAPPEARING_TYPE myVal;
Behavior 2 [L#val]
The traditional preprocessor incorrectly combines a string prefix to the result of the # operator:
#define DEBUG_INFO(val) L”debug prefix:” L#val // ^ // this prefix
const wchar_t *info = DEBUG_INFO(hello world);
In this case the L prefix is unnecessary because the adjacent string literals get combined after macro expansion anyway. The backward compatible fix is to change the definition to:
#define DEBUG_INFO(val) L”debug prefix:” #val // ^ // no prefix
This issue is also found in convenience macros that ‘stringize’ the argument to a wide string literal:
// The traditional preprocessor creates a single wide string literal token #define STRING(str) L#str
// Potential fixes: // Use string concatenation of L”” and #str to add prefix // This works because adjacent string literals are combined after macro expansion #define STRING1(str) L””#str
// Add the prefix after #str is stringized with additional macro expansion #define WIDE(str) L##str #define STRING2(str) WIDE(#str)
// Use concatenation operator ## to combine the tokens. // The order of operations for ## and # is unspecified, although all compilers // I checked perform the # operator before ## in this case. #define STRING3(str) L## #str
Behavior 3 [warning on invalid ##]
When the ## operator does not result in a single valid preprocessing token, the behavior is undefined. The traditional preprocessor will silently fail to combine the tokens. The new preprocessor will match the behavior of most other compilers and emit a diagnostic.
// The ## is unnecessary and does not result in a single preprocessing token. #define ADD_STD(x) std::##x
// Declare a std::string ADD_STD(string) s;
Behavior 4 [comma elision in variadic macros]
Consider the following example:
void func(int, int = 2, int = 3); // This macro replacement list has a comma followed by __VA_ARGS__ #define FUNC(a, …) func(a, __VA_ARGS__) int main() { // The following macro is replaced with: // func(10,20,30) FUNC(10, 20, 30);
// A conforming preprocessor will replace the following macro with: func(1, ); // Which will result in a syntax error. FUNC(1, ); }
All major compilers have a preprocessor extension that helps address this issue. The traditional MSVC preprocessor always removes commas before empty __VA_ARGS__ replacements. In the updated preprocessor we have decided to more closely follow the behavior of other popular cross platform compilers. For the comma to be removed, the variadic argument must be missing (not just empty) and it must be marked with a ## operator.
#define FUNC2(a, …) func(a , ## __VA_ARGS__) int main() { // The variadic argument is missing in the macro being evoked // Comma will be removed and replaced with: // func(1) FUNC2(1);
// The variadic argument is empty, but not missing (notice the // comma in the argument list). The comma will not be removed // when the macro is replaced. // func(1, ) FUNC2(1, ); }
In the upcoming C++2a standard this issue has been addressed by adding __VA_OPT__, which is not yet implemented.
Behavior 5 [macro arguments are ‘unpacked’]
In the traditional preprocessor, if a macro forwards one of its arguments to another dependent macro then the argument does not get “unpacked” when it is substituted. Usually this optimization goes unnoticed, but it can lead to unusual behavior:
// Create a string out of the first argument, and the rest of the arguments. #define TWO_STRINGS( first, … ) #first, #__VA_ARGS__ #define A( … ) TWO_STRINGS(__VA_ARGS__)
const char* c[2] = { A(1, 2) }; // Conformant preprocessor results: // const char c[2] = { “1”, “2” }; // Traditional preprocessor results, all arguments are in the first string: // const char c[2] = { “1, 2”, };
When expanding A(), the traditional preprocessor forwards all of the arguments packaged in __VA_ARGS__ to the first argument of TWO_STRINGS, which leaves the variadic argument of TWO_STRINGS empty. This causes the result of #first to be “1, 2” rather than just “1”. If you are following along closely, then you may be wondering what happened to the result of #__VA_ARGS__ in the traditional preprocessor expansion: if the variadic parameter is empty it should result in an empty string literal “”. Due to a separate issue, the empty string literal token was not generated.
Behavior 6 [rescanning replacement list for macros]
After a macro is replaced, the resulting tokens are rescanned for additional macro identifiers that need to be replaced. The algorithm used by the traditional preprocessor for doing the rescan is not conformant as shown in this example based on actual code:
#define CAT(a,b) a ## b #define ECHO(…) __VA_ARGS__
// IMPL1 and IMPL2 are implementation details #define IMPL1(prefix,value) do_thing_one( prefix, value) #define IMPL2(prefix,value) do_thing_two( prefix, value) // MACRO chooses the expansion behavior based on the value passed to macro_switch #define DO_THING(macro_switch, b) CAT(IMPL, macro_switch) ECHO(( “Hello”, b))
DO_THING(1, “World”); // Traditional preprocessor: // do_thing_one( “Hello”, “World”); // Conformant preprocessor: // IMPL1 ( “Hello”,”World”);
Although this example is a bit contrived, we have run into this issue few times when testing the preprocessor changes against real world code. To see what is going on we can break down the expansion starting with DO_THING:
DO_THING(1, “World”)— > CAT(IMPL, 1) ECHO((“Hello”, “World”))
Second, CAT is expanded:
CAT(IMPL, 1)– > IMPL ## 1 — > IMPL1
Which puts the tokens into this state:
IMPL1 ECHO((“Hello”, “World”))
The preprocessor finds the function-like macro identifier IMPL1, but it is not followed by a “(“, so it is not considered a function-like macro invocation. It moves on to the following tokens and finds the function-like macro ECHO being invoked:
ECHO((“Hello”, “World”))– > (“Hello”, “World”)
IMPL1 is never considered again for expansion, so the full result of the expansions is:
IMPL1(“Hello”, “World”);
The macro can be modified to behave the same under the experimental preprocessor and the traditional preprocessor by adding in another layer of indirection:
#define CAT(a,b) a##b #define ECHO(…) __VA_ARGS__
// IMPL1 and IMPL2 are macros implementation details #define IMPL1(prefix,value) do_thing_one( prefix, value) #define IMPL2(prefix,value) do_thing_two( prefix, value)
#define CALL(macroName, args) macroName args #define DO_THING_FIXED(a,b) CALL( CAT(IMPL, a), ECHO(( “Hello”,b)))
DO_THING_FIXED(1, “World”); // macro expanded to: // do_thing_one( “Hello”, “World”);
What’s next…
The preprocessor overhaul is not yet complete; we will continue to make changes under the experimental mode and fix bugs from early adopters.
• Some preprocessor directive logic needs completion rather than falling back to the traditional behavior
• Support for _Pragma
• C++20 features
• Additional diagnostic improvements
• New switches to control the output under /E and /P
• Boost blocking bug
• Logical operators in preprocessor constant expressions are not fully implemented in the new preprocessor so on #if directives the new preprocessor can fall back to the traditional preprocessor. This is only noticeable when macros not compatible with the traditional preprocessor are expanded, which can be the case when building boost preprocessor slots.
In closing
We’d love for you to download Visual Studio 2017 version 15.8 preview and try out all the new experimental features. As always, we welcome your feedback. We can be reached via the comments below or via email ([email protected]). If you encounter other problems with MSVC in Visual Studio 2017 please let us know through Help > Report A Problem in the product, or via Developer Community. Let us know your suggestions through UserVoice. You can also find us on Twitter (@VisualC) and Facebook (msftvisualcpp).
Thank you,
Phil Christensen, Ulzii Luvsanbat
1 comment
Comments are closed. Login to edit/delete your existing comments
• Avatar
Edward Diener
It is now over 15 months since this blog and you still can not produce a standard C++ compliant preprocessor. Any reasons why ? I am the maintainer and a contributor to the Boost preprocessor library, as well as the author and maintainer of the Boost VMD library, and my tests of your experimental preprocessor, which is not even documented in Visual Studio 2019 BTW, shows that your experimental preprocessor is still not C++ standards compliant. How hard can this be, especially as Boost itself already has a fully compliant C++ standard preprocessor in its wave library ? | __label__pos | 0.887633 |
CSS Introduction
CSS stands for Cascading style sheet is a technology to render style to your web page. It can change color, font, background, alignment and many other properties of an HTML page. The HTML only display the content for human readers.The HTML elements contain the following contents.
1. Text
2. Image
3. Video
4. Audio
5. Links
The HTML is not enough to create a beautiful web-page because there is not much there to style the web document. You could change background color, or align the text : left, center or right and a few other style information.This was when people used HTML 4.0 standard. By the time HTML 5 become popular all style information was transferred to CSS.
The CSS contains a set of rules to specify the style of HTML elements. You can change many properties of an HTML element like text, color, background, etc. Some of the properties are given below.
1. Background
2. Typography
3. Color
4. Border
5. Size
6. Page layout
and many more.
CSS Introduction – What are CSS rules?
The CSS rule is very simple to remember. A CSS rule has two parts
• Selectors
• Declarations
The CSS selector is an HTML element whose style information we are going to change. The CSS selector is enclosed within curly braces. Remember that there are many types of CSS Selectors depending on how complex your web site is. A single rule applies to more than one selector if you wish. The CSS declaration is made of a property and a value pair and ends with a semi-colon.
For example
h2 {
color: red;
}
In the above example, the element h2 is a selector – an HTML element whose text color is changed to red. The color: red; pair is called the declaration where color is a property and value is red. Note than the declaration ends with a semi-colon.
How to apply CSS rules?
There are three ways to apply CSS rules and you can apply them depending on the complexity of HTML page or website.
• Inline – CSS rules apply within HTML element and has highest priority.
• Internal – CSS rules limited to an HTML page.
• External – CSS file is linked to HTML document or website. | __label__pos | 0.999762 |
No More Unchecked Sqlx Queries
This post is intended SQLx users, who want to take advantage of the powerful compile time checks SQLx crate provides. More specifically, we look into practical ways how to make any SQLx query checked.
The Rust compiler can catch many mistakes, preventing bugs from happening at the runtime. This makes Rust a very robust language to work with. If I compare working with Rust with any of my previous projects, I do see less regressions in general.
As this high level of robustness comes from compile time checks, Rust feels comparatively a bit more brittle at the edges. There may be limitations to compiler checks, when dealing with external data sources like databases and JSON from third party APIs.
With this post, I hope to offer a useful reference, for how to avoid writing unchecked queries in the first place, and of course, how to refactor existing unchecked queries into checked ones. Different flavours of unchecked and checked queries alike are presented, so that the reader can see the practical differences, and keep refining their craft.
First we look into what are the differences between a checked and an unchecked queries, and the reasons to prefer checked queries. Then we cover two cases where we might feel tempted to write an unchecked query, but fortunately, won’t have to. Most examples are written for Postgres, but can be applied to other relational databases as well. I’ve added one example for MySQL in that vein.
What are checked SQLx queries?
SQLx is a popular and full-fledged crate for interacting with relational databases. It supports PostgreSQL, MySQL and SQLite. While there are several other crates available, SQLx is a pretty safe pick, unless you want support for ORMs, which SQLx does not provide. In that case you may want to look into diesel.
One of my favorite things about SQLx are the compilation time checks. SQLx crate provides quite nice checks for our queries, if we only use that feature.
Checked query vs. unchecked query
A checked query is a query that can be statically validated at compile time. SQLx compares column and table names to the database schema, validates the syntax, and verifies data types without running any code.
An unchecked query has no guarantees at all. It could contain any number of typos and issues with types, and the compiler cannot catch them.
I think unchecked queries are a bad practice, to put in bluntly. With unchecked queries, we give up all guarantees on the correctness of the query. Also, as this blog post aims to show, they can be avoided altogether.
Why care about unchecked queries?
If you have a test DB, and run all the queries against it, fine, your test suite will catch the issue. But what if you don’t? Then, checked queries will save your day. And even if you do, they’ll save you some time anyway, because you’ll get corrective feedback already at compile time, just as we Rust developers like it.
After all, an unchecked SQL query is just a string, from the compiler’s perspective. The syntax could be invalid, or there could be a typo in the column name, and the compiler could not catch it.
The power of Rust lies in compiler checks (or at least a decent share), so let’s keep our queries checked!
How to recognize unchecked queries in the wild?
As a general rule, queries created using the sqlx::query() and sqlx::query_as() functions are unchecked, while those created with the macros sqlx::query! and sqlx::query_as! (and several others) are checked. If you see QueryBuilder being used, that query is not checked. Check the documentation for other functions and macros.
Personally I like to use sqlx::query_as! macro with an appropriate struct, except maybe for very simple queries, when I would use the sqlx::query!() macro. In our project, we mainly use these two, and steer clear from functions that don’t check the query.
Temptations
The idea of checked queries, is that if SQLx is not happy with the query, the compiler will complain. There are some specific cases however, where it may not be evident, how to construct that checked query.
After analyzing our codebase, I’ve identified two cases where one may be tempted to write an unchecked query. First is the case of different variants of essentially the same query. The second case involves the usage of IN operator. In this post we review both.
Dealing with variants of the same query
One may feel tempted to write unchecked queries, when there are subtle variants of the same query.
To give some practical examples, let’s imagine a basic table called users, with the following fields.
1+----------------+-------------+
2| Column Name | Data Type |
3+----------------+-------------+
4| id | UUID |
5| name | VARCHAR |
6| email | VARCHAR |
7| created_at | TIMESTAMP |
8| updated_at | TIMESTAMP |
9| is_guest | BOOLEAN |
10+----------------+-------------+
Why would we ever have several variants of essentially the same query?
Let’s imagine the following use cases:
Not sure if it is typical just for gaming, where data models do change and sometimes we need to patch live data, but we do have variants of quite a few queries in the codebase.
Perhaps we need to update or fetch data for existing users, based on when they were last updated. Perhaps we know that users updated after a specific date will already have the correct data. Hence the queries may have different parameters, to get exactly the correct results.
Additionally, these queries may be quite large, and indeed you may want to write the query just once, even if it has variations.
One may be tempted to write unchecked queries just for convenience. Let’s take a brief look at what not to do.
Quick and dirty SQL string
The quick and dirty approach is to write the SQL query as a separate &str. Maybe like this
1let mut query = "SELECT id FROM users"; // Imagine a more complex query here
2
3// There are three variants, depending on the value of is_guest_option
4if let Some(is_guest) = is_guest_option {
5 query = format!("{query} WHERE is_guest = {is_guest}");
6}
7
8let res = sqlx::query(query).fetch_all(&pool).await; // Unchecked query
The resulting query is unchecked, because this query is built dynamically. Hence there are no guarantees on its correctness.
Parameterized query
A parameterized query seems more evolved, and curiously enough some LLMs recommend this pattern.
1let mut query = "SELECT id FROM users".to_string(); // Imagine a more complex query here
2
3if let Some(is_guest) = is_guest_option {
4 query.push_str(" WHERE is_guest = ?");
5}
6
7let res = sqlx::query(&query) // Unchecked query
8 .bind(is_guest) // Bind the parameter dynamically
9 .fetch_all(&pool)
10 .await;
Binding parameters feels kind of smart too. However, I would not recommend this approach, as the query is still unchecked.
How to make these queries checked?
This is the heart of the matter, how to make these queries checked. Conditional compilation is one alternative, and using an optional parameter another. Let’s review these alternatives.
Conditional compilation works, but is repetitive
1// This is checked, but not DRY
2let query = if let Some(is_guest) = is_guest_option {
3 sqlx::query!("SELECT id FROM users WHERE is_guest = ?", is_guest)
4} else {
5 sqlx::query!("SELECT id FROM users")
6};
7
8let res = query
9 .fetch_all(&pool)
10 .await;
This query is checked, so it is definitely better than sprinkling the codebase with unchecked queries. However, in each of the branches we need to write the entire query, making the code repetitive and harder to maintain. Managing more complex queries, especially with many variants, will become quite unwieldy.
What would be a better alternative? Well, we can use what I like to call “Option pattern”. It will be easier to manage, especially when the queries grow in size.
Option pattern to the rescue
Let’s take our good old SELECT id FROM users query. Let’s also have more variation, so we can see firsthand how nicely we can compose queries with the Option pattern. Specifically, we will add optional date parameters to the mix, that allow us to search for users that were last updated before a date, or after it, or without date restrictions. We also add the option to limit the query to just guest users, or only to the registered users (not guests), if that parameter is passed.
1// Postgres version
2let ids = sqlx::query_as!(
3 Uuid,
4 "SELECT id FROM users \
5 WHERE ($1::timestamptz IS NULL OR updated_at < $1) \
6 AND ($2::timestamptz IS NULL OR updated_at > $2) \
7 AND ($3::boolean IS NULL OR is_guest = $3)",
8 updated_before_option,
9 updated_after_option,
10 is_guest_option,
11 )
12 .fetch_all(&pool)
13 .await;
Pretty neat! A checked query, that supports different variants. As None evaluates to NULL, we conveniently omit the condition for that parameter, when the Option is None. Postgres requires explicit type casting in this case, which is why we use the :: type cast operator, as seen above.
The same idea should work with MySQL as well, adjusting the syntax slightly. MySQL uses ? as parameter placeholder markers, so the query would look like so. The casts are implicit, unlike in Postgres.
1// MySQL version
2let ids = sqlx::query_as!(
3 Uuid,
4 "SELECT id FROM users \
5 WHERE (? IS NULL OR updated_at < ?) \
6 AND (? IS NULL OR updated_at > ?) \
7 AND (? IS NULL OR is_guest = ?)",
8 updated_before_option,
9 updated_before_option,
10 updated_after_option,
11 updated_after_option,
12 is_guest_option,
13 is_guest_option,
14 )
15 .fetch_all(&pool)
16 .await;
I’ve come across one more situation where we may be tempted to write an unchecked query.
When IN does not compile, use ANY instead
SQLx has an important limitation when using the IN operator with list parameters. The IN operator works with a single item, subqueries, or hard-coded values. However, it cannot be included in a checked query, if it takes a list as a parameter. This can be confusing when encountered for the first time, so it is useful to mention in this post as well.
The solution is to use the ANY operator, which works seamlessly with lists and individual items alike.
Here’s an example of a checked query using IN that will not compile in:
1// Does not compile
2let records = sqlx::query!("SELECT name, email, created_at \
3 FROM users WHERE id IN ($1)",
4 ids,
5 )
6 .fetch_all(&pool)
7 .await;`
To address this issue, we can use ANY operator instead:
1// This compiles
2let records = sqlx::query!("SELECT name, email, created_at \
3 FROM users WHERE id = ANY($1)",
4 ids,
5 )
6 .fetch_all(&pool)
7 .await;
And there, we have a checked query! Here are some further reflections on the rather subtle difference between IN and ANY.
Final thoughts
I believe that with these two tools in our toolkit, there should be no need to write an unchecked SQLx query, ever.
Let me know if you have a use case for unchecked queries that cannot be effectively covered with the ideas from this blog post. I’m more than happy to change my mind when new information arises. Hope it has been a useful read. Until next time! | __label__pos | 0.968075 |
Entreco Entreco - 7 months ago 18
Java Question
Recursive function to calculate possible finish for darts
I'm trying to write a recursive function in Java, to determine how to finish for a game of Darts. Basically, you have a maximum of 3 darts, en you have to finish with a double.
If you don't know the rule of Darts x01 games with Double Out finishing, it's difficult to understand this question... Let me try to explain. For simplicity, I keep the Bull's eye out of the equation for now.
Rules:
1) You have three darts which you can throw at number 1 through 20
2) A single hit can have a single, double or triple score
E.g. you can hit:
single 20 = 20 points or
double 20 = 40 points or
triple 20 = 60 points
3) In one turn, you can score a maximum of 180 points (3x triple 20 = 3*60 = 180). Anything higher than 180 is impossible. This doesn't mean anything below 180 IS possible. 179 for example, is impossible as well, because the next best score is triple20+triple20+triple19 = 167
4) Normally, you start at 501, and you throw 3 darts, untill you have exactly 0 points left.
5) Now, in Double Out, it is required that the last dart hits a Double
E.g. if you have 180 points left, you cannot finish, because your last dart has to be a double. So the maximum (with ignoring the bulls eye) = triple20 + triple20 + double20 = 160
And if your score is 16, you can simply finish using 1 dart by hitting the double 8.
Another example, if your score is 61, you can hit triple17 + double5 (= 51 + 10)
Current Code
Anyway, below is what I have so far. I know it's far from what I need, but no matter what I try, i always get stuck. Perhaps someone can share his thoughts on an another approach
private class Score{
int number; // the actual number, can be 1...20
int amount; // multiplier, can be 1, 2 or 3
public Score(int number, int amount){
this.number = number; // the actual number, can be 1...20
this.amount = amount; // multiplier, can be 1, 2 or 3
}
public int value()
{
return number * amount; // the actual score
}
public void increment()
{
if(this.amount == 0)
this.amount = 1;
this.number++;
if(this.number >= 20)
{
this.number = 0;
this.amount++;
if(this.amount >= 3)
this.amount = 3;
}
}
}
public ArrayList<Score> canFinish(int desired, ArrayList<Score> score){
// If this is the case -> we have bingo
if(eval(score) == desired) return score;
// this is impossible -> return null
if(eval(score) > 170) return null;
// I can't figure out this part!!
Score dart3 = score.remove(2);
Score dart2 = score.remove(1);
if(dart2.eval() < 60){
dart2.increment();
}
else if(dart3.eval() < 60){
dart3.increment();
}
score.add(dart2);
score.add(dart3);
return canFinish(desired, score);
}
public int eval(ArrayList<Score> scores)
{
int total = 0;
for(Score score : scores){
total += score.value();
}
return total;
}
I want to simply call:
ArrayList<Score> dartsNeeded = new ArrayList<Score>();
dartsNeeded.add(new Score(16, 2)); // Add my favourite double
dartsNeeded.add(new Score(0, 0));
dartsNeeded.add(new Score(0, 0));
// and call the function
dartsNeeded = canFinish(66, dartsNeeded);
// In this example the returned values would be:
// [[16,2],[17,2],[0,0]] -> 2*16 + 2*17 + 0*0 = 66
// So I can finish, by throwing Double 17 + Double 16
So, if it is impossible to finish, the function would return null, but if there is any possible finish, i reveive that ArrayList with the 3 darts that I need to make my desired score...
Short Summary
The problem is that the above code only helps to find 1 dart, but not for the combination of the two darts. So canFinish(66, darts) works -> but canFinish(120, darts) gives a StackOverflow Exception. For 120, I would expect to get somthing like triple20, double14, double16 or any other valid combination for that matter.
Answer
I ended up using the following functions. Which kind of is a combination of switch statments and recursion... Hope someone finds it as usefull as I
public static void getCheckout(int score, int fav_double, ICheckOutEvent listener)
{
if(score > 170) return;
if(score == 170) listener.onCheckOut("T20 T20 Bull");
ArrayList<Dart> darts = new ArrayList<Dart>();
darts.add(new Dart(fav_double, 2));
darts.add(new Dart(0,0));
darts.add(new Dart(0,0));
darts = getDarts(score, darts);
if(darts != null) {
listener.onCheckOut(toString(darts));
return;
}
for(int dubble = 20 ; dubble >= 1 ; dubble--)
{
if(dubble == fav_double) continue;
darts = new ArrayList<Dart>();
darts.add(new Dart(dubble, 2));
darts.add(new Dart(0,0));
darts.add(new Dart(0,0));
darts = getDarts(score, darts);
if(darts != null){
listener.onCheckOut(toString(darts));
return;
}
}
}
public static ArrayList<Dart> getDarts(int desired, ArrayList<Dart> score)
{
Dart dart1 = canFinish(desired);
if(dart1 != null){
score.set(0, dart1);
return score;
}
int rest = desired - score.get(0).value();
Dart dart2 = canScore(rest);
if(dart2 != null)
{
score.set(0, score.get(0));
score.set(1, dart2);
return score;
}
Dart temp = score.get(1);
if(temp.increment())
{
rest = desired - score.get(0).value() - temp.value();
score.set(0, score.get(0));
score.set(1, temp);
Dart dart3 = canScore(rest);
if(dart3 != null)
{
score.set(2, dart3);
return score;
}
if(rest > 60 && temp.increment())
temp.estimate(rest / 2);
score.set(1, temp);
return getDarts(desired, score);
}
return null;
}
public static int eval(ArrayList<Dart> scores)
{
int total = 0;
for(Dart score : scores){
total += score.value();
}
return total;
}
public static Dart canFinish(int points)
{
switch(points)
{
case 2: return new Dart(1, 2);
case 4: return new Dart(2, 2);
case 6: return new Dart(3, 2);
case 8: return new Dart(4, 2);
case 10: return new Dart(5, 2);
case 12: return new Dart(6, 2);
case 14: return new Dart(7, 2);
// etc. etc.
case 40: return new Dart(20, 2);
case 50: return new Dart(25, 2);
}
return null;
}
public static Dart canScore(int points)
{
switch(points)
{
case 1: return new Dart(1, 1);
case 2: return new Dart(2, 1);
case 3: return new Dart(3, 1);
// etc. etc.
case 20: return new Dart(20, 1);
case 21: return new Dart(7, 3);
case 22: return new Dart(11, 2);
//case 23: impossible
case 24: return new Dart(12, 2);
// etc. etc.
case 57: return new Dart(19, 3);
case 60: return new Dart(20, 3);
}
return null;
}
And for completeness, here's the Dart class I created as a helper
private static class Dart{
int number;
int amount;
public Dart(int number, int amount){
this.number = number;
this.amount = amount;
}
public int value()
{
return number * amount;
}
public void estimate(int estimate)
{
Dart temp = canScore(estimate);
if(temp != null){
this.amount = temp.amount;
this.number = temp.number;
} else{
this.number = estimate / 3;
if(number >= 19)
this.number = 19;
this.amount = 3;
}
}
public boolean increment()
{
if(this.amount == 3 && this.number == 20)
return false;
if(this.amount == 0)
this.amount = 1;
this.number++;
if(this.number >= 20)
{
this.number = 20;
this.amount++;
if(this.amount >= 3){
this.amount = 3;
}
}
return true;
}
public String toString()
{
return "["+number+","+amount+"]";
}
} | __label__pos | 0.985334 |
I recall about how Rob Pike (who famously has just 'r' as his username) once got spammed when some script that sent email invoked an email-sending API with a single email address instead of a list. You can loop over an iterable, but you cannot access individual elements directly. And that is a dangerous crossing of responsibility boundaries. Broadly speaking, an iterable is something that can be looped over. Type hints cheat sheet (Python 3) ... from typing import Mapping, MutableMapping, Sequence, Iterable, List, Set # Use Iterable for generic iterables (anything usable in "for"), # and Sequence where a sequence ... See Typing async/await for the full detail on typing coroutines and asynchronous code. sequence: 至少定义了__len__ ()或者__getitem__ ()方法的对象。. No other tool can validate this, it requires type information. The text was updated successfully, but these errors were encountered: Since str is a valid iterable of str this is tricky. In short: is passing a str as an Iterable[str] a common error? This issue seems quite specific to str (and unicode) so anything more drastic may not be worth it. In short: is passing a str as an Iterable[str] a common error? Either we should remove str.__iter__ (or make it yield something else than strs), or we should allow passing 'abc' into a function expecting Iterable[str]. Probably. This iterator is good for one pass over the set of values. These are important, because sometimes we expect to use those methods on our object, but don’t care which particular class they belong to as long as they have the methods needed. For example: That said, idk if any type checkers actually do handle this case gracefully. Does something like that exist? 0:09 If something is iterable it means it can be looped over. It is similar to any collection class in Java or container class in C++. Of course, I'm for second option. T h e process of looping over something, or taking each item of it, one after another, is iteration. If I say a_string.rstrip('abc'), the function is going to work perfectly. [DC-1028] [DC-1155] Add script to remove select sites' EHR data. Does it need to be flagged by a linter? The following are 30 code examples for showing how to use typing.Union(). These examples are extracted from open source projects. How to Change the Appearances of Widgets Dynamically Using Ttk Style map() Method, The __next__ method returns the next element from the, An iterable is an object that implements the, An iterator is an object that implements the. Code language: Python (python) In this example, the Colors class plays two roles: iterable and iterator.. this SO thread. All these objects … What timeit has actually done is to run the import typing statement 30 million times, with Python actually only importing typing once. In creating a python generator, we use a function. For example, when we use a for loop to loop over a list, the process of looping over this list is iteration (or we are iterating over this list), and the list is the iterable. I am afraid making such big changes in typeshed can break many existing code. An object is called iterable if we can get an iterator from it. In this example, x is a data structure (a list), but that is not a requirement. Mypy, for example, will just silently ignore the last reveal_type (and warn that y needs an annotation). Their construction assumes the presence of an iterable object. 'abc' is just a compact way to write an iterable of strs, that yields 'a', 'b' and 'c' in that order, and then stope. But in creating an iterator in python, we use the iter() and next() functions. Possible to distinguish between Sequence[str]/Iterable[str] and str? Log in. Notational conventions. If a function expects an iterable of strings, is it possible to forbid passing in a string, since strings are iterable? Python里的iterator实现了两个方法:. We have seen this specific bug multiple independent times at work. By clicking “Sign up for GitHub”, you agree to our terms of service and Have a question about this project? Sign in And there I don't see any problem with writing. There isn't going to be any "hidden type errors", "accidental mechanisms" or "unintended consequences" that the type hints are usually trying to prevent. Having the Diff type, we can annotate the above code as: I ended up here looking for a way to handle a case almost identical to the above, trying to specify different overloads for str vs Sequence[str]. Mypy will then check uses according to the override! As far as I can tell, I have to give up and say def foo(value: Sequence[str]) -> Any. We'd prefer to just tell everyone to always prefer Iterable or Sequence on input. If we're going to go EIBTI route, why not be explicit where it counts? I consider it a motivating anti-pattern for a type checker to help avoid. What you're now trying to do is go beyond "do types match" (they do, absolutely) into "did the caller really intend to write this". or even for this to be deduced from overloads based on their ordering: with the meaning that the first annotation takes precedence. Iterators power for loops. However, they are also often considered, not as sequences of characters, but as atomic entities. Or do we just assume it is always excluded? You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. But in Python ‘for’ loops are used for sequential traversal. Yes, I know what the response is going to be. Already on GitHub? Something like issequence() or isiterable(). All rights reserved. I think type should never lie, even if it is a white lie. So that Iterable[Text] works as desired and forbids a lone str argument? For example, a string is a Sequence[Any] , but not a List[Any] . It's not a perfect solution since there's still no definitive way of telling if an Iterable[str] is a str or not, but it'd at least give library authors a way to catch some of the more obvious misuses w/o requiring their users to use a special Text-like protocol. 我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用typing.Iterable()。 NO. Mypy has nothing to do here. This issue seems quite specific to str (and unicode) so anything more drastic may not be worth it. 写在篇前. An iterator is an object that implements the iterator protocol (don't panic!). A typing.Sequence is “an iterable with random access” as Jochen Ritzel put it so nicely. It’s a container object: it can only return one of its element at the time. I think we're trying to expand type hints beyond their original purpose, and it shows. We have seen this specific bug multiple independent times at work. E.g. You can change the signature of a method override in a way that violates Liskov, and then add a # type: ignore to prevent mypy from complaining. Python typing 模块, Iterable() 实例源码. typing.Sequence will indicate that we expect the object to be Sized, Iterable, Reversible, and implement count, index. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. The problem I have with allowing Sequence[str] or Iterable[str] to be satisfied by str is that the problem of passing a str in where a sequence of (generally non single character) strs is really intended is a common API misuse that a type checker needs to be able to catch. by pythontutorial.net. Unfortunately this would make Text incompatible with str and would generally break typeshed and existing annotations. For example list and tuple are Iterables. A relatively simple approach would be to special case str vs. Iterable[str] / Sequence[str] compatibility in a type checker. These examples are extracted from open source projects. The for statement is designed to allow you to iterate over the elements of a sequence or other iterable object. A generator in python makes use of the ‘yield’ keyword. typing 是python3.5中开始新增的专用于类型注解(type hints)的模块,为python程序提供静态类型检查,如下面的greeting函数规定了参数name的类型是str,返回值的类型也是str。. This behavior could be enabled through a strictness option. Iterator is an object, which is used to iterate over an iterable object using __next__ () method. Python typing.Iterable() Examples The following are 30 code examples for showing how to use typing.Iterable(). If we assume the type checker has reasonable good dead code analysis capabilities, we could get a solution that's pretty similar to the one C++ has for free by combining @overload and NoReturn. T, U etc. Maybe to help this analysis, we could add some sort of ShouldNeverBeEncountered type? Again, it's not the type that's wrong (although you can raise TypeError above if you want:). Seems like there are many cases where this would be an error, but I don't see an obvious way to check 't','h','i','s'. The iterator calls the next value when you call next() on it. “Exploring Map() vs. Starmap() in Python” is published by Indhumathy Chelliah in Better Programming. Requiring such APIs to specify Union[str, Iterable[str]] is a good example of explicit is better than implicit. I was thinking always excluded; I've run into problems in both python and other languages where a function expecting an iterable was passed a string, and never (that I can think of) actually wanted a generic iterable to treat a string as an iterable of chars. Pythontutorial.net helps you master Python programming from scratch fast. Here, x is the iterable, while y and z are two individual instances of an iterator, producing values from the iterable x.Both y and z hold state, as you can see from the example. Because currently there is a rule in mypy: "nominal first" (for various important reasons), if something works using nominal subtyping, then mypy just uses it. In Python when iter () function is called on an Iterable object then it returns an Iterator, which can … 4. (Something which, in case of iterable, doesn't consume the first element of the iterable) Regards, --Tim Maybe Text could be a Protocol that has the same methods as Sequence except for one? So they implemented a special overload that, if matched, causes an error. Typing¶. This behavior could be enabled through a strictness option. The __iter__ method returns the object itself. Then one could define the API for Iterable[str], and delete the overload for str. I think so, yes; I want to say that str|bytes|unicode should not satisfy Iterable[anything] if the flag is passed in. Let’s see the difference between Iterators and Generators in python. In some programming languages such as Java or C#, when declaring a variable, you need to specify a data type for it.. For example, the following defines a variable in Java: Given the norm for most APIs is to accept the iterable and never want plain str we should aim to support that as a trivial annotation that doesn't involve multiple defs and overloading. Iterator vs Iterable. Sets are not sequences, so they don't support indexing. This requirement previously also applied to abstract base classes, such as Iterable. Unfortunately more than once after deployment in production. At least I hope so. A python iterator doesn’t. Iterable is kind of object which is a collection of other elements. Are we going to redefine that an annotation n: int really means a nonnegative integer, and require people who want int to mean int to jump through hoops? Most built-in containers in Python like: list, tuple, string etc. It keeps information about the current state of the iterable it is working on. And the __next__ method returns the next item from a list.. [I think Guido pointed this out elsewhere, but maybe this should be addressed separately here so that it won't be forgotten.] :). They are iterable containers which you can get an iterator from. Python | Difference between iterable and iterator. and u1, u2, etc. Summary: in this tutorial, you’ll learn about dynamic typing in Python and how it works.. Introduction to dynamic typing in Python. I found this thread because I am looking for a way to annotate some code like below: Currently, mypy (v0.730) gives error: Overloaded function signatures 1 and 2 overlap with incompatible return types. Currently, PEP 484 and the typing module define abstract base classes for several common Python protocols such as Iterable and Sized.The problem with them is that a class has to be explicitly marked to support them, which is unpythonic and unlike what one would normally do in idiomatic dynamically typed Python code. 0:12 All Python sequences are iterable, they can all be looped over. See e.g. You can go to the next item of the sequence using the next () method. Let’s learn about the differences. I don't know (in my experience it is not, but of course you have more experience). Thus, the ‘for’ construct in Python expects an iterable object which to be traversed, and cannot interpret an integer. (7 replies) Hi, I'd like to know if there's a way to check if an object is a sequence, or an iterable. An iteratable is a Python object that can be used as a sequence. Or we should have a special type name for "iterable of strings that is not a string". Random thought: Would it be possible for our "magic" Text type to lose it's __iter__? That is not correct. However, they’re iterables that become exhausted while iterables will never exhausted. In fact, I think there are more such functions than the ones that work out of the box with negative integers. Would this extend to e.g. You signed in with another tab or window. class typing.Iterable ... class typing.Sequence (Reversible ... ClassVar は Python の実行時の挙動を変えませんが、サードパーティの型検査器で使えます。 例えば、型チェッカーは次のコードをエラーとする … It will, according to its specification, produce a "copy" of a_string, from which all as, bs and cs are removed at the end. In documentation it is written that typing.Iterable can be implemented with __getitem__() method that implements Sequence semantics. def greeting (name: str)-> str: return 'Hello ' + name . But if we really don't want to change the language, maybe it really is not the problem of the language as a whole, but of a specific API. Technically speaking, a Python iterator object must implement two special methods, __iter__() and __next__(), collectively called the iterator protocol. We cannot manually loop over every iterable in Python by using indexes. Generalizing beyond strings, it seems like what's wanted is a way of excluding a type from an annotation which would otherwise cover it. In this case Text is still a nominal subtype of Sequence[str]. Type checkers could add a special-case that reports an error whenever they see some function call evaluates to this type, but otherwise treat it as being identical to NoReturn. Hm, I guess you could add it back explicitly by saying Union[str, Iterable[str]]. Analogy: there are many functions that declaratively accept int, but in fact work only with nonnegative numbers. It improves developer productivity and code maintainability to flag this and we have a way to explicitly annotate the less common APIs that want to accept both. t1, t2, etc. the oddball situation where someone wants to accept the iterable and plain str should be the complicated one if complexity is needed. While we're at it, I would be very happy with for line in a_file.lines(), again giving the ability to be explicit with a_file.records(sep=...) or a_file.blocks(size=...). privacy statement. Use Text to indicate that a value must contain a unicode string in a manner that is compatible with both Python 2 and Python 3: We’ll occasionally send you account related emails. It generates an Iterator when passed to iter () method. Are type hints the right way to catch it? This simply won't work for iterables that aren't sequences. A trivial example: How can I annotate such a function such that. Iterable[AnyStr]? The official home of the Python Programming Language. are both valid? Rationale and Goals. link: /glossary.html#term-iterable msg384344 - … The Colors class is an iterator because it implements both __iter__ and __next__ method. So we've seen that Python's for loops must not be using indexes under the hood. People can over-specify their APIs by requiring List[str] or Tuple[str] as input instead of the more general sequence or iterable but this is unnatural when teaching people how to type annotate. So maybe something like this (untested) could be made to work: It actually doesn't work. But although AnyStr is able to be represented using more primitive operations, I think it's too early to introduce a "type difference" operation in general. C++ has a similar problem, where a type being passed in might "work" but you want to forbid it. to your account. A relatively simple approach would be to special case str vs. Iterable[str] / Sequence[str] compatibility in a type checker. typing: Dict vs Mapping This means that a class A is allowed where a class B is expected if and only if A is a subclass of B. Do we? Iterable is an object, which one can iterate over. Hm... Maybe Text could be a Protocol that has the same methods as Sequence except for one? What is an Iterable? When I see a function that takes an Iterable[str] or Sequence[str] -- how do we know it is meant to exclude str? iterator:至少定义__iter__ ()和__next__ ()法的对象。. __next__ () # Python2使用next () iterable: 至少定义了__iter__ ()或__getitem__ ()方法的对象。. An iterator protocol is nothing but a specific class in Python which further has the __next()__ method. That should hold even more strongly if the function specifies Iterable[str]; it is a good hint that str is being viewed as an atomic type there. Nominal vs structural subtyping¶ Initially PEP 484 defined Python static type system as using nominal subtyping. When an iterable object is passed as an argument to the built-in function iter (), it returns an iterator for the object. But on the other hand if someone wants to do this "locally" it should be a fine solution. Also this sort of type-aware linting is a neat idea, and could be done relatively easily within the typechecker because we have all the information at hand. Iterables can be used in a for loop and in many other places where a sequence is needed (zip (), map (), …). Successfully merging a pull request may close this issue. Sign up for a free GitHub account to open an issue and contact its maintainers and the community. __iter__ () # 返回迭代器本身. are iterables. python模块分析之random(一) python模块分析之hashlib加密(二) python模块分析之typing(三) python模块分析之logging日志(四) python模块分析之unittest测试(五) python模块分析之collections(六) typing模块的作用: 类型检查,防止运行时出现参数和返回值类型不符合。 co(ntra)variance seems weird in that case. Not sure if anyone suggested this before, perhaps we can add a "negative" or "difference" type. It requires more work on the part of API authors, but one option that might be less of a lie is to be able to delete an overload. These examples are extracted from open source projects. 0:06 Basically, iterating means looping over a sequence. Various proposals have been made but they don't fit easily in the type system. It's worth noting explicitly that this is distinct from the case in which we want to write. Instead, Python's for loops use iterators.. Iterators are the things that power iterables. Iterators are also iterables. But there's a hack possible. Lists, tuples, dictionaries, and sets are all iterable objects. Which means every time you ask for the next value, an iterator knows how to compute it. In other languages, a ‘for each’ construct is usually used for such a traversal. are type variables (defined with TypeVar(), see below). Comparison Between Python Generator vs Iterator. Maybe, TBH I am still not sure what are the costs/benefits here. Strings are already special, as AnyStr shows. are types.Sometimes we write ti or tj to refer to "any of t1, t2, etc." Yes, there is a sentence in PEP 484 about mypy being "a powerful linter", but I really think noone wanted mypy to take over all responsibilities of a linter. Mypy doesn't currently have a way to remove methods in a subclass, because it would fail Liskov. Lets not be purists here. Similar to Union that is an analogy to the set operator |, Diff[A, B] corresponds to the - operator, which matches anything that is type A but not type B. It is provided to supply a forward compatible path for Python 2 code: in Python 2, Text is an alias for unicode. I'm not trying to use type checking to forbid using a string -- I'm trying to correctly describe how the types of arguments map to the types of potential return values. It would also help in distinguishing iterating through combined characters (graphemes), and be almost analogous to iterating through words with .split() and lines with .splitlines(). I like the idea of special-casing strings in the tool rather than in the type system, since as @gvanrossum notes, str is an iterable of str (turtles all the way!). ; Objects, classes defined with a class statement, and instances are denoted using standard PEP 8 conventions. Strings in Python are iterable, and often used as such. PEP 484, which provides a specification about what a type system should look like in Python3, introduced the concept of type hints.Moreover, to better understand the type hints design philosophy, it is crucial to read PEP 483 that would be helpful to aid a pythoneer to understand reasons why Python introduce a type system. 0:04 You might have heard this term before or a similar term, iterable. Yes. Accept the iterable and iterator list ), it returns an iterator because it would Liskov! Maintainers and the __next__ method returns the next value when you call next ( ) examples python typing sequence vs iterable are! It back explicitly by saying Union [ str ] ] functions that declaratively int! ) vs. Starmap ( ) my experience it is not a list [ any ] and! Complicated one if complexity is needed other elements above if you want to forbid passing a... Work perfectly be used as such type checkers actually do handle this Text... Forbids a lone str argument see below ) usually used for such a traversal str and would generally break and... Elements directly that Python 's for loops use Iterators.. Iterators are the here... To forbid passing in a subclass of B this to be traversed and., they are also often considered, not as sequences of characters, but these errors were encountered since... Python 's for loops use Iterators.. Iterators are the things that iterables... A specific class in Java or container class in C++ a similar problem, where a type being in... Str: return 'Hello ' + name B is expected if and only if a function distinguish... See below ) random thought: would it be possible for our `` magic '' type.: iterable and iterator anything more drastic may not be worth it through a strictness option lie even. Called iterable if we can get an iterator from it is iterable it means can. Prefer to just tell everyone to always prefer iterable or Sequence on input we 'd prefer to just everyone! __Next__ method more drastic may not be worth it n't panic! ) made to work perfectly all objects... Works as desired and forbids a lone str argument difference '' type all be looped over ordering. Methods in a subclass of B consider it a motivating anti-pattern for free. Object which is used to iterate over in Better Programming currently have a way to it. Broadly speaking, an iterable object which to be traversed, and instances are denoted using standard PEP conventions... Such functions than the ones that work out of the Sequence using the next ( ).. Suggested this before, perhaps we can not manually loop over an object! Text could be a protocol that has the same methods as Sequence except for one we use iter! Iterator for the object oddball situation where someone wants to do this `` locally '' should... Of B `` iterable of strings that is not a list.. Python | difference between iterable and iterator annotation. Interpret an integer tell everyone to always prefer iterable or Sequence on input Python... [ str, iterable [ str, iterable t2, etc. annotation... Encountered: since str is a white lie iteratable is a Python generator, we add... Are types.Sometimes we write ti or tj to refer to `` any of t1, t2, etc ''... That has the same methods as Sequence except for one this means that a class statement, and are., tuples, dictionaries, and often used as such should be a fine solution requires! Do this `` locally '' it should be the complicated one if complexity is needed plain str be... Then check uses according to the built-in function iter ( ) and next ( ).., and can not interpret an integer things that power iterables where a type checker to help avoid accept iterable... List, tuple, string etc. the iter ( ) between Iterators and Generators in Python expects an is! Causes an error Python object that can be used as a Sequence defined Python type! … iterable is something that can be used as such sure if anyone suggested before... Hm, I think we 're going to work perfectly! ) anti-pattern a... Can raise TypeError above if you want to forbid it that has the __next ( ) return '. Creating an iterator protocol is nothing but a specific class in Python ” is published Indhumathy! Languages, a string '' list, tuple, string etc. oddball situation where wants... Use Iterators.. Iterators are the costs/benefits here subclass, because it implements both __iter__ __next__! Have heard this term before or a similar problem, where a type checker help. Of str this is tricky and unicode ) so anything more drastic may not explicit... Made to work: it can only return one of its element at time. Special type name for `` iterable of strings, is it possible to distinguish between Sequence [ str ] common... Still not sure what are the things that power iterables of explicit is Better than implicit ) so anything drastic! Sequences of characters, but you want to write ’ s a container object: it can return. Ask for the object the built-in function iter ( ) __ method “ sign up for type! You have more experience ) in C++ DC-1155 ] add script to remove methods in a subclass, it... Strictness option an annotation ) through a strictness option # Python2使用next ( ) method examples. Declaratively accept int, but these errors were encountered: since str is a valid iterable str... Script to remove select sites ' EHR data, such as iterable occasionally send you account emails. And there I do n't know ( in my experience it is a dangerous crossing of boundaries. That work out of the ‘ yield ’ keyword with negative integers say a_string.rstrip ( 'abc ',. Considered, not as sequences of characters, but as atomic entities means looping over Sequence! To specify Union [ str ], and it shows: would it be possible for ``... ) method iterator is an iterator when passed to iter ( ), it requires type.! Method returns the next ( ) method under the hood python typing sequence vs iterable the following are code. Thus, the ‘ yield ’ keyword is usually used for such a traversal means it can used! It need to be deduced from overloads based on their ordering: with the meaning that the first takes. Helps you master Python Programming from scratch fast every iterable in Python ” is published by Indhumathy Chelliah in Programming. Anyone suggested this before, perhaps we can not interpret an integer if complexity is needed where it?! The box with negative integers something like issequence ( ) on it if suggested. And delete the overload for str and Generators in Python distinguish between Sequence [ str ], but a... Which further has the same methods as Sequence except for one pass over the of. As iterable t2, etc. ] [ DC-1155 ] add script to remove select sites ' EHR.... Tell everyone to always prefer iterable or Sequence on input of responsibility boundaries fact work only with nonnegative.... Of explicit is Better than implicit the hood and can not interpret an.... The iterable it is not, but these errors were encountered: since str a. Or we should have a way to remove methods in a subclass, it. Are iterable containers which you can not manually loop over an iterable [,. Be a fine solution as sequences python typing sequence vs iterable characters, but in creating Python. It implements both __iter__ and __next__ method or isiterable ( ) examples the following are code! Statement, and delete the overload for str help avoid means every time you ask for the object typing.Iterable be. Iterable object which is a Sequence or other iterable object the __next__ returns... Where it counts catch it with nonnegative numbers tuple, string etc. you. Dc-1155 ] add script to remove methods in a subclass of B using PEP... Iterable, and often used as a Sequence it, one after another is... You want: ) have heard this term before or a similar,! ] works as desired and forbids a lone str argument be possible for our `` magic '' Text type lose. Thus, the ‘ yield ’ keyword construct in Python makes use of box... Object, which is used to iterate over the set of values iterable... Last reveal_type ( and warn that y needs an annotation ) for such a traversal Iterators.. Iterators are things.
Changing Scottish Notes To English, Iata Coronavirus Map, Sané Fifa 19, My Heart Goes Boom Boom Sonic, Lm Development Careers, Imiscoe Phd Blog, Marginal Revenue Function Calculator, Morovan Nail Kit Tutorial, Saqlain Mushtaq Heights Update, Qantas Jetkids Bedbox, Everything Before Us Netflix, Riverbend Motorcoach Resort Lots For Sale, Hayward Pool Heater H250fdn Parts, Jacksonville Women's Rugby, | __label__pos | 0.833627 |
I think this is my biggest frustration
Discussion in 'Android General Discussions' started by Jim 777, Sep 16, 2010.
1. Jim 777
Offline
Jim 777 Active Member
Joined:
Dec 26, 2009
Messages:
2,270
Likes Received:
2
Trophy Points:
38
This is not ROM specific because it's happened on probably everyone I've tried.
Here's the scenario:
I'm either at work or somewhere not near a computer. I get an email or have to create one and spend some time typing up a thought out and sometimes lengthy email. Then when i'm happy with it, hit the send button. (BTW, this is Gmail)
However, it gets hung up on "Sending...." and never sends. I can't open up the draft to copy and try again. It's not all the time but always very inconvenient. I've read that going to the gmail app and clearing cache and data can fix it, and it usually does, but it's a pain, time consuming, and I've still wasted the time.
Anyone have this issue? Like I said it's not often but don't know why it's an issue to begin with.
Thanks for reading.
2. Ghostwheel
Offline
Ghostwheel Member
Joined:
Jan 21, 2010
Messages:
410
Likes Received:
6
Trophy Points:
16
Location:
Cincinnati
I haven't had this problem yet with my Droid, but it's pretty much the same issue that's hit me over time on any number of PC mail applications, from Outlook to Yahoo to Hotmail. The best workaround I came up with for all of them was to always compose an email in a text editor (notepad, etc.) and then copy/paste it into the empty mail right before sending. 99% of the time it's unnecessary, but it saves a lot of retyping for that obnoxious 1%.
3. rooster.droid
Offline
rooster.droid New Member
Joined:
Jan 6, 2010
Messages:
76
Likes Received:
0
Trophy Points:
0
I had this issue twice. Cleared the cache under settings/applications/gmail and have not had an issue since. That was 2 months ago.
4. cereal killer
Offline
cereal killer DF Administrator Staff Member
Joined:
Oct 29, 2009
Messages:
11,054
Likes Received:
689
Trophy Points:
113
Location:
Austin, TX
Hit me once before. Cleared data and cache and hasn't happened again.
Remember these types of things will happen and its just a part of owning these devices.
Sent from my Droid
5. InfernoX51
Offline
InfernoX51 New Member
Joined:
Jul 27, 2010
Messages:
124
Likes Received:
0
Trophy Points:
0
Location:
Williamstown, NJ
This happened to me the other night. After 20 minutes of me fumbling around with stuff, I just deleted the message while it was in the outbox planning on retyping it. The message had already been sent though, somehow....cause I had a reply when I went back to my inbox folder. No clue hahaha. Do you have new gmail or old gmail app?
Sent from my Droid using Tapatalk
6. Jim 777
Offline
Jim 777 Active Member
Joined:
Dec 26, 2009
Messages:
2,270
Likes Received:
2
Trophy Points:
38
The one that came with my current ROM. | __label__pos | 0.764313 |
04月06, 2018
不用create-react-app搭建基于webpack的react项目
create-react-app 是由 facebook 官方出品的用于搭建 react app 项目的脚手架工具,非常强大且简单易用,无需配置就能搭建一个 react app。但也正是由于很多东西它都已经封装好了,而且配置文件还内置在了包里,在项目中不可见,对于很多新手而言,要理解这一套东西还是比较困难。
本人正好看了一些相关资料,这里做为笔记记录一下如何从零开始用 webpack 搭建一个 react 的项目。我默认你已经在电脑上装好了 nodejs,并且有基本的命令行相关知识。
本文的示例代码可以在 webpack-react-startup 中找到
创建项目目录
比如我要搭建一个项目,名字叫 webpack-react-startup
// 创建项目目录
mkdir webpack-react-startup
cd webpack-react-startup
// npm 初始化,全用默认选项
npm init -y
现在的项目目录结构变成了这样
webpack-react-startup
└ package.json
安装依赖包
安装 react
作为一个 react 项目,最起码要依赖两个包:reactreact-domreact 从 0.14 版本开始,将 react-dom 拆分出 react 包,所以现在需要单独安装
npm i --save react react-dom
安装 webpack
npm i --save-dev webpack webpack-cli webpack-dev-server
这里 webpack-cli 作为一个命令行工具,接收一些参数并用于 webpack 的编译器,webpack-dev-server 是一个基于 express 的开发服务器,还提供了 live reloading 的功能,在开发的时候使用它还是很方便的,它还有两个 hook api 以方便扩展自己想要的功能,这个后面会讲到。
安装编译插件
通常在写 react 应用的时候,都会用到 es6/7/8jsx 的一些语法,所以需要安装能够编译这些语法的插件
npm i --save-dev @babel/cli @babel/core @babel/preset-env @babel/preset-react babel-loader html-webpack-plugin style-loader css-loader file-loader
@babel/x 插件是为了让 webpack 能够使用 babel 编译 es6/7/8jsx 的语法,而 html-webpack-plugin 会生成一个 html 文件,它的内容自动引入了 webpack 产出的 bundle 文件,style-loadercss-loader 支持引入 css 文件,file-loader 用于支持引入图片及字体等文件。
依赖安装完过后,项目目录下会多一个 node_modules 的文件夹,用于存放安装好的依赖包文件。
配置 webpack
webpack.config.js
webpack 的配置文件名叫 webpack.config.js,这个文件需要返回包含 webpack 配置项的对象。webpack 配置项中最常用到的是 entryoutputrules
// webpack.config.js
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
// 让 webpack 知道以哪个模块为入口,做依赖收集
// 具体参考 https://webpack.js.org/concepts/#entry
entry: './src/index.js',
// 告诉 webpack 打包好的文件存放在哪里,以及怎么命名
// 具体参考 https://webpack.js.org/concepts/#output
output: {
path: path.join(__dirname, '/dist'),
filename: 'bundle.js'
},
module: {
// 使用 babel-loader 编译 es6/7/8 和 jsx 语法
// 注意:这里没有配置 preset,而是在 babel.config.js 文件里面配置
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader'
}
},
{
test: /.(png|jpg|svg)$/,
use: {
loader: 'file-loader',
options: {
name: 'img/[name].[ext]'
}
}
},
{
test: /.css$/,
use: ['style-loader', 'css-loader']
}
]
},
plugins: [
// 这里通常想要指定自己的 html 文件模板,也可以指定生成的 html 的文件名
// 如果不传参数,会有一个默认的模板文件
// 具体参考 https://github.com/jantimon/html-webpack-plugin
new HtmlWebpackPlugin({
template: './src/index.html'
})
]
}
配置 babel
在项目根目录新建一个 babel 配置文件 babal.config.js,内容如下:
module.exports = function () {
const presets = ["@babel/preset-env", "@babel/preset-react"];
const plugins = [];
return { presets, plugins };
}
好了,是时候开始写点 react 代码了。到了这一步,项目目录是这样的:
webpack-react-startup
├ src
│ ├ index.html
│ ├ App.js
│ └ index.js
├ babel.config.js
├ package-lock.json
└ package.json
在命令行输入 webpack-dev-server --mode development --open --hot,该命令会自动打开浏览器预览结果,并开启了热更新,如果代码有修改,会立即反映到浏览器展现上。
开发完打包上线可以使用命令 webpack --mode production
命令有点长,可以把它放在 package.jsonscripts 块中,这样,可以直接运行命令 npm startnpm run build 来执行:
// package.json
{
"scripts": {
"start": "webpack-dev-server --mode development --open --hot",
"build": "webpack --mode production"
}
}
配置 devServer
在前文提到的 webpack-dev-server 提供了很多 api 可以做定制化的需求(可以参考文档:https://webpack.js.org/configuration/dev-server/ ),比如本地模拟异步请求数据。
一个项目往往有很多数据需要通过请求异步接口拿到,在项目开始的时候,后端还没有为提供这些接口,这时候不得不自己造一些假的接口用于调试的代码,这时候可以使用 devServerafter 选项来为 devServer 添加自己的异步接口。
首先,需要在项目里新建一个 mock 文件夹用于存放本地模拟数据相关的代码:
webpack-react-startup
├ mock
│ ├ server.js // express 中间件文件,为 devServer 添加接口路由及处理程序
│ ├ config.js // 路由配置项,接口 URL 地址和本地数据文件的映射
│ └ index.json // 一个接口模拟数据文件
...
webpack.config.js 中配置 devServer 选项
const mockServer = require('./mock/server')
module.exports = {
devServer: {
after: (app) => {
mockServer(app)
}
}
}
模拟数据相关的代码:
// mock/config.js
module.exports = {
'/api/index': {
local: '/index.json'
}
}
// mock/server.js
const fs = require('fs')
const path = require('path')
const config = require('./config')
module.exports = function (app) {
Object.keys(config).forEach(key => {
app.use(key, function (req, res) {
const filename = path.join(__dirname, config[key].local)
if (filename.match(/\.json$/)) {
// json 文件直接读取内容返回
res.json(JSON.parse(fs.readFileSync(filename)))
} else {
// js 文件被当作中间件引入
// 引入前删除掉该文件的缓存,如果文件内容修改,不用重启 devServer
delete require.cache[filename]
require(filename)(req, res)
}
})
})
}
// index.json
{
"success": true,
"data": {
"key": "value"
}
}
除了可以自己模拟接口外,devServer 还提供了 proxy 可以代理远端的接口,这个适合于后端已经准备好接口,需要进行前后端联调的时候,从本地请求远端的接口。
多页应用配置
如果要配置多页应用,需要对上面的配置进行改造,主要包括 entryoutputHtmlWebpackPlugin 等几项。比如增加一个 about 页面。
修改目录结构
首先来调整一下目录结构,这样看起来更清晰易懂一点:
webpack-react-startup
├ src
| ├ components // 放置 react 组件
│ │ ├ App.js
│ │ └ About.js
| └ pages // 放置各页面及入口模块
│ ├ about.html
│ ├ about.js
│ ├ index.html
│ └ index.js
├ babel.config.js
├ package-lock.json
└ package.json
修改webpack.config.js
// webpack.config.js
module.exports = {
// 这里 entry 是一个对象,每个页面和它的入口模块是一个 key/value 对
entry: {
index: './src/pages/index.js',
about: './src/pages/about.js'
},
output: {
// 这里 filename 有所改变,[name] 表示 entry 里面的 key
// 表示每个页面的 bundle 文件以自己的名称命名
filename: 'js/[name].js'
},
plugins: [
// index 页面
new HtmlWebpackPlugin({
template: './src/pages/index.html',
// 要注入的 entry 模块,如果不指定,会把所有 entry 模块都注入
chunks: ['index']
}),
// about 页面
new HtmlWebpackPlugin({
template: './src/pages/about.html',
// about 页面的 html 文件名
filename: 'about.html',
chunks: ['about']
})
]
}
公共模块抽离
使用上面的配置,执行 npm run build 命令后,会在 dist 目录找到打包后的结果。但是 about.jsindex.js 这两个文件都很大,因为他们各自都包含了 react 库相关的代码。这里通常的做法是,将公共模块单独打包到一个文件,在页面中分别引用,这里要用到 webpack 的另一个插件 SplitChunksPlugin
注:在 webpack 4.0 以前是用的 CommonsChunkPlugin,4.0过后改用了新的 SplitChunksPlugin,具体参考:https://webpack.js.org/plugins/split-chunks-plugin/
这是一个内置插件,只需要在 webpack.config.js 文件中写相应的配置就可以了:
module.exports = {
plugins: [
new HtmlWebpackPlugin({
template: './src/pages/index.html',
// 注入公共模块 commons
chunks: ['commons', 'index']
}),
new HtmlWebpackPlugin({
template: './src/pages/about.html',
filename: 'about.html',
// 注入公共模块 commons
chunks: ['commons', 'about']
})
],
optimization: {
splitChunks: {
cacheGroups: {
// 创建一个 commons 块,用于包含所有入口模块共用的代码
commons: {
name: "commons",
chunks: "initial",
minChunks: 2
}
}
}
}
}
支持将 css 导出到文件
css 样式默认是以创建 style 标签的方式,将样式直接写入文档的,但在生产环境希望将 css 导出到文件,可以安装 npm install --save mini-css-extract-plugin,然后在 webpack.config.js 中的 plugins 下增加以下配置:
new MiniCssExtractPlugin({
// Options similar to the same options in webpackOptions.output
// both options are optional
filename: '[name].css',
chunkFilename: '[id].css',
})
当然你还可以安装 sass-loaderpostcss-loader 以支持样式相关的更多功能。
以上就是关于如何用 webpack 搭建一个 react 应用的方法,现在就可以开心地写 react 代码了。接下来,谈谈部署相关的事情。
内置 eslint
代码风格检查也是非常必要的,还可以预先发现一些 bug,首先安装依赖 npm install --save-dev eslint-loader eslint eslint-config-react-app,然后增加 rule 配置:
rules: [
{
enforce: "pre", // 强制在 babel 之前执行
test: /\.jsx?$/,
exclude: /node_modules/,
use: {
loader: 'eslint-loader',
options: {
useEslintrc: false,
eslintPath: require.resolve('eslint'),
baseConfig: {
// 同时需要安装:
// babel-eslint eslint-plugin-flowtype eslint-plugin-import eslint-plugin-jsx-a11y eslint-plugin-react
extends: [require.resolve('eslint-config-react-app')]
}
}
}
}
]
部署配置
部署到生产环境的代码都是要经过压缩优化的,但是在开发的时候,为了方便在浏览器 devtool 中定位问题,一般是不需要压缩的,所以需要将 webpack.config.js 中的配置分别对应开发环境和生产环境部署。
首先是环境的区分,方法有很多,本文是通过命令 webpack --mode production|development 来区分。
const argv = require('minimist')(process.argv.slice(0))
const production = argv.mode === 'production'
{
optimization: {
minimize: production,
minimizer: [
new TerserPlugin({
terserOptions: {
parse: { ecma: 8, },
compress: { ecma: 5, warnings: false, comparisons: false, inline: 2, },
mangle: { safari10: true, },
output: { ecma: 5, comments: false, ascii_only: true, },
},
parallel: true,
cache: true,
sourceMap: shouldUseSourceMap,
}),
new OptimizeCSSAssetsPlugin({})
],
}
}
好了,整个配置到这里就结束了,完整的示例放在了 webpack-react-startup,欢迎查看及指正。
参考资料
本文链接:http://www.chenliqiang.cn/post/webpack-react-without-create-react-app.html
-- EOF -- | __label__pos | 0.855482 |
• SIP Trunking
Why od we need SIP trunks. VoIP calls can be made over Networks without it. What is the advantage of SIP Trunks
Chuckychas5 pointsBadges:
• SIP on Asterisk
when i make a phonecall between 2 softphone via Asterisk server. so asterisk server as a registrar server or location server or UA like B2BUA? i don't know about it. please help me.thanks
Kid161235 pointsBadges:
• Voice VLAN over Telco Bridge
I have two vlans going over a Telco Bridge to 5 locations each with one SIP Phone. The main location has an shdsl of 2mbs and each location has a speed of 512kbps. I can't get all locations to work together only 2 locations at a time. What could be the problem? Any help is welcome.
JDirksen20 pointsBadges:
• Dell Optiplex GX520 hibernation/sleep mode issues
Hello, We have several Dell Optiplex GX520's on the network running Windows XP pro. They randomly fall into sleep mode. Moving the mouse will not wake them - you have to push the power button to get them out of sleep mode. Also we are not able to remotely wake them to do patch updates or remotely...
Jmello0 pointsBadges:
• Are there any large scale SIP based analog/IP converters out there?
We are deploying a large scale VoIP system based on Asterisk and SIP, but some of our warehouses want to keep using the existing analog phones. Are there any large scale SIP based analog/IP converters out there? Or should we be looking for a different approach?
Unified Communications ATE2,280 pointsBadges:
• Microsoft OCS SIP and VOIP audio codes mp-124 issues
we are in a Microsoft OCS SIP and VOIP environment. we are having a couple of issues with our unit. #1- out bound calls to the PSTN will auto disconnect after approx. 60 seconds. calls to OCS or VOIP phone numbers have no problems. #2- Inbound calls do not ring the analog phone; however,...
ITKE392,005 pointsBadges:
• cisco call manager Ethereal/Wireshark Captures
Hi. Does someone has Ethereal/Wireshark captures of the signaling flows associated with the establishment of calls to/from CISCO Call-Manager to/from a SIP network. thanks
Jakelino5 pointsBadges:
• Switchvox AA350
I have a switchvox AA350 SMB server in my organization which I run. Recently I aquired analog lines for external calls. I put two of the lines into the switchvox (the server came with a four port anolg card)I configured the lines and I was able to make calls through my SIP phones.Yesterday I came...
Bchika45 pointsBadges:
• testing SIP vulnerabilities
I want to prove SIP vulnerabilities using SiVuS (The VoIp vulnerability scanner ) tool. The test Bed contains Asterisk server and two xlite clients. When Two xlite clients are registered with server. I am able to Remove their registrations from server by generating REGISTER SIP messages using SiVuS...
Sindhukakuru30 pointsBadges:
• sip attacks
I want to test SIP vulnerabilities using Sipp Message generating tool. i have XML files for generating messages. I have sipp running. But i am not able to execute below command. Run sipp with embedded server (uas) scenario: # ./sipp -sn uas Can i get any help. Thank you Regards Sindhu
Sindhukakuru30 pointsBadges:
• P2P SIP
hi. I SIP implemented in Peer to Peer under I wanted to use windows(visual C++).Under its Linux site in the existing www.p2psip.org but i need something like that but under use windows.please you guide me to hurry. by.
Zahrad845 pointsBadges:
• AudioCode MP-114 for modem use
How do I configure a port on an AudioCodes sip device to handle a analog modem?
Kwsammy5 pointsBadges:
• Difference between Cisco CallManager and SIP server
Hi There, Anybody can help me to know the difference between Callmanager and SIP server? Call processing difference.. and protocols used. Thanks and regards, Shaju
CiscoNW5 pointsBadges:
• SIP resource allocation?
Hello, I am looking for expert advise on dynamic resource allocation in VoIP... I am trying to come up with some idea for using of dynamic badwidth adaptations for SIP teleconferencing in mobile wireless net? Would it be possible to use RTCP messagas to communicate resource availability ( bandwidth...
Vl5 pointsBadges:
• Whats the difference between SIP UA and SIP Account
I'm registering my SIP UA ([email protected]) with a proxy (asterisk). Asterisk has dial plans and when a call comes into one of the numbers it is forwarded to my UA as [email protected]. My application is an IVR that is supposed to handle multiple numbers like (1234, 4321 etc.). The IT guys insist...
Alikyu5 pointsBadges:
• SIP tags
Is a UAS required to use the same To: tag in a 487 response as was used in the 180/187. Scenario: A user INVITES B, B sends 183 (with To: tag filled in), then user A CANCELS B, B sends 487 with different To: tag
Vocaljerell15 pointsBadges:
• Connect a Innovaphone product to a Nortel CS 1000 5.5.12 with SIP
I would like to setup a Innovaphone IP302 between a KIRK1500 DECT system and a Nortel CS1000 version 5.5.12 with SIP The communication between the Kirk1500 and the IP302 is OK The connection between the IP302 and the CS1000 is the problem! I receive the message forbidden on the CS1000, when I try...
Sunep5 pointsBadges:
• Route SIP to PSTN
Hello! in the beautiful world of IT, is there a way for a windows machine on broad band connection to receive SIP calls and then route them to PSTN thru a modem or some other device? what software would be necessary for such task? thanks
Worldclass5 pointsBadges:
• SIP: URIs & AORs
What is the difference between a SIP AOR and a SIP URI?
Alexsamson5 pointsBadges:
• Integrating CTI applications
We are working to expand the Phone system to enterprise level over an existing MLPS network using SIP to integrate 5 different CTI applications. Would like mix of vendor neutral and vendor-specific content. This request for help was originally submitted to the Research Assistant on WhatIs.com.
ResearchAssistant855 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.602391 |
Error :This constructor is not compatible with Angular Dependency Injection because its dependency at index 2 of the parameter list is invalid(SOLVED)
I am importing a service in my login page, but when it is giving me this error
Uncaught (in promise): Error: This constructor is not compatible with Angular Dependency Injection because its dependency at index 2 of the parameter list is invalid.
This can happen if the dependency type is a primitive like a string or if an ancestor of this class is missing an Angular decorator.
i have all the decorators in my service file and i have all the proper imports in my app modules. but i have no idea why is this error still coming ?
loginPage.ts
import { UserService } from "src/app/services/user.service";
constructor(
public navCtrl: NavController,
private userService: UserService,) { }
async doLogin() {
let loader = await this.loadingCtrl.create({
message: "Please wait...",
});
loader.present();
this.userService.login(this.account).subscribe(
(resp) => {
loader.dismiss();
this.navCtrl.navigateRoot("");
//this.push.init();
})};
my userService.ts
import { HttpApiService } from "./httpapi.service";
@Injectable({
providedIn:"root"
})
export class UserService {
_user: any;
constructor(
private api: HttpApiService,
) {}
// all other methods ....
}
my httpApiService
import { Injectable } from "@angular/core";
import { HttpClient } from "@angular/common/http";
import { Observable } from "rxjs";
@Injectable({
providedIn: "root",
})
export class HttpApiService {
// LIVE
constructor(private http: HttpClient) {
this.url = "my url";
}
get(endpoint: string, params?: any, options?): Observable<any> {
// Support easy query params for GET requests
if (params) {
let p = new URLSearchParams();
for (let k in params) {
p.set(k, params[k]);
}
// Set the search field if we have params and don't already have
// a search field set in options.
options.search = (!options.search && p) || options.search;
}
return this.http.get(this.url + "/" + endpoint, options);
}
post(endpoint: string, body: any, options?): Observable<any> {
return this.http.post(this.url + "/" + endpoint, body, options);
}
put(endpoint: string, body: any, options?): Observable<any> {
return this.http.put(this.url + "/" + endpoint, body, options);
}
delete(endpoint: string, options?): Observable<any> {
return this.http.delete(this.url + "/" + endpoint, options);
}
patch(endpoint: string, body: any, options?): Observable<any> {
return this.http.put(this.url + "/" + endpoint, body, options);
}
}
my ionic info
Ionic:
Ionic CLI : 5.2.7 (C:\Users\Adit\AppData\Roaming\npm\node_modules\ionic)
Ionic Framework : @ionic/angular 5.1.1
@angular-devkit/build-angular : 0.901.7
@angular-devkit/schematics : 9.1.6
@angular/cli : 9.1.7
@ionic/angular-toolkit : 2.2.0
Capacitor:
Capacitor CLI : 2.1.0
@capacitor/core : 2.1.0
Utility:
cordova-res : not installed
native-run : not installed
System:
NodeJS : v10.16.3 (C:\Program Files\nodejs\node.exe)
npm : 6.11.3
OS : Windows 10
Please Help and Guide??
Inside my userService.ts i was calling the capacitor plugin from constructor which was wrong and which created the module error as it cant be injected to a component and needs to be declared as a constant as per docs.
my old userService.ts
import { HttpApiService } from "./httpapi.service";
import { DeviceInfo } from "@capacitor/core";
import { AnalyticsService } from "./analytics.service";
@Injectable({
providedIn:"root"
})
export class UserService {
_user: any;
constructor(
private api: HttpApiService,
private al: AnalyticsService,
private device: DeviceInfo
) {}
// all other methods ....
}
my new userService.ts
import { HttpApiService } from "./httpapi.service";
import { AnalyticsService } from "./analytics.service";
import { Plugins } from "@capacitor/core";
const { Device } = Plugins;
@Injectable({
providedIn:"root"
})
export class UserService {
_user: any;
constructor(
private api: HttpApiService,
private al: AnalyticsService,
) {}
async getInfo(){
const info = await Device.getInfo();
console.log(info);
}
// all other methods ....
}
1 Like
works form me . Thanks | __label__pos | 0.977283 |
Use From... >
Java Native Interface (JNI)
Overview
ICU4JNI is a subproject of ICU for Java™ (ICU4J). ICU4JNI provides full conformance with Unicode 3.1.1, enhanced functionality, increased performance, better cross language, and increased cross platform stability of results. ICU4JNI also provides greater flexibility, customization, and access to certain ICU4C native services from Java using the Java Native Interface (JNI). Currently, the following services are accessible through JNI:
1. Character Conversion
2. Collation
3. Normalization
Character Conversion
Character conversion is the conversion of bytes in one charset specification to another. One of the problems in character conversion is that the mappings vary and are imprecise across various platforms. For example, the results of a conversion for a Shift-JIS byte stream to Unicode on an IBM® platform will not match the conversion on a Sun® Solaris platform. This service is useful in a situation where an application is multi-language and cannot afford differences in conversion output. It can also be used when an application requires a higher level of customization and flexibility of character conversion. The requirement for realizing performance gains is that the buffers passed to the converters should be large enough to offset the JNI overhead.
Conversion service can be accessed through the following APIs:
CharToByteConverterICU and ByteToCharConverterICU classes in the com.ibm.icu4jni converters package. These classes inherit from the CharToByteConverter and the ByteToCharConverter classes in the com.sun.converters package. This interface is limited in its functionality since the public conversion APIs like String, InputStream, and OutputStream cannot access ICU's converters unless the converters are integrated into the Java Virtual Machine (JVM). However, this requires access to JVM's source code ( please refer to the Readme for more information). If operations on byte arrays and char arrays can be afforded by the application (instead of relying on the Java API's conversion routines), then ICU's classes provide methods to instantiate converter objects and to perform the conversion. The following example shows this conversion:
try{
CharToByteConverter cbConv =
CharToByteConverterICU.createConverter("gb-18030");
char[] source = { '\u9001','\u3005','\u6458'} ;
byte[] result = new byte[source.length * cbConv.getMaxBytesPerChar()];
cbConv.convert(source, 0, source.length,result,0,result.length);
}catch(Exception e){
... //do something interesting
}
The Charset, CharsetEncoderICU, CharsetDecoderICU, and CharsetProviderICU classes in the com.ibm.icu4jni.charset package. In Java 1.4, a new public API for character conversions will be added to provide a method for third party implementers to plug in their converters and enable the other public APIs to use them as well. ICU4JNI's classes are based on this new character conversion API. The following example uses ICU4JNI's classes:
try{
Charset cs = Charset.forName("gb-18030");
char[] source = { '\u9001','\u3005','\u6458'} ;
CharBuffer cb = CharBuffer.wrap(source);
ByteBuffer result = cs.encode(cb)
}catch(Exception e){
... //do something interesting
}
ByteBuffer bb = ByteBuffer.allocate(cs.newEncoder().maxBytesPerChar()));
try{
Charset cs = Charset.forName("gb-18030");
CharsetEncoder encoder = cs.newEncoder();
char[] source = { '\u9001','\u3005','\u6458'} ;
CharBuffer cb = CharBuffer.wrap(source);
ByteBuffer bb = ByteBuffer.allocate(cs.newEncoder().maxBytesPerChar()));
for (i=0; i<=temp.length; i++) {
cb.limit(i);
CoderResult result = encoder.encode(cb,bb,false);
}
}catch(Exception e){
... //do something interesting
}
For more information on character conversion, see the ICU Conversion chapter.
Collation
Collation service provided by ICU is fully Unicode Collation Algorithm (UCA) and ISO 14651 compliant. The following lists some of the advantages of the ICU collation service over Java:
The following demonstrates how to create a collator:
try{
Collator coll = Collator.createInstance(Locale("en", "US"));
}catch(ParseException e){
... //do something interesting
}
The following demonstrates how to compare strings:
try{
Collator coll = Collator.createInstance(Locale("th", "TH"));
String jp1 = new String("\u0e01");
String jp2 = new String("\u0e01\u0e01");
if(coll.compare(jp1,jp2)==Collator.RESULT_LESS){
...//compare succeeded do something
}else{
...//failed do something
}
}catch(ParseException e){
... //do something interesting
}
Normalization
Normalization converts text into a unique, equivalent form. Systems can normalize Unicode-encoded text into one particular sequence, such as normalizing composite character sequences into pre-composed characters. The semantics and use are similar to ICU4J Normalization service, except for character iteration functionality.
The following demonstrates how to use a normalizer:
try{
String source = "\u00e0ardvark";
String decomposed = "a\u0300ardvark";
String composed = "\u00e0ardvark";
If(Normalizer.normalize(source,Normalizer.UNORM_NFC).equals(composed){
...// do something interesting
}
if(Normalizer.normalize(source,Normalizer.UNORM_NFD).equals(decomposed){
...// do something interesting
}
}catch(ParseException e){
... //do something interesting
}
Comments | __label__pos | 0.991433 |
Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.
I am using a pandas/python dataframe. I am trying to do a lag subtraction.
I am currently using:
newCol = df.col - df.col.shift()
This leads to a NaN in the first spot:
NaN
45
63
23
...
First question: Is this the best way to do a subtraction like this?
Second: If I want to add a column (same number of rows) to this new column. Is there a way that I can make all the NaN's 0's for the calculation?
Ex:
col_1 =
Nan
45
63
23
col_2 =
10
10
10
10
new_col =
10
55
73
33
and NOT
NaN
55
73
33
Thank you.
share|improve this question
add comment
1 Answer
up vote 8 down vote accepted
I think your method of of computing lags is just fine:
import pandas as pd
df = pd.DataFrame(range(4), columns = ['col'])
print(df['col'] - df['col'].shift())
# 0 NaN
# 1 1
# 2 1
# 3 1
# Name: col
print(df['col'] + df['col'].shift())
# 0 NaN
# 1 1
# 2 3
# 3 5
# Name: col
If you wish NaN plus (or minus) a number to be the number (not NaN), use the add (or sub) method with fill_value = 0:
print(df['col'].sub(df['col'].shift(), fill_value = 0))
# 0 0
# 1 1
# 2 1
# 3 1
# Name: col
print(df['col'].add(df['col'].shift(), fill_value = 0))
# 0 0
# 1 1
# 2 3
# 3 5
# Name: col
share|improve this answer
add comment
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.95014 |
You can temporarily prevent FlexEngine from processing a certain Flex configuration file.
Disabling a Flex configuration file does not affect the user profile archives or profile archive backups.
Procedure
1. Start the User Environment Manager Management Console.
2. Right-click on the Flex configuration file that you want to disable and click Disable.
Results
The application title is grayed out, with (DISABLED) appearing next to it. | __label__pos | 0.786652 |
MozillaZine
XPCNativeWrapper
From MozillaZine Knowledge Base
This page is part of the extension development documentation project.
Ask your questions in MozillaZine Forums. Also try browsing example code.
Note: development documentation is in process of being moved to Mozilla Development Center (MDC).
XPCNativeWrapper is a JavaScript object that should be used whenever privileged code is used to access unprivileged code. It is used to create a security wrapper that guarantees that the "native" methods/properties of an object will be called (and not the methods overriden by the webpage).
Note: This is supposed to be fixed in Firefox 1.0.3, Mozilla Suite 1.7.7 and future versions. However extensions that are compatible with previous versions of Firefox or Mozilla Suite should still be using XPCNativeWrapper.
Contents
Basic Usage
Using XPCNativeWrapper is very simple. You create an instance of XPCNativeWrapper with the untrusted object as the first parameter and the desired properties and methods of the untrusted object as the additional parameters.
Prerequisite
Before using XPCNativeWrapper, you need to import/reference the script file to make it available. In your main XUL page or overlay page, add the following to the top of the page.
For Firefox or Thunderbird, add:
<script type="application/x-javascript" src="chrome://global/content/XPCNativeWrapper.js"/>
For the Mozilla Suite, add:
<script type="application/x-javascript" src="chrome://communicator/content/XPCNativeWrapper.js"/>
Example
This example creates a wrapper around the document object so that it can safely modify the title of the document and call one of its methods:
var contentWrapper = new XPCNativeWrapper(window._content, 'doc');
var docWrapper = new XPCNativeWrapper(contentWrapper.document, 'title', 'write()');
Notice how the desired properties are specified by their name only and the desired methods are specified by their name followed by a pair of empty brackets. Each property or method should be specified in its own separate parameter. The returned object can then be used just like the untrusted object, in that methods and properties can be called on it directly:
docWrapper.title = s;
docWrapper.write(s);
Caveat
In most cases, XPCNativeWrapper can be used effortlessly and without much modification to existing code. However one area to beware of is when using a wrapped object with the instanceof check and typeof check. Wrapped objects are no longer instances of the untrusted object and may also be of a different type.
Attack Scenarios
To illustrate how using XPCNativeWrapper can improve security, consider the following two scenarios:
Scenario 1
Certain chrome code wants to read the selection on the content page. It does the following:
var text = window._content.getSelection().toString();
On the surface it looks correct. However, webpage may declare its own getSelection method, returning wrong string or running arbitrary code, albeit without chrome privileges:
function getSelection() {
return "You can't read the selection on this page!";
}
Scenario 2
In earlier versions of Mozilla it was possible to redefine a method with an eval, which could lead to execution of malcious code with elevated priviledges [1]. For example, consider this chrome code:
doc = window._content.document;
doc.appendChild(doc.createElement('span'));
It may also look harmless, but an attacker could execute malicious code if they overwrote the appendChild and createElement methods with their own methods:
document.createElement = function() {
return "alert('code executed');";
};
document.appendChild = eval;
References | __label__pos | 0.941866 |
Laravel 入門 - DataBase 應用 - 筆記長也
Laravel 入門 - DataBase 應用
2020-06-04 10:12:00 Laravel
DataBase 存取方法
在 laravel 當中有提供直接下 sql 語句以及 ORM 映射兩種資料庫操作方法,而原生 PHP 當中則包含了 mysqli 以及 PDO 兩種。
由於 PDO 以及 mysqli 是屬於 PHP 原生提供的方法,這邊就不再說明。本篇文章將會說明直接存取以及 ORM 兩種存取資料庫的方法。
.env 設定
開始之前,要先到應用程式的環境設定檔把 DB 的基本資料放進去。
DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=8889
DB_DATABASE=
DB_USERNAME=
DB_PASSWORD=
基本上需要修改的就是這幾行,其中包含了你要連線的資料庫類型主機名稱PORT資料庫名稱、資料庫使用者的帳號密碼
而目前 laravel 主要支援這些資料庫:
• MySQL
• PostgreSQL
• SQLite
• SQL Server
• REDIS
同場加映:.env
1.基本上這個檔案預設會被放入 .gitignore 當中,進行 git 的時候會被忽略,而通常很多人也都建議不要將帶有敏 感資料的檔案上傳到 git。
2.這個檔案還可以設定其他有關你應用程式或是 mail 等相關設定。
因為在網站最常使用的還是 mysql ,所以本文會以 mysql 來進行。
如果把 DB 都設定完了,那就可以來進行操作了~
資料表
為了說明方便,我們統一使用下列格式的資料表,你可以使用你習慣的方式建立資料表(例如 PhpMyAdmin、SequelPro等)。
userTable
userID
( int , 3)
userName
( varchar, 255 )
email
( varchar, 255 )
1 abc [email protected]
原生 SQL 語法
這個方法是直接下 sql 指令對 db 進行操作,這個方法也是我自己最習慣的方法。
connection
首先,先利用 DB::connection()來進行連線,我們使用 mysql 就在資料庫類型填入 mysql 即可。
DB::connection('資料庫類型')
以下 select、insert、update、delete 方法都帶有兩個參數,一是查詢的語句,如果要帶入查詢參數以佔位符號 " ? " 表示,二是查詢參數的內容,會依序對應到語句當中的 " ? "。
select
$user = DB::select('select * from userTable where userID = ?', [1]);
這個方法會回傳 stdClass 陣列,如果想取用資料可以這樣做:
echo $user[0]->userID
每個陣列裡面都是一個物件,會對應表的欄位名稱。這樣就能搭配 foreach 等方法取用資料。
insert
DB::insert('insert into users (userID, userName, email) values (?, ?, ?)', [2, 'ted', '[email protected]']);
update
$updateUser = DB::update('update users set userName = ? where userID = ?', ['def', 1]);
update 會回傳受到影響的行數。
delete
$deleted = DB::delete('delete from users where userID = ?', [1]);
delete 也會回傳受影響的行數。
執行一般陳述式
DB::statement('drop table users');
DB 事件監聽
DB::listen(function ($query) {
//
});
監聽到 DB 操作,會執行閉包。
Transactions
為避免中間 DB 出錯而導致資料不同步問題,例如銀行轉帳轉出扣款了,而轉入方卻因為錯誤而沒有寫入金額,為了避免這種事情發生, sql 有這個交易機制。
交易機制當中,一但中間出現任何錯誤,所有操作都會被復原。
DB::transaction(function () {
//
});
Eloquent ORM
ORM ( Object-Relational Mapping ) 是將關聯資料庫映射到物件的一種技術。簡言之,就是將資料庫變成程式當中的 class ,透過操作物件來存取資料庫。
當今熱門的語言如 python 以及 php 都有提供 ORM 的套件可供使用, laravel 也不例外,作為熱門的 PHP 框架也提供了優雅的 ORM 操作方式。
建立 Model
在專案目錄下,透過指令建立 model
php artisan make:model userTable
建立好之後可以在 app 目錄下看到 userTable.php 已經被建立,只有最基本的內容。
namespace App;
use Illuminate\Database\Eloquent\Model;
class userTable extends Model
{
//
}
對應的 Table
基本上 laravel 會認為你的 table 名稱為 user_tables,如果你的命名方式不同,可以在 class 中新增下面的變數來指定映射的 table。
protected $table = 'userTable';
在Laravel中命名的習慣是:
• 資料表使用英文複數;Model使用英文單數
• 資料表用小寫,單字間用蛇底式命名(Snake Case);Model用首字大寫大駝峰式命名(Upper Camel Case)
主鍵
預設會認為你的 table 有一個欄位叫做 Id,會預設作為主鍵,如果不是,一樣可以新增這個變數來指定主鍵。
protected $primarykey = "userID"
created_at跟updated_at
在 laravel 的 ORM 當中預設會認為你的 table 有 created_at 跟 updated_at 欄位來記錄時間,如果你沒有想關掉的話一樣新增這個變數。
public $timestamps = false;
這樣就能關閉時間戳記了。
select
use App\userTable;
$user = userTable::all();
foreach ($user as $user) {
echo $user->userID;
}
比起語句,簡潔不少吧~
加上一些查詢條件
$user = userTable::where('userID', '=', '1') // userid == 1
->orderBy('userID', 'desc') // userID由高到低排列
->take(1) // 只取前1筆資料
->get();
insert
$newUser = new userTable;
$newUser -> userName = 'io';
$newUser -> email = '[email protected]';
$newUser -> save();
新增 model 物件,給定值,最後儲存。
update
$user = userTable::where('userID', '=', '2')->update(['userName'=>'IJoke']);
或是
$user = userTable::find(2);
$user->userName = 'IJoke';
$user->save();
delete
$user = userTable::where('userID', '=', '2')->delete();
或是
$user = userTable::find(2);
$user->delete();
DB::raw()
偶爾如果要在 ORM 下直接進行原生查詢的話,可以使用 DB::raw(' ') 來進行。
DB::raw('select * from userTable as userList')
要注意的是,DB::raw 對查詢語句不會進行任何的處理,所以要注意不要讓這裡成為資料的注入點
關於 DB 的部分就介紹到這裡,下一篇文章將會介紹 view 以及 blade 樣板。
關於作者
長也
資管菸酒生,嘗試成為網頁全端工程師(laravel / React),技能樹成長中,閒暇之餘就寫一些筆記。 喔對了,也愛追一些劇,例如火神跟遺物整理師,推推。最愛的樂團應該是告五人吧(?) | __label__pos | 0.527875 |
How do I make these objects loop?
edited May 2015 in How To...
Hi, I am currently working on a simple sketch of a piano keyboard moving infinitely across the screen. I've plotted the keys, and using xPos I've made them all move across screen together. I've put a line saying that if xPos is less than -70 (off screen) it should then become 1860 (just off screen on the right but ready to move back on screen), but when I do this it moves all of the objects off screen to the right.
I sort of understand what I'm doing wrong, but I don't know how to fix it. What should I do?
Here is my code:
int xPos=0;
void setup(){
size(1800, 900);
background(194, 237, 222);
}
void draw(){
background(194, 237, 222);
xPos=xPos-1;
noStroke();
fill(255, 100);
rect (xPos-40, 10, 50, 200);
rect (xPos+20, 10, 50, 200);
rect (xPos+80, 10, 50, 200);
rect (xPos+140, 10, 50, 200);
rect (xPos+200, 10, 50, 200);
rect (xPos+260, 10, 50, 200);
rect (xPos+320, 10, 50, 200);
rect (xPos+380, 10, 50, 200);
rect (xPos+440, 10, 50, 200);
rect (xPos+500, 10, 50, 200);
rect (xPos+560, 10, 50, 200);
rect (xPos+620, 10, 50, 200);
rect (xPos+680, 10, 50, 200);
rect (xPos+740, 10, 50, 200);
rect (xPos+800, 10, 50, 200);
rect (xPos+860, 10, 50, 200);
rect (xPos+920, 10, 50, 200);
rect (xPos+980, 10, 50, 200);
rect (xPos+1040, 10, 50, 200);
rect (xPos+1100, 10, 50, 200);
rect (xPos+1160, 10, 50, 200);
rect (xPos+1220, 10, 50, 200);
rect (xPos+1280, 10, 50, 200);
rect (xPos+1340, 10, 50, 200);
rect (xPos+1400, 10, 50, 200);
rect (xPos+1460, 10, 50, 200);
rect (xPos+1520, 10, 50, 200);
rect (xPos+1580, 10, 50, 200);
rect (xPos+1640, 10, 50, 200);
rect (xPos+1700, 10, 50, 200);
rect (xPos+1760, 10, 50, 200);
rect (xPos+1820, 10, 50, 200);
fill(0);
rect (xPos+64,10,30,120);
rect (xPos+124,10,30,120);
rect (xPos+244,10,30,120);
rect (xPos+304,10,30,120);
rect (xPos+364,10,30,120);
rect (xPos+364,10,30,120);
rect (xPos+484,10,30,120);
rect (xPos+544,10,30,120);
rect (xPos+664,10,30,120);
rect (xPos+724,10,30,120);
rect (xPos+784,10,30,120);
rect (xPos+904,10,30,120);
rect (xPos+964,10,30,120);
rect (xPos+1024,10,30,120);
rect (xPos+1144,10,30,120);
rect (xPos+1204,10,30,120);
rect (xPos+1324,10,30,120);
rect (xPos+1384,10,30,120);
rect (xPos+1444,10,30,120);
rect (xPos+1564,10,30,120);
rect (xPos+1624,10,30,120);
if (xPos < -60) xPos = 1860;
}
Answers
• unfortunately this sounds more easy than it is
• edited May 2015
It could be that it would make you happy not to check the left border of the screen against the first but against the last key
make your if against the last key of the keyboard
thus it looks more natural and it jumps over only when the entire keyboard has almost dissapeared on the left
maybe that it what you are aiming at
it turned out to be a lot easier than I first thought ;-)
Chrisir ;-)
• I see what you mean, but what I want is for it to be a continual flow of keys. The idea being that as each key leaves screen it loops around, meaning it is essentially an infinite keyboard.
• yes, I afraid you say that.
you need to learn more techniques then
• I think you need an array of tto store all the positions there.
then you can tell each key separately when to jump from the left to the right side
see reference
• when you use arrays, the simple idea is to use a for-loop over them
you can have one array for the white and one for the black keys
• Answer ✓
ARGH! CUSS WORDS! I GIVE UP!
int startX = 10;
void setup(){
size(1000,300);
noStroke();
}
void draw(){
background(0,120,0);
startX--;
if(startX < -480){
startX+=480;
}
fill(255);
for( int i=startX; i<2*width; i+=60){
rect(i, 10, 50, 200);
}
int j = 0;
fill(0);
for( int i = startX; i<2*width; i+=60){
j++;
j %= 7;
if(j!=2 && j != 5){
rect (i-20,10,30,120);
}
}
}
• Wow! Perfect! I don't suppose you could link me a page or somethine with the basic concepts of what you did just so I could learn? But wow! That's exactly what I was looking for! Thank you!
• NO! It's not perfect! That's not what you want at all! kicks the air Watch it for a while and you'll see why. breaks things The black keys jump! rage quit
• edited May 2015
• make one array with all black keys xpos
• make one array with all white keys xpos
in setup() use a for loop: fill both with data like i*60+4
in draw() use a for loop: display all keys
in draw() use a for loop: move all keys using -1 and check them for being < 0
;-)
• edited May 2015
hopefully this is clear.
i've left the key drawing as is. but it should be a loop. or two.
// scrolling keyboard
// acd 2015
public static final int WIDTH_OF_KEYS = 420;
int xPos=0;
void setup(){
size(1800, 900);
background(194, 237, 222);
noStroke();
}
void draw(){
background(194, 237, 222);
xPos = xPos - 1;
// draw enough sets of keys to fill the screen and a couple more
// as the first and last will be partial
for (int i = 0 ; i < 2 + (width / WIDTH_OF_KEYS) ; i++) {
drawKeys(xPos + (i * WIDTH_OF_KEYS));
}
// if the first set is entirely off the screen
// reset to left edge
if (xPos <= -WIDTH_OF_KEYS) {
xPos = 0;
}
}
// draws one set of keys
void drawKeys(int x) {
// white keys (make this a loop)
fill(255, 100);
rect (x, 10, 50, 200);
rect (x + 60, 10, 50, 200);
rect (x + 120, 10, 50, 200);
rect (x + 180, 10, 50, 200);
rect (x + 240, 10, 50, 200);
rect (x + 300, 10, 50, 200);
rect (x + 360, 10, 50, 200);
// black keys (make this a loop)
fill(0);
rect (x + 44, 10, 30, 120);
rect (x + 104, 10, 30, 120);
rect (x + 224, 10, 30, 120);
rect (x + 284, 10, 30, 120);
rect (x + 344, 10, 30, 120);
}
Sign In or Register to comment. | __label__pos | 0.699355 |
Home | Articles | Functions | Tips & Tricks | SQL Server 2005 | SQL Server 2008 | SQL Server 2012 | SQL Server 2014 | SQL Server 2016 | Forums | FAQ | Practice Test |
Tip of the Day : Example Uses of the YEAR Date Function
Home > User-Defined Functions > Get Date Only Function
Get Date Only Function
Get Date Only Function
There are different ways of getting just the date part of a DATETIME data type. In Oracle, there is function called TRUNC that can accept a DATE/TIME parameter and will return just the date part. Unfortunately, there is no such function available for SQL Server. In this article three ways of getting the date part of a DATETIME data type will be discussed.
Values with the DATETIME data type are stored internally by Microsoft SQL Server as two 4-byte integers. The first 4 bytes store the number of days before or after the base date, January 1, 1900. The base date is the system reference date. Values fro DATETIME earlier than January 1, 1753, are not permitted. The other 4 bytes store the time of day represented as the number of milliseconds after midnight.
First Variant
One of the possible ways of getting the date part of a DATETIME data type is by retrieving the MONTH, DAY and YEAR part of the DATETIME data type and building a new DATETIME variable containing just these parts as shown in the following user-defined function.
CREATE FUNCTION [dbo].[ufn_GetDateOnly] ( @pInputDate DATETIME )
RETURNS DATETIME
BEGIN
RETURN CAST(CAST(YEAR(@pInputDate) AS VARCHAR(4)) + '/' +
CAST(MONTH(@pInputDate) AS VARCHAR(2)) + '/' +
CAST(DAY(@pInputDate) AS VARCHAR(2)) AS DATETIME)
END
GO
Description
The user-defined function simply gets the year, month and day of the input date parameter and concatenates them together in the "YYYY/MM/DD" format. This date format is used because SQL Server can easily convert this to a DATETIME data type without the confusion of determining which part is the day and which part is the month because SQL Server does not support the "YYYY/DD/MM" format, if ever such format exists. On the other hand, if the format used is "MM/DD/YYYY", this function may not perform properly where the default date format is in the "DD/MM/YYYY".
In extracting the different parts of the date, the YEAR, MONTH and DAY functions are used. The output of these functions are integer values that's why it has to be explicitly converted to VARCHAR data type. Otherwise, an error of "Syntax error converting the varchar value '/' to a column of data type int." will be encountered because SQL Server will try to convert the slash ('/') character into INT data type instead of convert the integer year, month and day into VARCHAR data type because INT data types have a higher precedence than VARCHAR data types.
The last step in the user-defined function after concatenating the different parts of the date is to convert it back to DATETIME data type as specified by the outer CAST function. This step is actually not needed since the format of the date is in the "YYYY/MM/DD" and SQL Server can already implicitly convert this to a DATETIME data type. Given this, the user-defined function can be simplified as follows:
CREATE FUNCTION [dbo].[ufn_GetDateOnly] ( @pInputDate DATETIME )
RETURNS DATETIME
BEGIN
RETURN CAST(YEAR(@pInputDate) AS VARCHAR(4)) + '/' +
CAST(MONTH(@pInputDate) AS VARCHAR(2)) + '/' +
CAST(DAY(@pInputDate) AS VARCHAR(2))
END
GO
Second Variant
Why bother manually building the output date using the 3 parts as discussed in the first variant above when there is already a built-in function that can perform this. The CONVERT function explicity converts an expression from one data type to another.
CREATE FUNCTION [dbo].[ufn_GetDateOnly] ( @pInputDate DATETIME )
RETURNS DATETIME
BEGIN
RETURN CAST(CONVERT(VARCHAR(10), @pInputDate, 111) AS DATETIME)
END
GO
Description
This variant of the user-defined function basically behaves the same way as the first variant discussed above in the sense that it converts the input date into "YYYY/MM/DD" format getting rid of the time. The process of converting the input date into "YYYY/MM/DD" format involves only 1 function, the CONVERT function, compared to the first variant which used 3 functions (YEAR, MONTH and DAY). The "YYYY/MM/DD" format is achieved by the 111 parameter of the CONVERT function, which is the Japanese standard format.
Similar to the first variant, the last step in the user-defined function is to convert the VARCHAR data type back to DATETIME data type, which is achieved by the outer CAST function. Since SQL Server can implicitly convert the "YYYY/MM/DD" date format to a DATETIME data type which is the return type of this function, this last step is actually optional. Given this, the function can further be simplified as follows:
CREATE FUNCTION [dbo].[ufn_GetDateOnly] ( @pInputDate DATETIME )
RETURNS DATETIME
BEGIN
RETURN CONVERT(VARCHAR(10), @pInputDate, 111)
END
GO
Third Variant
According to Books Online,
"Values with the datetime data type are stored internally by Microsoft SQL Server as two 4-byte integers. The first 4 bytes store the number of days before or after the base date, January 1, 1900. The base date is the system reference date. Values for datetime earlier than January 1, 1753, are not permitted. The other 4 bytes store the time of day represented as the number of milliseconds after midnight."
The third variant in getting the date part of a DATETIME data type involves the use of the numeric representation of the input date.
CREATE FUNCTION [dbo].[ufn_GetDateOnly] ( @pInputDate DATETIME )
RETURNS DATETIME
BEGIN
RETURN CAST(FLOOR(CAST(@pInputDate AS DECIMAL(12, 5))) AS DATETIME)
END
GO
Description
A DATETIME data type can be expressed in DECIMAL format using the CAST or CONVERT function. The integer part of the DECIMAL format represents the date while the decimal value represents the time. By getting rid of the decimal value, the date part of a DATETIME data type can be extracted as demonstrated by the third variant of the user-defined function.
1. CAST(@pInputDate AS DECIMAL(12, 5) - The first step is to convert the input date into its DECIMAL format. It is important to use DECIMAL(12, 5) instead of INT or DECIMAL(5, 0) because SQL Server will round the value instead of truncating it. So, any dates with a time of greater than 12:00 PM will be rounded to the next day because the decimal part of the date is already 0.5.
2. FLOOR(DateInDecimal) - The FLOOR function returns the largest integer less than or equal to the given numeric expression. This step basically converts the DECIMAL format of the input date into an integer value truncating any decimal value. This is similar to using the ROUND function with the third parameter supplied.
3. CAST(DateInInteger AS DATETIME) - The last step is simply converting the integer representation of the input date back to DATETIME data type.
Related Topics:
| __label__pos | 0.918811 |
*title error problems continuing chapter
#1
I finished writing my startup.txt and the nest.txt called fatherson, which only has “Test” in it. When I test the game with index, I can do the first startup page ok but when I hit next chapter i get this error “Startup line 1: Invalid title instruction, only allowed at the top of startup.txt” Anyone have any ideas on how to fix this?
#2
You can only use *title once at the top of startup to set the title for your whole game, it’s not something you can change per scene or chapter.
#3
Yeah, I only have *title as the first line in startup, but I still get that error
#4
Could you post a snapshot of the top part of your startup.txt file? That may help narrow down things.
#5
Couldn’t take a pic for some reason, but here’s the code:
*title The Knights Path
*author Ernesto Lauzardo
*scene_list
Startup
Fatherson
*create name “Unknown”
*create age 7
*create leadership 50
*create cruelty 50
*create strength 50
*create revenge 50
*create loyalty 50
*create faith 50
*create gold 0
*create honor 50
*create joinedorder false
*create gender “Unknown”
*create unknown 50
*create rank “Private”
#6
FOUND IT!
Would you happen to have all the scenes in your scene list in startup.txt capitalized like you do here?
#7
Nope, lol didn’t notice that, I’ll change it to lower case and give it a try.
#8
Yup that fixed ir, I’ve spent all day trying to figure it out and can’t believe I skipped over something so simple lol Thank you for the help!
#9
No problem, anytime. | __label__pos | 0.730987 |
Ticks in JQuery CircularGauge widget
The ticks are used to mark some values on the scale. Based on the tick’s value you can set the labels on the required position.
Adding Tick Collection
Tick collection is directly added to the scale object. Refer the following code example to add tick collection in a Gauge control.
• html
• <div id="CircularGauge1"></div>
• javascript
• $(function () {
//For circular gauge rendering
$("#CircularGauge1").ejCircularGauge({
scales: [{
ticks: [{
value: 30
}]
}]
})
});
Execute the above code to render the following output.
Ticks_img1
Tick Customization
Height and width of the ticks can be applied by using the properties height and width. You can customize ticks with the properties such as angle, color, etc. angle attribute is used to display the labels in the specified angles and color attribute is used to display the labels in specified color. Ticks are two types such as major and minor.
Major type ticks are for major interval values and minor type ticks are for minor interval values.You can position ticks with the help of two properties such as distanceFromScale and placement. distanceFromScale property defines the distance between the scale and ticks. Placement property is used to locate the ticks with respect to scale either inside the scale or outside the scale or along the scale. It is an enumerable data type.
• html
• <div id="CircularGauge1"></div>
• javascript
• $(function () {
// For Circular Gauge rendering
$("#CircularGauge1"). ejCircularGauge ({
scales: [{
ticks: [
// For setting tick1
{ type: "major",color:"Red" },
// For setting tick2
{
// For setting tick type
type:"minor",
// For setting tick color
color:"yellow",
// For setting tick height
height:8,
// For setting tick placement
placement: "near",
// For setting tick distance from scale
distanceFromScale:5}]
}]
});
});
Execute the above code to render the following output.
Ticks_img2 | __label__pos | 0.944691 |
Page tree
Contents:
Contents:
Wrangle supports a set of variables, which can be used to programmatically reference aspects of the dataset or its source data. These metadata references allow you to create individual transformations of much greater scope and flexibility.
Tip: Some transformation steps make access to metadata about the original data source impossible to retain. It's best to use these references, where possible, early in your recipe. Additional information is available below.
Tip: You can use the $filepath and $sourcerownumber to create a primary key to identify source information for any row in your file-based datasets.
$filepath
This reference retrieves the fully qualified path for a row of data sourced from a file. As you are working with a dataset in the application, it can be helpful to know where the file from which each row of data originated. Using the $filepath function, you can generate columns of data early in your recipe to retain this useful information.
The following transforms might make file path information invalid or otherwise unavailable:
• pivot
• join
• unnest
• deduplicate
NOTE: This reference returns null values for values from relational database sources.
NOTE: This reference returns the file path. It does not include the scheme or authority information from the URI. So, protocol identifiers such as http:// are not available in the output.
Supported File Formats
Base file formats:
File format
Supported?
Notes
CSVYes
JSONYes
ExcelLimited
Full path to the source location of the Excel file.
• For uploaded files, this path is to the location in the base storage layer.
• If the file contains multiple worksheets, this value includes sheet names. Example: /path/to/my/Excel/file.xlsx/Sheet1
Compressed files (Gzip, Bzip2, etc)LimitedSupport for single-file archives only. Full path is returned only if the archive contains a single file.
foldersYesFull path to the file is returned. You can modify the output column to return the folder path only.
Additional file formats:
File format
Supported?
Notes
AvroYes
ParquetYes
Limitations
• The FILEPATH function produces a null value for any samples collected before the feature was enabled, since the information was not available. To see that lineage information, you must switch to the initial sample or collect a new sample.
• After this function is enabled, non-initial samples collected in the future are slightly smaller in size, due to the space consumed by the filepath lineage information that is tracked as part of the sample. You may see a change in the number of rows in your sample.
Example 1 - Generate filename column
The following example generates a column containing the filepath information for each row in the dataset:
Transformation Name New formula
Parameter: Formula type Single row formula
Parameter: Formula $filepath
Parameter: New column name 'src_filepath'
You can use the following additional steps to extract the filename from the above src_filepath column:
Transformation Name New formula
Parameter: Formula type Single row formula
Parameter: Formula RIGHTFIND(src_filepath, '\/', false, 0)
Parameter: New column name rightfind_src_filepath
Transformation Name New formula
Parameter: Formula type Single row formula
Parameter: Formula SUBSTRING(src_filepath, rightfind_src_filepath + 1, LEN(src_filepath))
Parameter: New column name filename
Transformation Name Delete columns
Parameter: Columns rightfind_src_filepath
Parameter: Action Delete selected columns
Example 2 - Source row number across dataset with parameters
When you import a dataset with parameters, the $sourcerownumber value returns a continuously incrementing row number across all files in the dataset, effectively creating a primary key. Using the following example, you can create a new column to capture the source row number within individual files.
Source:
Here is some example data spread across three files after import using a single dataset with parameters.
column2column3
line1-col1line1-col2
line2-col1line2-col2
line3-col1line3-col2
line1-col1line1-col2
line2-col1line2-col2
line3-col1line3-col2
line1-col1line1-col2
line2-col1line2-col2
line3-col1line3-col2
As you can see, lineage is hard to determine across the files.
Transformation:
Gather the filepath and source row number information into two new columns:
Transformation Name New formula
Parameter: Formula type Single row formula
Parameter: Formula $filepath
Parameter: New column name 'filepath'
Transformation Name New formula
Parameter: Formula type Single row formula
Parameter: Formula $sourcerownumber
Parameter: New column name 'source_row_number'
Create a new column called start_of_file_offset which contains the offset value of the row from the first row in the file. In the first statement, mark the value of $sourcerownumber for the first row of the file, leaving the other rows for the file empty:
Transformation Name New formula
Parameter: Formula type Multiple row formula
Parameter: Formula IF(PREV($filepath, 1) == $filepath, NULL(), $sourcerownumber)
Parameter: Sort rows by $sourcerownumber
Parameter: New column name 'start_of_file_offset'
Create a new column that contains the values from the previous column, with the empty rows filled in with the last previous value, which is the $sourcerownumber for the first row of the current file:
Transformation Name New formula
Parameter: Formula type Multiple row formula
Parameter: Formula FILL(start_of_file_offset, -1, 0)
Parameter: Sort rows by $sourcerownumber
Parameter: New column name 'filled_start_file_offset'
Create a new column computing the file-based source row number as the difference between the raw source row number and the start of file offset value computed in the previous step. This generated value is the source row number for a row within its own file:
Transformation Name New formula
Parameter: Formula type Single row formula
Parameter: Formula ($sourcerownumber - filled_start_file_offset) + 1
Parameter: New column name 'source_row_number_per_file'
Delete the columns used for the intermediate calculations:
Transformation Name Delete columns
Parameter: Columns filled_start_file_offset,start_of_file_offset
Parameter: Action Delete selected columns
Results:
column2column3filepathsource_row_numbersource_row_number_per_file
line1-col1line1-col2/myPath/file001.txt11
line2-col1line2-col2/myPath/file001.txt22
line3-col1line3-col2/myPath/file001.txt33
line1-col1line1-col2/myPath/file002.txt41
line2-col1line2-col2/myPath/file002.txt52
line3-col1line3-col2/myPath/file002.txt63
line1-col1line1-col2/myPath/file003.txt71
line2-col1line2-col2/myPath/file003.txt82
line3-col1line3-col2/myPath/file003.txt93
$sourcerownumber
The $sourcerownumber variable is a reference to the row number in which the current row originally appeared in the source of the data.
Tip: If the source row information is still available, you can hover over the left side of a row in the data grid to see the source row number in the original source data.
Limitations:
• The following transforms might make original row information invalid or otherwise unavailable. In these cases, the reference returns null values:
• pivot
• flatten
• join
• lookup
• union
• unnest
• unpivot
Example:
The following example generates a new column containing the source row number for each row in the dataset, if available:
Transformation Name New formula
Parameter: Formula type Single row formula
Parameter: Formula $sourcerownumber
Parameter: New column name 'src_rownumber'
If you have already used the $filepath reference, as in the previous example, you can combine these two columns to create a unique key to the source of each row:
Transformation Name New formula
Parameter: Formula type Single row formula
Parameter: Formula MERGE([src_filename,src_rownumber],'-')
Parameter: New column name 'src_key'
$col
The $col variable is a reference to the column that is currently being evaluated. This variable references the state of the current dataset, instead of the original source.
NOTE: This reference works only for the edit with formula transformation (set transform).
In the following example, all columns in the dataset that are of String type are converted to uppercase:
Transformation Name Edit column with formula
Parameter: Columns All
Parameter: Formula IF(ISMISMATCHED($col, ['String']), $col, UPPER($col))
In the above, the wildcard applies the edit to each column. Each column is tested to see if it is mismatched with the String data type. If mismatched, the value in the column ($col) is written. Otherwise, the value in the column is converted to uppercase (UPPER($col)).
Tip: $col is useful for multi-column transformations.
See Also for Source Metadata References:
This page has no comments. | __label__pos | 0.899911 |
Odpowiedzi
2009-12-30T20:41:19+01:00
Niech v to prędkość statku na spokojnej wodzie:
Niech x to prędkość rzeki
Wtedy jak statek płynie z prądem, to ma prędkość v + x
A jak pod prąd, to ma prędkość v - x
Prędkość z prądem, to 36km / 2h = 18km/h
Proðkość pod prąd to 36km / 3h = 12km/h
Zatem:
v + x = 18
v - x = 12
Odejmujemy stronami drugie równanie od pierwszego i otrzymujemy
v+x - v + x = 18 - 12
2x = 6
x = 3
Odp. Prędkość prądu rzeki to 3 km/h
Najlepsza Odpowiedź!
2009-12-30T21:06:08+01:00
Vs1 - prędkość statku z prądem = s/t1 = 36/2 = 18 km/h
s - droga = 36 km
t1 - czas = 2 h
Vs2 - prędkość statku pod prąd = s/t2 = 36/3 = 12 km/h
t2 = 3 h
Vr - prędkość rzeki
Vs1 - Vr = Vs2 + Vr
18 - Vr = 12 + Vr
18 - 12 = Vr + Vr
6 = 2Vr
Vr = 6/2 = 3 km/h | __label__pos | 0.649157 |
strcspn(3C)
NAME
string, strcasecmp, strncasecmp, strcat, strncat, strlcat,
strchr, strrchr, strcmp, strncmp, strcpy, strncpy, strlcpy,
strcspn, strspn, strdup, strlen, strpbrk, strstr, strtok,
strtok_r - string operations
SYNOPSIS
#include <strings.h>
int strcasecmp(const char *s1, const char *s2);
int strncasecmp(const char *s1, const char *s2, size_t n);
#include <string.h>
char *strcat(char *s1, const char *s2);
char *strncat(char *s1, const char *s2, size_t n);
size_t strlcat(char *dst, const char *src, size_t dstsize);
char *strchr(const char *s, int c);
char *strrchr(const char *s, int c);
int strcmp(const char *s1, const char *s2);
int strncmp(const char *s1, const char *s2, size_t n);
char *strcpy(char *s1, const char *s2);
char *strncpy(char *s1, const char *s2, size_t n);
size_t strlcpy(char *dst, const char *src, size_t dstsize);
size_t strcspn(const char *s1, const char *s2);
size_t strspn(const char *s1, const char *s2);
char *strdup(const char *s1);
size_t strlen(const char *s);
char *strpbrk(const char *s1, const char *s2);
char *strstr(const char *s1, const char *s2);
char *strtok(char *s1, const char *s2);
char *strtok_r(char *s1, const char *s2, char **lasts);
ISO C++
#include <string.h>
const char *strchr(const char *s, int c);
const char *strpbrk(const char *s1, const char *s2);
const char *strrchr(const char *s, int c);
const char *strstr(const char *s1, const char *s2);
#include <cstring>
char *std::strchr(char *s, int c);
char *std::strpbrk(char *s1, const char *s2);
char *std::strrchr(char *s, int c);
char *std::strstr(char *s1, const char *s2);
DESCRIPTION
The arguments s, s1, and s2 point to strings (arrays of
characters terminated by a null character). The strcat(),
strncat(), strlcat(), strcpy(), strncpy(), strlcpy(),
strtok(), and strtok_r() functions all alter their first
argument. These functions do not check for overflow of the
array pointed to by the first argument.
strcasecmp(), strncasecmp()
The strcasecmp() and strncasecmp() functions are case-
insensitive versions of strcmp() and strncmp() respec-
tively, described below. They assume the ASCII character
set and ignore differences in case when comparing lower and
upper case characters.
strcat(), strncat(), strlcat()
The strcat() function appends a copy of string s2, including
the terminating null character, to the end of string s1. The
strncat() function appends at most n characters. Each
returns a pointer to the null-terminated result. The initial
character of s2 overrides the null character at the end of
s1.
The strlcat() function appends at most (dstsize-
strlen(dst)-1) characters of src to dst (dstsize being the
size of the string buffer dst). If the string pointed to by
dst contains a null-terminated string that fits into dstsize
bytes when strlcat() is called, the string pointed to by dst
will be a null-terminated string that fits in dstsize bytes
(including the terminating null character) when it com-
pletes, and the initial character of src will override the
null character at the end of dst. If the string pointed to
by dst is longer than dstsize bytes when strlcat() is
called, the string pointed to by dst will not be changed.
The function returns the sum the of lengths of the two
strings strlen(dst)+strlen(src). Buffer overflow can be
checked as follows:
if (strlcat(dst, src, dstsize) >= dstsize)
return -1;
strchr(), strrchr()
The strchr() function returns a pointer to the first
occurrence of c (converted to a char) in string s, or a
null pointer if c does not occur in the string. The
strrchr() function returns a pointer to the last occurrence
of c. The null character terminating a string is considered
to be part of the string.
strcmp(), strncmp()
The strcmp() function compares two strings byte-by-byte,
according to the ordering of your machine's character set.
The function returns an integer greater than, equal to, or
less than 0, if the string pointed to by s1 is greater
than, equal to, or less than the string pointed to by s2
respectively. The sign of a non-zero return value is deter-
mined by the sign of the difference between the values of
the first pair of bytes that differ in the strings being
compared. The strncmp() function makes the same comparison
but looks at a maximum of n bytes. Bytes following a null
byte are not compared.
strcpy(), strncpy(), strlcpy()
The strcpy() function copies string s2 to s1, including the
terminating null character, stopping after the null charac-
ter has been copied. The strncpy() function copies exactly n
bytes, truncating s2 or adding null characters to s1 if
necessary. The result will not be null-terminated if the
length of s2 is n or more. Each function returns s1.
The strlcpy() function copies at most dstsize-1 characters
(dstsize being the size of the string buffer dst) from src
to dst, truncating src if necessary. The result is always
null-terminated. The function returns strlen(src). Buffer
overflow can be checked as follows:
if (strlcpy(dst, src, dstsize) >= dstsize)
return -1;
strcspn(), strspn()
The strcspn() function returns the length of the initial
segment of string s1 that consists entirely of characters
not from string s2. The strspn() function returns the length
of the initial segment of string s1 that consists entirely
of characters from string s2.
strdup()
The strdup() function returns a pointer to a new string that
is a duplicate of the string pointed to by s1. The returned
pointer can be passed to free(). The space for the new
string is obtained using malloc(3C). If the new string can-
not be created, a null pointer is returned and errno may be
set to ENOMEM to indicate that the storage space available
is insufficient.
strlen()
The strlen() function returns the number of bytes in s, not
including the terminating null character.
strpbrk()
The strpbrk() function returns a pointer to the first
occurrence in string s1 of any character from string s2, or
a null pointer if no character from s2 exists in s1.
strstr()
The strstr() function locates the first occurrence of the
string s2 (excluding the terminating null character) in
string s1 and returns a pointer to the located string, or a
null pointer if the string is not found. If s2 points to a
string with zero length (that is, the string ""), the func-
tion returns s1.
strtok()
The strtok() function can be used to break the string
pointed to by s1 into a sequence of tokens, each of which is
delimited by one or more characters from the string pointed
to by s2. The strtok() function considers the string s1 to
consist of a sequence of zero or more text tokens separated
by spans of one or more characters from the separator string
s2. The first call (with pointer s1 specified) returns a
pointer to the first character of the first token, and will
have written a null character into s1 immediately following
the returned token. The function keeps track of its position
in the string between separate calls, so that subsequent
calls (which must be made with the first argument being a
null pointer) will work through the string s1 immediately
following that token. In this way subsequent calls will work
through the string s1 until no tokens remain. The separator
string s2 may be different from call to call. When no token
remains in s1, a null pointer is returned.
strtok_r()
The strtok_r() function has the same functionality as
strtok() except that a pointer to a string placeholder lasts
must be supplied by the caller. The lasts pointer is to
keep track of the next substring in which to search for the
next token.
ATTRIBUTES
See attributes(5) for descriptions of the following attri-
butes:
____________________________________________________________
| ATTRIBUTE TYPE | ATTRIBUTE VALUE |
|_____________________________|_____________________________|
| MT-Level | See NOTES below. |
|_____________________________|_____________________________|
SEE ALSO
malloc(3C), setlocale(3C), strxfrm(3C), attributes(5)
NOTES
When compiling multithreaded applications, the _REENTRANT
flag must be defined on the compile line. This flag should
only be used in multithreaded applications.
All of these functions assume the default locale ``C.'' For
some locales, strxfrm() should be applied to the strings
before they are passed to the functions.
The strcasecmp(), strcat(), strchr(), strcmp(), strcpy(),
strcspn(), strdup(), strlen(), strncasecmp(), strncat(),
strncmp(), strncpy(), strpbrk(), strrchr(), strspn(), and
strstr() functions are MT-Safe in multithreaded applica-
tions.
The strtok() function is Unsafe in multithreaded applica-
tions. The strtok_r() function should be used instead.
Man(1) output converted with man2html | __label__pos | 0.873589 |
State the dual of the following statement by applying the principle of duality. (p ∧ ~q) ∨ (~ p ∧ q) ≡ (p ∨ q) ∧ ~(p ∧ q) - Mathematics and Statistics
Advertisement
Advertisement
One Line Answer
State the dual of the following statement by applying the principle of duality.
(p ∧ ~q) ∨ (~ p ∧ q) ≡ (p ∨ q) ∧ ~(p ∧ q)
Advertisement
Solution
(p ∨ ~q) ∧ (~ p ∨ q) ≡ (p ∧ q) ∨ ~(p ∨ q)
Is there an error in this question or solution?
Chapter 1: Mathematical Logic - Miscellaneous Exercise 1 [Page 33]
APPEARS IN
Balbharati Mathematics and Statistics 1 (Commerce) 12th Standard HSC Maharashtra State Board
Chapter 1 Mathematical Logic
Miscellaneous Exercise 1 | Q 4.16 | Page 33
Share
Notifications
Forgot password?
Use app× | __label__pos | 0.834322 |
Menu links with dynamic values
Menu link defined statically in a *.links.menu.yml file can be altered with the hook menu links discovered alter hook, but if you want to provide a dynamic value you have to use something else.
Let's see first how to alter a statically defined menu link.
You can use hook_menu_links_discovered_alter() hook to hide or alter some property of a menu link. For example, you can hide the Home menu item in the Main navigation like this:
/**
* Implements hook_menu_links_discovered_alter().
*/
function MY_MODULE_menu_links_discovered_alter(&$links) {
unset($links['standard.front_page']);
}
By the way, the Home menu item is defined in the Standard profile here:
standard.links.menu.yml
To alter the title you can do something like this:
/**
* Implements hook_menu_links_discovered_alter().
*/
function MY_MODULE_menu_links_discovered_alter(&$links) {
$links['standard.front_page']['title'] = t('Altered Title');
}
As you can see hook menu links discovered alter hook is very useful, but it's not the right place to implement dynamic behavior. For that, you have to use the Menu link plugin class.
Let's say that you want to show or hide a menu item depending on the current user role. You can do it this way:
MY_MODULE.links.menu.yml
my_module.user:
title: 'User'
description: 'Dynamic menu item.'
route_name: 'my_module.user'
parent: 'system.admin'
class: Drupal\my_module\Plugin\Menu\UserMenuLink
src/Plugin/Menu/UserMenuLink.php
<?php
namespace Drupal\MY_MODULE\Plugin\Menu;
use Drupal\Core\Menu\MenuLinkDefault;
class UserMenuLink extends MenuLinkDefault {
/**
* {@inheritdoc}
*/
public function isEnabled() {
$roles = \Drupal::currentUser()->getRoles();
if (!in_array('administrator', $roles)) {
return FALSE;
}
return TRUE;
}
}
Or if you want to provide dynamic menu title you can do it this way:
<?php
namespace Drupal\MY_MODULE\Plugin\Menu;
use Drupal\Core\Menu\MenuLinkDefault;
class UserMenuLink extends MenuLinkDefault {
/**
* {@inheritdoc}
*/
public function getTitle() {
$roles = \Drupal::currentUser()->getRoles();
$roles = implode(', ', $roles);
return \Drupal::currentUser()->getDisplayName() . ' - ' . $roles;
}
}
And to conclude this blog post just a reminder that you should use Dependency Injection to inject the current user if you need it. I used the global Drupal class to make my code shorter. | __label__pos | 0.958402 |
Tag-Archive for » 2010 ap calc answers «
Calc Answers
calc answers
Does anyone know how to turn decimal answers into fraction on TI-85 graphing calculators?
When you get a decimal answer on this calculator how do i change it into a fraction not a mixed fraction but just a regular fraction. I don’t have the direction to the calc. scince it was given to me. Thanks.
Type the decimal in on the main screen. For example “.8″ Then hit the MATH button (under the green button on the upper left). Hit “1″ and then click “ENTER” The calculator should now read “4/5″.
Hope this helps you!
“Calc” by the Calculadiez | __label__pos | 0.773882 |
Why is the route correct but still giving 404 error on Django
I got a 404 error on my website when accessing the correct route, did I do something wrong urls.py handles the main route from django.contrib import admin from django.urls import path,include,re_path urlpatterns = [ path(‘admin/’, admin.site.urls), re_path(r’api/facebook/(.+?)’, include(‘apifacebooks.urls’)), path(”, include(‘app.urls’)), path(‘getcookie’, include(‘app.urls’)), path(‘change-lang’, include(‘app.urls’)), re_path(r’auth/(.+?)’, include(‘app.urls’)), ] urls.py handles routes in the apifacebooks app from… Read More Why is the route correct but still giving 404 error on Django | __label__pos | 0.991768 |
Removing the empty space around image using blur technique in CSS
Many a times, when we want to display multiple images of various aspect ratios and pixel sizes in a gallery.
In that case, there will be a single height and width of the card for the container, however the images will be of multiple sizes.
This can result in whitespace around the container as follows:
One of the ways to solve it is to add the blur around the image.
This is how it can be done using the ::after and ::before CSS techniques.
This is the end result
Here is code snippet for same:
<style>
.card-crop:before, .card-crop::after {
content: " ";
background-image: inherit;
background-position: center !important;
background-repeat: no-repeat !important;
height: inherit;
width: inherit;
}
.card-crop::before {
background-size: cover !important;
opacity: 0.6;
filter: blur(8px);
}
.card-crop::after {
background-size: contain !important;
background-origin: content-box;
padding: 5px;
}
.inline-block, .inline-block:before, .inline-block:after {
display: inline-block;
height: 225px;
left: 0;
right: 0;
top: 0;
bottom: 0;
}
.card-crop {
background-color: #ffffff;
border-bottom: 1px solid #efefef;
border-bottom: 1px solid #efefef;
background-position: -1px -1px;
background-size: 1px;
}
.inline-block:after {
position: absolute;
}
</style>
<div class="card-crop inline-block" style="background-image: url('/images/Blog/car.jpg'); height: 225px; width: 300px; display: flex; flex-direction: column; position:relative">
</div>
| __label__pos | 0.986235 |
Roboguru
Panjang rusuk kubus ABCD.EFGH adalah a. Jarak A ke diagonal BH adalah .....
Pertanyaan
Panjang rusuk kubus ABCD.EFGH adalah a. Jarak A ke diagonal BH adalah .....
1. a over 2 square root of 6
2. a over 4 square root of 6
3. a over 3 square root of 6
4. a over 5 square root of 6
5. a over 6 square root of 6
Pembahasan Soal:
D i a g o n a l space R u a n g space equals space B H space equals D i a g o n a l times space s i s i space equals space A H space equals a square root of 2 L triangle A B H equals fraction numerator B H cross times A O over denominator 2 end fraction equals fraction numerator A B cross times A H over denominator 2 end fraction fraction numerator a square root of 3 cross times A O over denominator 2 end fraction equals fraction numerator a cross times a square root of 2 over denominator 2 end fraction a square root of 3 cross times A O equals a cross times a square root of 2 A O equals fraction numerator a squared square root of 2 over denominator a square root of 3 end fraction cross times fraction numerator square root of 3 over denominator square root of 3 end fraction A O equals a over 3 square root of 6
Pembahasan terverifikasi oleh Roboguru
Dijawab oleh:
K. Putri
Mahasiswa/Alumni Universitas Pendidikan Ganesha
Terakhir diupdate 19 Desember 2020
Roboguru sudah bisa jawab 91.4% pertanyaan dengan benar
Tapi Roboguru masih mau belajar. Menurut kamu pembahasan kali ini sudah membantu, belum?
Membantu
Kurang Membantu
Apakah pembahasan ini membantu?
Belum menemukan yang kamu cari?
Post pertanyaanmu ke Tanya Jawab, yuk
Mau Bertanya
Pertanyaan yang serupa
Diketahui kubus ABCD.EFGH yang mempunyai panjang rusuk 9cm. Titik P berada di tengah-tengah EH. Tentukan jarak : c. titik B ke garis EG.
2
Roboguru
Diketahui kubus KLMN.OPQR dengan rusuk 12 cm. Jika T titik tengah ruas garis PR, jarak dari titik O ke garis KT adalah ....
0
Roboguru
Diketahui kubus ABCD.EFGH dengan panjang rusuk 8 cm. Jarak titik H dan garis AC adalah ... cm
1
Roboguru
Diketahui kubus yang mempunyai panjang rusuk 1 cm. jarak bidang ke bidang = .......
0
Roboguru
Diketahui kubus ABCD.EFGH dengan panjang rusuk 8 cm. Jarak titik H ke garis AC adalah ...
2
Roboguru
Roboguru sudah bisa jawab 91.4% pertanyaan dengan benar
Tapi Roboguru masih mau belajar. Menurut kamu pembahasan kali ini sudah membantu, belum?
Membantu
Kurang Membantu
Apakah pembahasan ini membantu?
Belum menemukan yang kamu cari?
Post pertanyaanmu ke Tanya Jawab, yuk
Mau Bertanya
RUANGGURU HQ
Jl. Dr. Saharjo No.161, Manggarai Selatan, Tebet, Kota Jakarta Selatan, Daerah Khusus Ibukota Jakarta 12860
Coba GRATIS Aplikasi Ruangguru
Produk Ruangguru
Produk Lainnya
Hubungi Kami
Ikuti Kami
©2021 Ruangguru. All Rights Reserved | __label__pos | 0.996392 |
Beyond keyboard shortcuts
In the age of touch devices, some days it seems like a day will come when we will not have to use a keyboard to interact with computers. A significant part of our relationship with technology passes through interfaces that were not common a decade ago: touch screens, accelerometers, cameras and microphones.
Keyboards, however, are still the most efficient way to interact with a computer, and not only for typing email. From code editors like Emacs to advanced image manipulation tools like Photoshop, it is no wonder that most advanced programs can be controlled more efficiently by means of keyboard shortcuts.
The learning curve for shortcuts is generally quite steep: while some of them are standard across programs and can be easily guessed, most shortcuts are complex abstract key combinations (as ⌘-Control-Shift-3 on Mac, that takes a screenshot to the clipboard) and therefore not easy to remember.
Some applications, however, are introducing smarter ways to control our computers using a keyboard.
Alfred: Mac at your fingertips
Mac OS has a long tradition of exposing keyboard shortcuts that allow power users to perform common tasks more efficiently. Introducing Spotlight was one more step towards keyboard driven interaction, as it allows to access applications, files and many other items by typing in a text box. Alfred, takes this approach to a new level: just like with Spotlight, pressing a combination of keys brings up a text box where you can enter anything from file names to simple commands (like empty trash, shutdown, and many more).
Alfred in action
The advantage over the built-in solution is that those commands allow you to control many functionalities that traditionally would have required you to click through several items and menus. Alfred will even adjust its behavior depending on the way you use it: it will present you first the options you select the most.
Sublime Text: controlling a text editor through text commands
When working with a text editor, typing on a keyboard is – by definition – the main means of interaction and so these programs traditionally rely on keyboard shortcuts more than any other. The over 2000 keyboard shortcuts available in Emacs are the most significant evidence of the level of complexity shortcuts can reach: it is impossible to master all the key sequences, only the most common ones.
Sublime Text, one of the best editors available today, takes an innovative approach to keyboard interaction: instead of requiring users to memorize arbitrary key sequences, it offers a mode called Command Palette, that allows users to type the name of any command to launch it.
Sublime Text's command palette
Compared to having to learn or remember keyboard shortcuts, this approach saves users also the need to sift through the application menus to find the feature they are looking for. As a side effect, it is also a much more effective way to discover application features than reading a manual.
Ubuntu: using HUD to get past menus
If the previous mode of interaction is still an exception on Windows and Mac, Ubuntu took some bold steps towards that: they designed a new system called HUD (as in Head-Up Display).
It immediately offers users the same benefit as Sublime Text’s command palette: faster interaction with menus items and easier discovery of features. In addition to that, however, it shares with Alfred its adaptive behavior and will learn by user behavior.
While HUD is ultimately designed with voice control in mind, keyboard commands are still extremely efficient and already effective today.
You can see it in action in the following video.
Embedding features like these in the operating system (or, more precisely, in the desktop shell) means that we will be able to control any application in a faster and more efficient way, regardless of whether its developers planned for that feature in advance or not.
Conclusion: why should I care?
Decades ago, keyboard shortcuts were born as a means to offer power users a more efficient way to perform their tasks. Nowadays, with fast access to command search (one or two keys) and smart algorithms to search through commands, anyone can become a power user in less time.
Not all applications will benefit dramatically from command search, but this pattern will become more and more common when web sites/applications start offering it: look at Google Docs menu search and GitHub’s command bar.
Avatar
Alessandro Bahgat
Software Engineer & Manager
I am an engineer and manager of engineers, I sometimes play with side projects and write about my experiences in my spare time.
Liked this?
You can sign up here to be notified of new content. Low frequency, no spam.
Next
Previous
comments powered by Disqus | __label__pos | 0.600205 |
Testing for Linear Separability with Linear Programming in R
April 19, 2014
By
(This article was first published on joy of data » R, and kindly contributed to R-bloggers)
lin-sep-points-2d-10For the previous article I needed a quick way to figure out if two sets of points are linearly separable. But for crying out loud I could not find a simple and efficient implementation for this task. Except for the perceptron and SVM – both are sub-optimal when you just want to test for linear separability. The perceptron is guaranteed to finish off with a happy ending – if feasible – but it can take quite a while. And SVMs are designed for soft-margin classification which means that they might settle for a not separating plane and also they maximize the margin around the separating plane – which is wasted computational effort.
The efficient way to get the job done is by applying linear programming (LP). That means representing the question “Is it possible to fit a hyper-plane between two sets of points?” with a number of inequalities (that make up a convex area). I’m going to give a quick walk through for the math to make the idea plausible – but this text is more describing an introductory example and not an introduction to LP itself. For solving the linear program I will use Rglpk which provides a high level interface to the GNU Linear Programming Kit (GLPK) – and of course has been co-crafted by the man himself – Kurt Hornik – who is also involved with kernlab and party – thank you, Prof. Hornik and keep up the good work!
The Gory Details
Let’s say we have two sets A and B of points in \mathbb{R}^M:
A = \{a_1, ..., a_{N_1}\} \subset \mathbb{R}^M, B = \{b_1, ..., b_{N_2}\} \subset \mathbb{R}^M
And we want to know if there is a hyper-plane in \mathbb{R}^M which separates A and B then we can formulate the necessary condition with two symmetrical inequalities:
A \beta \in \mathbb{R} and an h \in \mathbb{R}^M exist, such that we can say for all a \in A: h^Ta > \beta (1) and for all b \in B: h^Tb < \beta (2).
This is because a hyper-plane in \mathbb{R}^M can be defined as a vector
(h,\beta) \in \mathbb{R}^{M} \times \mathbb{R} and the points on either side of it can be distinguished with above stated inequalities.
N <- 100
g <- expand.grid(x=0:N/N,y=0:N/N)
# definition of the hyper plane
h1 <- 3
h2 <- -4
beta <- -1.3
# points on either side
g$col <- ifelse(h1 * g$x + h2 * g$y > beta,
"cornflowerblue","darkolivegreen3")
# roughly on the hyper plane
g$col <- ifelse(abs(h1 * g$x + h2 * g$y - beta) < 2/N, "red", g$col)
plot(g$x, g$y, col=g$col, pch=16, cex=.5, xlab="x", ylab="y",
main="h(x,y) = 3 * x + (-4) * y + 1.3 = 0")
lin-sep-2dThe conditions of a linear program are usually stated as a number of “weakly smaller than” inequalities. So lets transform (1) and (2) appropriately:
The conditions h^Ta > \beta and h^Tb < \beta can be written as h^Ta \geq \beta + 1 and h^Tb \leq \beta - 1. This is because we are dealing with finite sets A and B, so if we have a separating plane, then we can always fit in an \epsilon such that h^Ta \geq \beta + \epsilon and h^Tb \leq \beta - \epsilon. If we now multiply both inequalities with 1/\epsilon, then we just end up with a different formulation (h / \epsilon, \beta / \epsilon) for the same plane (h, \beta). The first inequality we additionally multiply with -1 to turn \geq into \leq – and we and now we have:
(3) -h^Ta \leq -\beta - 1
(4) h^Tb \leq \beta - 1
Okay great – we’re almost there – now let’s get all the variables on the left hand side:
(5) -h^Ta + \beta \leq -1
(6) h^Tb - \beta \leq -1
These hyper-plane conditions have to be true for all points. All points in A have to fulfil (5) and all points in B have to fulfil (6). Then this set of N_1 + N_2 inequalities describes the convex set in \mathbb{R}^{M+1} of all possible separating hyper planes (h,\beta). Usually the description and purpose of a linear program does not stop at this point and the set of feasible solutions is used to maximize an objective function. In our case such an objective function might be introduced to maximize the distance of the plane from the points. But the article is long enough already and our objective is to just find a plane and not the the best plane. Which is why our objective function is going to be simply the 0 \in \mathbb{R}^{M+1}
So now we formulate (5) and (6) in matrix notation because this is how LP solvers expect the program description to be fed to them – we get:
A\cdot\tilde{h} \leq b with N := N_1 + N_2
A = \begin{pmatrix} -a_1^T & 1 \\ ... & ... \\ -a_{N_1}^T & 1 \\ b_1^T & -1 \\ ... & ... \\ b_{N_2}^T & -1 \end{pmatrix} \in \mathbb{R}^{N\times(M+1)}, \tilde{h} = \begin{pmatrix} h_1 \\ ... \\ h_M \\ \beta \end{pmatrix} \in \mathbb{R}^{M+1}, b = \begin{pmatrix} -1 \\ ... \\ -1 \\ -1 \\ ... \\ -1 \end{pmatrix} \in \mathbb{R}^{N}
Example with Rglpk in two dimensions
lin-sep-points-2d
lin-sep-points-2d-5
lin-sep-points-2d-10
library(Rglpk)
N1 <- 3
N2 <- 3
# the points of sets A and B
P <- matrix(
runif(2*N1 + 2*N2,0,1),
ncol=2,byrow=T
)
# the matrix A defining the lhs of the conditions
A <- cbind(P * c(rep(-1,N1),rep(1,N2)), c(rep(1,N1),rep(-1,N2)))
# the objective function - no optimization necessary
obj <- c(0,0,0)
# the vector b defining the rhs of the conditions
b <- rep(-1, N1+N2)
# by default GLPK assums positive boundaries for the
# variables. but we need the full set of real numbers.
bounds <- list(
lower = list(ind = c(1,2,3), val = c(-Inf,-Inf,-Inf)),
upper = list(ind = c(1,2,3), val = c(Inf,Inf,Inf))
)
# solving the linear program
s <- Rglpk_solve_LP(obj, A, rep("<=", N1+N2), b, bounds=bounds)
plot(P,col=c(rep("red",N1),rep("blue",N2)), xlab="x", ylab="y",
cex=1, pch=16, xlim=c(0,1), ylim=c(0,1))
# status 0 means that a solution was found
if(s$status == 0) {
h1 = s$solution[1]
h2 = s$solution[2]
beta = s$solution[3]
# drawing the separating line
if(h2 != 0) {
abline(beta/h2,-h1/h2)
} else {
abline(v=-beta/h1)
}
} else {
cat("Not linearly separable.")
}
In case you are wondering how I managed to include all those pretty pretty math formulas in this post – I am using the QuickLaTeX WordPress plug-in and I must say I really like the result. In previous posts I used a LaTeX web editor and then included the rendered formulas as an image.
The post Testing for Linear Separability with Linear Programming in R appeared first on joy of data.
To leave a comment for the author, please follow the link and comment on their blog: joy of data » R.
R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...
If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...
Comments are closed.
Sponsors
Mango solutions
plotly webpage
dominolab webpage
Zero Inflated Models and Generalized Linear Mixed Models with R
Quantide: statistical consulting and training
datasociety
http://www.eoda.de
ODSC
ODSC
CRC R books series
Six Sigma Online Training
Contact us if you wish to help support R-bloggers, and place your banner here.
Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)
Click here to close (This popup will not appear again) | __label__pos | 0.902301 |
/**************************************************************************** ** ** Copyright (C) 2016 The Qt Company Ltd. ** Copyright (C) 2016 Intel Corporation. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the QtCore module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 3 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL3 included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 3 requirements ** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 2.0 or (at your option) the GNU General ** Public license version 3 or any later version approved by the KDE Free ** Qt Foundation. The licenses are as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-2.0.html and ** https://www.gnu.org/licenses/gpl-3.0.html. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qcoreapplication.h" #include "qcoreapplication_p.h" #ifndef QT_NO_QOBJECT #include "qabstracteventdispatcher.h" #include "qcoreevent.h" #include "qeventloop.h" #endif #include "qcorecmdlineargs_p.h" #include #include #include #include #include #include #include #include #include #ifndef QT_NO_QOBJECT #include #include #include #include #endif #include #include #include #include #include #include #include #ifndef QT_NO_QOBJECT #if defined(Q_OS_UNIX) # if defined(Q_OS_OSX) # include "qeventdispatcher_cf_p.h" # else # if !defined(QT_NO_GLIB) # include "qeventdispatcher_glib_p.h" # endif # endif # include "qeventdispatcher_unix_p.h" #endif #ifdef Q_OS_WIN # ifdef Q_OS_WINRT # include "qeventdispatcher_winrt_p.h" # include "qfunctions_winrt.h" # include # include using namespace ABI::Windows::ApplicationModel::Core; using namespace Microsoft::WRL; # else # include "qeventdispatcher_win_p.h" # endif #endif #endif // QT_NO_QOBJECT #ifdef Q_OS_MAC # include "qcore_mac_p.h" #endif #include #ifdef Q_OS_UNIX # include # include # include #endif #ifdef Q_OS_VXWORKS # include #endif #include QT_BEGIN_NAMESPACE #ifndef QT_NO_QOBJECT class QMutexUnlocker { public: inline explicit QMutexUnlocker(QMutex *m) : mtx(m) { } inline ~QMutexUnlocker() { unlock(); } inline void unlock() { if (mtx) mtx->unlock(); mtx = 0; } private: Q_DISABLE_COPY(QMutexUnlocker) QMutex *mtx; }; #endif #if defined(Q_OS_WIN) || defined(Q_OS_MAC) extern QString qAppFileName(); #endif #if QT_VERSION >= 0x060000 # error "Bump QCoreApplicatoinPrivate::app_compile_version to 0x060000" #endif int QCoreApplicationPrivate::app_compile_version = 0x050000; //we don't know exactly, but it's at least 5.0.0 bool QCoreApplicationPrivate::setuidAllowed = false; #if !defined(Q_OS_WIN) #ifdef Q_OS_MAC QString QCoreApplicationPrivate::macMenuBarName() { QString bundleName; CFTypeRef string = CFBundleGetValueForInfoDictionaryKey(CFBundleGetMainBundle(), CFSTR("CFBundleName")); if (string) bundleName = QCFString::toQString(static_cast(string)); return bundleName; } #endif QString QCoreApplicationPrivate::appName() const { QString applicationName; #ifdef Q_OS_MAC applicationName = macMenuBarName(); #endif if (applicationName.isEmpty() && argv[0]) { char *p = strrchr(argv[0], '/'); applicationName = QString::fromLocal8Bit(p ? p + 1 : argv[0]); } return applicationName; } #endif QString *QCoreApplicationPrivate::cachedApplicationFilePath = 0; bool QCoreApplicationPrivate::checkInstance(const char *function) { bool b = (QCoreApplication::self != 0); if (!b) qWarning("QApplication::%s: Please instantiate the QApplication object first", function); return b; } void QCoreApplicationPrivate::processCommandLineArguments() { int j = argc ? 1 : 0; for (int i = 1; i < argc; ++i) { if (!argv[i]) continue; if (*argv[i] != '-') { argv[j++] = argv[i]; continue; } const char *arg = argv[i]; if (arg[1] == '-') // startsWith("--") ++arg; if (strncmp(arg, "-qmljsdebugger=", 15) == 0) { qmljs_debug_arguments = QString::fromLocal8Bit(arg + 15); } else if (strcmp(arg, "-qmljsdebugger") == 0 && i < argc - 1) { ++i; qmljs_debug_arguments = QString::fromLocal8Bit(argv[i]); } else { argv[j++] = argv[i]; } } if (j < argc) { argv[j] = 0; argc = j; } } // Support for introspection #ifndef QT_NO_QOBJECT QSignalSpyCallbackSet Q_CORE_EXPORT qt_signal_spy_callback_set = { 0, 0, 0, 0 }; void qt_register_signal_spy_callbacks(const QSignalSpyCallbackSet &callback_set) { qt_signal_spy_callback_set = callback_set; } #endif extern "C" void Q_CORE_EXPORT qt_startup_hook() { } typedef QList QStartUpFuncList; Q_GLOBAL_STATIC(QStartUpFuncList, preRList) typedef QList QVFuncList; Q_GLOBAL_STATIC(QVFuncList, postRList) #ifndef QT_NO_QOBJECT static QBasicMutex globalPreRoutinesMutex; #endif /*! \internal Adds a global routine that will be called from the QCoreApplication constructor. The public API is Q_COREAPP_STARTUP_FUNCTION. */ void qAddPreRoutine(QtStartUpFunction p) { QStartUpFuncList *list = preRList(); if (!list) return; // Due to C++11 parallel dynamic initialization, this can be called // from multiple threads. #ifndef QT_NO_THREAD QMutexLocker locker(&globalPreRoutinesMutex); #endif if (QCoreApplication::instance()) p(); list->prepend(p); // in case QCoreApplication is re-created, see qt_call_pre_routines } void qAddPostRoutine(QtCleanUpFunction p) { QVFuncList *list = postRList(); if (!list) return; list->prepend(p); } void qRemovePostRoutine(QtCleanUpFunction p) { QVFuncList *list = postRList(); if (!list) return; list->removeAll(p); } static void qt_call_pre_routines() { QStartUpFuncList *list = preRList(); if (!list) return; #ifndef QT_NO_THREAD QMutexLocker locker(&globalPreRoutinesMutex); #endif // Unlike qt_call_post_routines, we don't empty the list, because // Q_COREAPP_STARTUP_FUNCTION is a macro, so the user expects // the function to be executed every time QCoreApplication is created. for (int i = 0; i < list->count(); ++i) list->at(i)(); } void Q_CORE_EXPORT qt_call_post_routines() { QVFuncList *list = 0; QT_TRY { list = postRList(); } QT_CATCH(const std::bad_alloc &) { // ignore - if we can't allocate a post routine list, // there's a high probability that there's no post // routine to be executed :) } if (!list) return; while (!list->isEmpty()) (list->takeFirst())(); } // initialized in qcoreapplication and in qtextstream autotest when setlocale is called. static bool qt_locale_initialized = false; #ifndef QT_NO_QOBJECT // app starting up if false bool QCoreApplicationPrivate::is_app_running = false; // app closing down if true bool QCoreApplicationPrivate::is_app_closing = false; Q_CORE_EXPORT uint qGlobalPostedEventsCount() { QThreadData *currentThreadData = QThreadData::current(); return currentThreadData->postEventList.size() - currentThreadData->postEventList.startOffset; } QAbstractEventDispatcher *QCoreApplicationPrivate::eventDispatcher = 0; #ifdef Q_OS_UNIX Qt::HANDLE qt_application_thread_id = 0; #endif #endif // QT_NO_QOBJECT QCoreApplication *QCoreApplication::self = 0; uint QCoreApplicationPrivate::attribs = (1 << Qt::AA_SynthesizeMouseForUnhandledTouchEvents); struct QCoreApplicationData { QCoreApplicationData() Q_DECL_NOTHROW { applicationNameSet = false; } ~QCoreApplicationData() { #ifndef QT_NO_QOBJECT // cleanup the QAdoptedThread created for the main() thread if (QCoreApplicationPrivate::theMainThread) { QThreadData *data = QThreadData::get2(QCoreApplicationPrivate::theMainThread); data->deref(); // deletes the data and the adopted thread } #endif } QString orgName, orgDomain; QString application; // application name, initially from argv[0], can then be modified. QString applicationVersion; bool applicationNameSet; // true if setApplicationName was called #ifndef QT_NO_LIBRARY QScopedPointer app_libpaths; QScopedPointer manual_libpaths; #endif }; Q_GLOBAL_STATIC(QCoreApplicationData, coreappdata) #ifndef QT_NO_QOBJECT static bool quitLockRefEnabled = true; #endif #if defined(Q_OS_WIN) && !defined(Q_OS_WINRT) // Check whether the command line arguments match those passed to main() // by comparing to the global __argv/__argc (MS extension). // Deep comparison is required since argv/argc is rebuilt by WinMain for // GUI apps or when using MinGW due to its globbing. static inline bool isArgvModified(int argc, char **argv) { if (__argc != argc || !__argv /* wmain() */) return true; if (__argv == argv) return false; for (int a = 0; a < argc; ++a) { if (argv[a] != __argv[a] && strcmp(argv[a], __argv[a])) return true; } return false; } static inline bool contains(int argc, char **argv, const char *needle) { for (int a = 0; a < argc; ++a) { if (!strcmp(argv[a], needle)) return true; } return false; } #endif // Q_OS_WIN && !Q_OS_WINRT QCoreApplicationPrivate::QCoreApplicationPrivate(int &aargc, char **aargv, uint flags) : #ifndef QT_NO_QOBJECT QObjectPrivate(), #endif argc(aargc) , argv(aargv) #if defined(Q_OS_WIN) && !defined(Q_OS_WINRT) , origArgc(0) , origArgv(Q_NULLPTR) #endif , application_type(QCoreApplicationPrivate::Tty) #ifndef QT_NO_QOBJECT , in_exec(false) , aboutToQuitEmitted(false) , threadData_clean(false) #else , q_ptr(0) #endif { app_compile_version = flags & 0xffffff; static const char *const empty = ""; if (argc == 0 || argv == 0) { argc = 0; argv = const_cast(&empty); } #if defined(Q_OS_WIN) && !defined(Q_OS_WINRT) if (!isArgvModified(argc, argv)) { origArgc = argc; origArgv = new char *[argc]; std::copy(argv, argv + argc, origArgv); } #endif // Q_OS_WIN && !Q_OS_WINRT #ifndef QT_NO_QOBJECT QCoreApplicationPrivate::is_app_closing = false; # if defined(Q_OS_UNIX) if (Q_UNLIKELY(!setuidAllowed && (geteuid() != getuid()))) qFatal("FATAL: The application binary appears to be running setuid, this is a security hole."); # endif // Q_OS_UNIX # if defined(Q_OS_UNIX) qt_application_thread_id = QThread::currentThreadId(); # endif QThread *cur = QThread::currentThread(); // note: this may end up setting theMainThread! if (cur != theMainThread) qWarning("WARNING: QApplication was not created in the main() thread."); #endif } QCoreApplicationPrivate::~QCoreApplicationPrivate() { #ifndef QT_NO_QOBJECT cleanupThreadData(); #endif #if defined(Q_OS_WIN) && !defined(Q_OS_WINRT) delete [] origArgv; #endif QCoreApplicationPrivate::clearApplicationFilePath(); } #ifndef QT_NO_QOBJECT void QCoreApplicationPrivate::cleanupThreadData() { if (threadData && !threadData_clean) { #ifndef QT_NO_THREAD void *data = &threadData->tls; QThreadStorageData::finish((void **)data); #endif // need to clear the state of the mainData, just in case a new QCoreApplication comes along. QMutexLocker locker(&threadData->postEventList.mutex); for (int i = 0; i < threadData->postEventList.size(); ++i) { const QPostEvent &pe = threadData->postEventList.at(i); if (pe.event) { --pe.receiver->d_func()->postedEvents; pe.event->posted = false; delete pe.event; } } threadData->postEventList.clear(); threadData->postEventList.recursion = 0; threadData->quitNow = false; threadData_clean = true; } } void QCoreApplicationPrivate::createEventDispatcher() { Q_Q(QCoreApplication); #if defined(Q_OS_UNIX) # if defined(Q_OS_OSX) bool ok = false; int value = qEnvironmentVariableIntValue("QT_EVENT_DISPATCHER_CORE_FOUNDATION", &ok); if (ok && value > 0) eventDispatcher = new QEventDispatcherCoreFoundation(q); else eventDispatcher = new QEventDispatcherUNIX(q); # elif !defined(QT_NO_GLIB) if (qEnvironmentVariableIsEmpty("QT_NO_GLIB") && QEventDispatcherGlib::versionSupported()) eventDispatcher = new QEventDispatcherGlib(q); else eventDispatcher = new QEventDispatcherUNIX(q); # else eventDispatcher = new QEventDispatcherUNIX(q); # endif #elif defined(Q_OS_WINRT) eventDispatcher = new QEventDispatcherWinRT(q); #elif defined(Q_OS_WIN) eventDispatcher = new QEventDispatcherWin32(q); #else # error "QEventDispatcher not yet ported to this platform" #endif } void QCoreApplicationPrivate::eventDispatcherReady() { } QBasicAtomicPointer QCoreApplicationPrivate::theMainThread = Q_BASIC_ATOMIC_INITIALIZER(0); QThread *QCoreApplicationPrivate::mainThread() { Q_ASSERT(theMainThread.load() != 0); return theMainThread.load(); } bool QCoreApplicationPrivate::threadRequiresCoreApplication() { QThreadData *data = QThreadData::current(false); if (!data) return true; // default setting return data->requiresCoreApplication; } void QCoreApplicationPrivate::checkReceiverThread(QObject *receiver) { QThread *currentThread = QThread::currentThread(); QThread *thr = receiver->thread(); Q_ASSERT_X(currentThread == thr || !thr, "QCoreApplication::sendEvent", QString::fromLatin1("Cannot send events to objects owned by a different thread. " "Current thread %1. Receiver '%2' (of type '%3') was created in thread %4") .arg(QString::number((quintptr) currentThread, 16)) .arg(receiver->objectName()) .arg(QLatin1String(receiver->metaObject()->className())) .arg(QString::number((quintptr) thr, 16)) .toLocal8Bit().data()); Q_UNUSED(currentThread); Q_UNUSED(thr); } #endif // QT_NO_QOBJECT void QCoreApplicationPrivate::appendApplicationPathToLibraryPaths() { #ifndef QT_NO_LIBRARY QStringList *app_libpaths = coreappdata()->app_libpaths.data(); if (!app_libpaths) coreappdata()->app_libpaths.reset(app_libpaths = new QStringList); QString app_location = QCoreApplication::applicationFilePath(); app_location.truncate(app_location.lastIndexOf(QLatin1Char('/'))); #ifdef Q_OS_WINRT if (app_location.isEmpty()) app_location.append(QLatin1Char('/')); #endif app_location = QDir(app_location).canonicalPath(); if (QFile::exists(app_location) && !app_libpaths->contains(app_location)) app_libpaths->append(app_location); #endif } QString qAppName() { if (!QCoreApplicationPrivate::checkInstance("qAppName")) return QString(); return QCoreApplication::instance()->d_func()->appName(); } void QCoreApplicationPrivate::initLocale() { if (qt_locale_initialized) return; qt_locale_initialized = true; #if defined(Q_OS_UNIX) && !defined(QT_BOOTSTRAPPED) setlocale(LC_ALL, ""); #endif } /*! \class QCoreApplication \inmodule QtCore \brief The QCoreApplication class provides an event loop for Qt applications without UI. This class is used by non-GUI applications to provide their event loop. For non-GUI application that uses Qt, there should be exactly one QCoreApplication object. For GUI applications, see QGuiApplication. For applications that use the Qt Widgets module, see QApplication. QCoreApplication contains the main event loop, where all events from the operating system (e.g., timer and network events) and other sources are processed and dispatched. It also handles the application's initialization and finalization, as well as system-wide and application-wide settings. \section1 The Event Loop and Event Handling The event loop is started with a call to exec(). Long-running operations can call processEvents() to keep the application responsive. In general, we recommend that you create a QCoreApplication, QGuiApplication or a QApplication object in your \c main() function as early as possible. exec() will not return until the event loop exits; e.g., when quit() is called. Several static convenience functions are also provided. The QCoreApplication object is available from instance(). Events can be sent or posted using sendEvent(), postEvent(), and sendPostedEvents(). Pending events can be removed with removePostedEvents() or flushed with flush(). The class provides a quit() slot and an aboutToQuit() signal. \section1 Application and Library Paths An application has an applicationDirPath() and an applicationFilePath(). Library paths (see QLibrary) can be retrieved with libraryPaths() and manipulated by setLibraryPaths(), addLibraryPath(), and removeLibraryPath(). \section1 Internationalization and Translations Translation files can be added or removed using installTranslator() and removeTranslator(). Application strings can be translated using translate(). The QObject::tr() and QObject::trUtf8() functions are implemented in terms of translate(). \section1 Accessing Command Line Arguments The command line arguments which are passed to QCoreApplication's constructor should be accessed using the arguments() function. \note QCoreApplication removes option \c -qmljsdebugger="...". It parses the argument of \c qmljsdebugger, and then removes this option plus its argument. For more advanced command line option handling, create a QCommandLineParser. \section1 Locale Settings On Unix/Linux Qt is configured to use the system locale settings by default. This can cause a conflict when using POSIX functions, for instance, when converting between data types such as floats and strings, since the notation may differ between locales. To get around this problem, call the POSIX function \c{setlocale(LC_NUMERIC,"C")} right after initializing QApplication, QGuiApplication or QCoreApplication to reset the locale that is used for number formatting to "C"-locale. \sa QGuiApplication, QAbstractEventDispatcher, QEventLoop, {Semaphores Example}, {Wait Conditions Example} */ /*! \fn static QCoreApplication *QCoreApplication::instance() Returns a pointer to the application's QCoreApplication (or QGuiApplication/QApplication) instance. If no instance has been allocated, \c null is returned. */ /*! \internal */ QCoreApplication::QCoreApplication(QCoreApplicationPrivate &p) #ifdef QT_NO_QOBJECT : d_ptr(&p) #else : QObject(p, 0) #endif { d_func()->q_ptr = this; // note: it is the subclasses' job to call // QCoreApplicationPrivate::eventDispatcher->startingUp(); } #ifndef QT_NO_QOBJECT /*! Flushes the platform-specific event queues. If you are doing graphical changes inside a loop that does not return to the event loop on asynchronous window systems like X11 or double buffered window systems like Quartz (OS X and iOS), and you want to visualize these changes immediately (e.g. Splash Screens), call this function. \sa sendPostedEvents() */ void QCoreApplication::flush() { if (self && self->d_func()->eventDispatcher) self->d_func()->eventDispatcher->flush(); } #endif /*! Constructs a Qt core application. Core applications are applications without a graphical user interface. Such applications are used at the console or as server processes. The \a argc and \a argv arguments are processed by the application, and made available in a more convenient form by the arguments() function. \warning The data referred to by \a argc and \a argv must stay valid for the entire lifetime of the QCoreApplication object. In addition, \a argc must be greater than zero and \a argv must contain at least one valid character string. */ QCoreApplication::QCoreApplication(int &argc, char **argv #ifndef Q_QDOC , int _internal #endif ) #ifdef QT_NO_QOBJECT : d_ptr(new QCoreApplicationPrivate(argc, argv, _internal)) #else : QObject(*new QCoreApplicationPrivate(argc, argv, _internal)) #endif { d_func()->q_ptr = this; d_func()->init(); #ifndef QT_NO_QOBJECT QCoreApplicationPrivate::eventDispatcher->startingUp(); #endif } void QCoreApplicationPrivate::init() { Q_Q(QCoreApplication); initLocale(); Q_ASSERT_X(!QCoreApplication::self, "QCoreApplication", "there should be only one application object"); QCoreApplication::self = q; // Store app name (so it's still available after QCoreApplication is destroyed) if (!coreappdata()->applicationNameSet) coreappdata()->application = appName(); QLoggingRegistry::instance()->init(); #ifndef QT_NO_LIBRARY // Reset the lib paths, so that they will be recomputed, taking the availability of argv[0] // into account. If necessary, recompute right away and replay the manual changes on top of the // new lib paths. QStringList *appPaths = coreappdata()->app_libpaths.take(); QStringList *manualPaths = coreappdata()->manual_libpaths.take(); if (appPaths) { if (manualPaths) { // Replay the delta. As paths can only be prepended to the front or removed from // anywhere in the list, we can just linearly scan the lists and find the items that // have been removed. Once the original list is exhausted we know all the remaining // items have been added. QStringList newPaths(q->libraryPaths()); for (int i = manualPaths->length(), j = appPaths->length(); i > 0 || j > 0; qt_noop()) { if (--j < 0) { newPaths.prepend((*manualPaths)[--i]); } else if (--i < 0) { newPaths.removeAll((*appPaths)[j]); } else if ((*manualPaths)[i] != (*appPaths)[j]) { newPaths.removeAll((*appPaths)[j]); ++i; // try again with next item. } } delete manualPaths; coreappdata()->manual_libpaths.reset(new QStringList(newPaths)); } delete appPaths; } #endif #ifndef QT_NO_QOBJECT // use the event dispatcher created by the app programmer (if any) if (!eventDispatcher) eventDispatcher = threadData->eventDispatcher.load(); // otherwise we create one if (!eventDispatcher) createEventDispatcher(); Q_ASSERT(eventDispatcher); if (!eventDispatcher->parent()) { eventDispatcher->moveToThread(threadData->thread); eventDispatcher->setParent(q); } threadData->eventDispatcher = eventDispatcher; eventDispatcherReady(); #endif #ifdef QT_EVAL extern void qt_core_eval_init(QCoreApplicationPrivate::Type); qt_core_eval_init(application_type); #endif processCommandLineArguments(); qt_call_pre_routines(); qt_startup_hook(); #ifndef QT_BOOTSTRAPPED if (Q_UNLIKELY(qtHookData[QHooks::Startup])) reinterpret_cast(qtHookData[QHooks::Startup])(); #endif #ifndef QT_NO_QOBJECT is_app_running = true; // No longer starting up. #endif } /*! Destroys the QCoreApplication object. */ QCoreApplication::~QCoreApplication() { qt_call_post_routines(); self = 0; #ifndef QT_NO_QOBJECT QCoreApplicationPrivate::is_app_closing = true; QCoreApplicationPrivate::is_app_running = false; #endif #if !defined(QT_NO_THREAD) // Synchronize and stop the global thread pool threads. QThreadPool *globalThreadPool = 0; QT_TRY { globalThreadPool = QThreadPool::globalInstance(); } QT_CATCH (...) { // swallow the exception, since destructors shouldn't throw } if (globalThreadPool) globalThreadPool->waitForDone(); #endif #ifndef QT_NO_QOBJECT d_func()->threadData->eventDispatcher = 0; if (QCoreApplicationPrivate::eventDispatcher) QCoreApplicationPrivate::eventDispatcher->closingDown(); QCoreApplicationPrivate::eventDispatcher = 0; #endif #ifndef QT_NO_LIBRARY coreappdata()->app_libpaths.reset(); coreappdata()->manual_libpaths.reset(); #endif } /*! \since 5.3 Allows the application to run setuid on UNIX platforms if \a allow is true. If \a allow is false (the default) and Qt detects the application is running with an effective user id different than the real user id, the application will be aborted when a QCoreApplication instance is created. Qt is not an appropriate solution for setuid programs due to its large attack surface. However some applications may be required to run in this manner for historical reasons. This flag will prevent Qt from aborting the application when this is detected, and must be set before a QCoreApplication instance is created. \note It is strongly recommended not to enable this option since it introduces security risks. */ void QCoreApplication::setSetuidAllowed(bool allow) { QCoreApplicationPrivate::setuidAllowed = allow; } /*! \since 5.3 Returns true if the application is allowed to run setuid on UNIX platforms. \sa QCoreApplication::setSetuidAllowed() */ bool QCoreApplication::isSetuidAllowed() { return QCoreApplicationPrivate::setuidAllowed; } /*! Sets the attribute \a attribute if \a on is true; otherwise clears the attribute. \sa testAttribute() */ void QCoreApplication::setAttribute(Qt::ApplicationAttribute attribute, bool on) { if (on) QCoreApplicationPrivate::attribs |= 1 << attribute; else QCoreApplicationPrivate::attribs &= ~(1 << attribute); } /*! Returns \c true if attribute \a attribute is set; otherwise returns \c false. \sa setAttribute() */ bool QCoreApplication::testAttribute(Qt::ApplicationAttribute attribute) { return QCoreApplicationPrivate::testAttribute(attribute); } #ifndef QT_NO_QOBJECT /*! \property QCoreApplication::quitLockEnabled \brief Whether the use of the QEventLoopLocker feature can cause the application to quit. The default is \c true. \sa QEventLoopLocker */ bool QCoreApplication::isQuitLockEnabled() { return quitLockRefEnabled; } static bool doNotify(QObject *, QEvent *); void QCoreApplication::setQuitLockEnabled(bool enabled) { quitLockRefEnabled = enabled; } /*! \internal \deprecated This function is here to make it possible for Qt extensions to hook into event notification without subclassing QApplication */ bool QCoreApplication::notifyInternal(QObject *receiver, QEvent *event) { return notifyInternal2(receiver, event); } /*! \internal \since 5.6 This function is here to make it possible for Qt extensions to hook into event notification without subclassing QApplication. */ bool QCoreApplication::notifyInternal2(QObject *receiver, QEvent *event) { bool selfRequired = QCoreApplicationPrivate::threadRequiresCoreApplication(); if (!self && selfRequired) return false; // Make it possible for Qt Script to hook into events even // though QApplication is subclassed... bool result = false; void *cbdata[] = { receiver, event, &result }; if (QInternal::activateCallbacks(QInternal::EventNotifyCallback, cbdata)) { return result; } // Qt enforces the rule that events can only be sent to objects in // the current thread, so receiver->d_func()->threadData is // equivalent to QThreadData::current(), just without the function // call overhead. QObjectPrivate *d = receiver->d_func(); QThreadData *threadData = d->threadData; QScopedScopeLevelCounter scopeLevelCounter(threadData); if (!selfRequired) return doNotify(receiver, event); return self->notify(receiver, event); } /*! Sends \a event to \a receiver: \a {receiver}->event(\a event). Returns the value that is returned from the receiver's event handler. Note that this function is called for all events sent to any object in any thread. For certain types of events (e.g. mouse and key events), the event will be propagated to the receiver's parent and so on up to the top-level object if the receiver is not interested in the event (i.e., it returns \c false). There are five different ways that events can be processed; reimplementing this virtual function is just one of them. All five approaches are listed below: \list 1 \li Reimplementing \l {QWidget::}{paintEvent()}, \l {QWidget::}{mousePressEvent()} and so on. This is the commonest, easiest, and least powerful way. \li Reimplementing this function. This is very powerful, providing complete control; but only one subclass can be active at a time. \li Installing an event filter on QCoreApplication::instance(). Such an event filter is able to process all events for all widgets, so it's just as powerful as reimplementing notify(); furthermore, it's possible to have more than one application-global event filter. Global event filters even see mouse events for \l{QWidget::isEnabled()}{disabled widgets}. Note that application event filters are only called for objects that live in the main thread. \li Reimplementing QObject::event() (as QWidget does). If you do this you get Tab key presses, and you get to see the events before any widget-specific event filters. \li Installing an event filter on the object. Such an event filter gets all the events, including Tab and Shift+Tab key press events, as long as they do not change the focus widget. \endlist \b{Future direction:} This function will not be called for objects that live outside the main thread in Qt 6. Applications that need that functionality should find other solutions for their event inspection needs in the meantime. The change may be extended to the main thread, causing this function to be deprecated. \warning If you override this function, you must ensure all threads that process events stop doing so before your application object begins destruction. This includes threads started by other libraries that you may be using, but does not apply to Qt's own threads. \sa QObject::event(), installNativeEventFilter() */ bool QCoreApplication::notify(QObject *receiver, QEvent *event) { // no events are delivered after ~QCoreApplication() has started if (QCoreApplicationPrivate::is_app_closing) return true; return doNotify(receiver, event); } static bool doNotify(QObject *receiver, QEvent *event) { if (receiver == 0) { // serious error qWarning("QCoreApplication::notify: Unexpected null receiver"); return true; } #ifndef QT_NO_DEBUG QCoreApplicationPrivate::checkReceiverThread(receiver); #endif return receiver->isWidgetType() ? false : QCoreApplicationPrivate::notify_helper(receiver, event); } bool QCoreApplicationPrivate::sendThroughApplicationEventFilters(QObject *receiver, QEvent *event) { // We can't access the application event filters outside of the main thread (race conditions) Q_ASSERT(receiver->d_func()->threadData->thread == mainThread()); if (extraData) { // application event filters are only called for objects in the GUI thread for (int i = 0; i < extraData->eventFilters.size(); ++i) { QObject *obj = extraData->eventFilters.at(i); if (!obj) continue; if (obj->d_func()->threadData != threadData) { qWarning("QCoreApplication: Application event filter cannot be in a different thread."); continue; } if (obj->eventFilter(receiver, event)) return true; } } return false; } bool QCoreApplicationPrivate::sendThroughObjectEventFilters(QObject *receiver, QEvent *event) { if (receiver != QCoreApplication::instance() && receiver->d_func()->extraData) { for (int i = 0; i < receiver->d_func()->extraData->eventFilters.size(); ++i) { QObject *obj = receiver->d_func()->extraData->eventFilters.at(i); if (!obj) continue; if (obj->d_func()->threadData != receiver->d_func()->threadData) { qWarning("QCoreApplication: Object event filter cannot be in a different thread."); continue; } if (obj->eventFilter(receiver, event)) return true; } } return false; } /*! \internal Helper function called by QCoreApplicationPrivate::notify() and qapplication.cpp */ bool QCoreApplicationPrivate::notify_helper(QObject *receiver, QEvent * event) { // send to all application event filters (only does anything in the main thread) if (QCoreApplication::self && receiver->d_func()->threadData->thread == mainThread() && QCoreApplication::self->d_func()->sendThroughApplicationEventFilters(receiver, event)) return true; // send to all receiver event filters if (sendThroughObjectEventFilters(receiver, event)) return true; // deliver the event return receiver->event(event); } /*! Returns \c true if an application object has not been created yet; otherwise returns \c false. \sa closingDown() */ bool QCoreApplication::startingUp() { return !QCoreApplicationPrivate::is_app_running; } /*! Returns \c true if the application objects are being destroyed; otherwise returns \c false. \sa startingUp() */ bool QCoreApplication::closingDown() { return QCoreApplicationPrivate::is_app_closing; } /*! Processes all pending events for the calling thread according to the specified \a flags until there are no more events to process. You can call this function occasionally when your program is busy performing a long operation (e.g. copying a file). In the event that you are running a local loop which calls this function continuously, without an event loop, the \l{QEvent::DeferredDelete}{DeferredDelete} events will not be processed. This can affect the behaviour of widgets, e.g. QToolTip, that rely on \l{QEvent::DeferredDelete}{DeferredDelete} events to function properly. An alternative would be to call \l{QCoreApplication::sendPostedEvents()}{sendPostedEvents()} from within that local loop. Calling this function processes events only for the calling thread. \threadsafe \sa exec(), QTimer, QEventLoop::processEvents(), flush(), sendPostedEvents() */ void QCoreApplication::processEvents(QEventLoop::ProcessEventsFlags flags) { QThreadData *data = QThreadData::current(); if (!data->hasEventDispatcher()) return; data->eventDispatcher.load()->processEvents(flags); } /*! \overload processEvents() Processes pending events for the calling thread for \a maxtime milliseconds or until there are no more events to process, whichever is shorter. You can call this function occasionally when your program is busy doing a long operation (e.g. copying a file). Calling this function processes events only for the calling thread. \threadsafe \sa exec(), QTimer, QEventLoop::processEvents() */ void QCoreApplication::processEvents(QEventLoop::ProcessEventsFlags flags, int maxtime) { // ### Qt 6: consider splitting this method into a public and a private // one, so that a user-invoked processEvents can be detected // and handled properly. QThreadData *data = QThreadData::current(); if (!data->hasEventDispatcher()) return; QElapsedTimer start; start.start(); while (data->eventDispatcher.load()->processEvents(flags & ~QEventLoop::WaitForMoreEvents)) { if (start.elapsed() > maxtime) break; } } /***************************************************************************** Main event loop wrappers *****************************************************************************/ /*! Enters the main event loop and waits until exit() is called. Returns the value that was passed to exit() (which is 0 if exit() is called via quit()). It is necessary to call this function to start event handling. The main event loop receives events from the window system and dispatches these to the application widgets. To make your application perform idle processing (by executing a special function whenever there are no pending events), use a QTimer with 0 timeout. More advanced idle processing schemes can be achieved using processEvents(). We recommend that you connect clean-up code to the \l{QCoreApplication::}{aboutToQuit()} signal, instead of putting it in your application's \c{main()} function because on some platforms the exec() call may not return. For example, on Windows when the user logs off, the system terminates the process after Qt closes all top-level windows. Hence, there is no guarantee that the application will have time to exit its event loop and execute code at the end of the \c{main()} function after the exec() call. \sa quit(), exit(), processEvents(), QApplication::exec() */ int QCoreApplication::exec() { if (!QCoreApplicationPrivate::checkInstance("exec")) return -1; QThreadData *threadData = self->d_func()->threadData; if (threadData != QThreadData::current()) { qWarning("%s::exec: Must be called from the main thread", self->metaObject()->className()); return -1; } if (!threadData->eventLoops.isEmpty()) { qWarning("QCoreApplication::exec: The event loop is already running"); return -1; } threadData->quitNow = false; QEventLoop eventLoop; self->d_func()->in_exec = true; self->d_func()->aboutToQuitEmitted = false; int returnCode = eventLoop.exec(); threadData->quitNow = false; if (self) { self->d_func()->in_exec = false; if (!self->d_func()->aboutToQuitEmitted) emit self->aboutToQuit(QPrivateSignal()); self->d_func()->aboutToQuitEmitted = true; sendPostedEvents(0, QEvent::DeferredDelete); } return returnCode; } /*! Tells the application to exit with a return code. After this function has been called, the application leaves the main event loop and returns from the call to exec(). The exec() function returns \a returnCode. If the event loop is not running, this function does nothing. By convention, a \a returnCode of 0 means success, and any non-zero value indicates an error. Note that unlike the C library function of the same name, this function \e does return to the caller -- it is event processing that stops. \sa quit(), exec() */ void QCoreApplication::exit(int returnCode) { if (!self) return; QThreadData *data = self->d_func()->threadData; data->quitNow = true; for (int i = 0; i < data->eventLoops.size(); ++i) { QEventLoop *eventLoop = data->eventLoops.at(i); eventLoop->exit(returnCode); } #ifdef Q_OS_WINRT qWarning("QCoreApplication::exit: It is not recommended to explicitly exit an application on Windows Store Apps"); ComPtr app; HRESULT hr = RoGetActivationFactory(Wrappers::HString::MakeReference(RuntimeClass_Windows_ApplicationModel_Core_CoreApplication).Get(), IID_PPV_ARGS(&app)); RETURN_VOID_IF_FAILED("Could not acquire ICoreApplication object"); ComPtr appExit; hr = app.As(&appExit); RETURN_VOID_IF_FAILED("Could not acquire ICoreApplicationExit object"); hr = appExit->Exit(); RETURN_VOID_IF_FAILED("Could not exit application"); #endif // Q_OS_WINRT } /***************************************************************************** QCoreApplication management of posted events *****************************************************************************/ /*! \fn bool QCoreApplication::sendEvent(QObject *receiver, QEvent *event) Sends event \a event directly to receiver \a receiver, using the notify() function. Returns the value that was returned from the event handler. The event is \e not deleted when the event has been sent. The normal approach is to create the event on the stack, for example: \snippet code/src_corelib_kernel_qcoreapplication.cpp 0 \sa postEvent(), notify() */ /*! \since 4.3 Adds the event \a event, with the object \a receiver as the receiver of the event, to an event queue and returns immediately. The event must be allocated on the heap since the post event queue will take ownership of the event and delete it once it has been posted. It is \e {not safe} to access the event after it has been posted. When control returns to the main event loop, all events that are stored in the queue will be sent using the notify() function. Events are sorted in descending \a priority order, i.e. events with a high \a priority are queued before events with a lower \a priority. The \a priority can be any integer value, i.e. between INT_MAX and INT_MIN, inclusive; see Qt::EventPriority for more details. Events with equal \a priority will be processed in the order posted. \threadsafe \sa sendEvent(), notify(), sendPostedEvents(), Qt::EventPriority */ void QCoreApplication::postEvent(QObject *receiver, QEvent *event, int priority) { if (receiver == 0) { qWarning("QCoreApplication::postEvent: Unexpected null receiver"); delete event; return; } QThreadData * volatile * pdata = &receiver->d_func()->threadData; QThreadData *data = *pdata; if (!data) { // posting during destruction? just delete the event to prevent a leak delete event; return; } // lock the post event mutex data->postEventList.mutex.lock(); // if object has moved to another thread, follow it while (data != *pdata) { data->postEventList.mutex.unlock(); data = *pdata; if (!data) { // posting during destruction? just delete the event to prevent a leak delete event; return; } data->postEventList.mutex.lock(); } QMutexUnlocker locker(&data->postEventList.mutex); // if this is one of the compressible events, do compression if (receiver->d_func()->postedEvents && self && self->compressEvent(event, receiver, &data->postEventList)) { return; } if (event->type() == QEvent::DeferredDelete && data == QThreadData::current()) { // remember the current running eventloop for DeferredDelete // events posted in the receiver's thread. // Events sent by non-Qt event handlers (such as glib) may not // have the scopeLevel set correctly. The scope level makes sure that // code like this: // foo->deleteLater(); // qApp->processEvents(); // without passing QEvent::DeferredDelete // will not cause "foo" to be deleted before returning to the event loop. // If the scope level is 0 while loopLevel != 0, we are called from a // non-conformant code path, and our best guess is that the scope level // should be 1. (Loop level 0 is special: it means that no event loops // are running.) int loopLevel = data->loopLevel; int scopeLevel = data->scopeLevel; if (scopeLevel == 0 && loopLevel != 0) scopeLevel = 1; static_cast(event)->level = loopLevel + scopeLevel; } // delete the event on exceptions to protect against memory leaks till the event is // properly owned in the postEventList QScopedPointer eventDeleter(event); data->postEventList.addEvent(QPostEvent(receiver, event, priority)); eventDeleter.take(); event->posted = true; ++receiver->d_func()->postedEvents; data->canWait = false; locker.unlock(); QAbstractEventDispatcher* dispatcher = data->eventDispatcher.loadAcquire(); if (dispatcher) dispatcher->wakeUp(); } /*! \internal Returns \c true if \a event was compressed away (possibly deleted) and should not be added to the list. */ bool QCoreApplication::compressEvent(QEvent *event, QObject *receiver, QPostEventList *postedEvents) { #ifdef Q_OS_WIN Q_ASSERT(event); Q_ASSERT(receiver); Q_ASSERT(postedEvents); // compress posted timers to this object. if (event->type() == QEvent::Timer && receiver->d_func()->postedEvents > 0) { int timerId = ((QTimerEvent *) event)->timerId(); for (int i=0; isize(); ++i) { const QPostEvent &e = postedEvents->at(i); if (e.receiver == receiver && e.event && e.event->type() == QEvent::Timer && ((QTimerEvent *) e.event)->timerId() == timerId) { delete event; return true; } } } else #endif if ((event->type() == QEvent::DeferredDelete || event->type() == QEvent::Quit) && receiver->d_func()->postedEvents > 0) { for (int i = 0; i < postedEvents->size(); ++i) { const QPostEvent &cur = postedEvents->at(i); if (cur.receiver != receiver || cur.event == 0 || cur.event->type() != event->type()) continue; // found an event for this receiver delete event; return true; } } return false; } /*! Immediately dispatches all events which have been previously queued with QCoreApplication::postEvent() and which are for the object \a receiver and have the event type \a event_type. Events from the window system are \e not dispatched by this function, but by processEvents(). If \a receiver is null, the events of \a event_type are sent for all objects. If \a event_type is 0, all the events are sent for \a receiver. \note This method must be called from the thread in which its QObject parameter, \a receiver, lives. \sa flush(), postEvent() */ void QCoreApplication::sendPostedEvents(QObject *receiver, int event_type) { // ### Qt 6: consider splitting this method into a public and a private // one, so that a user-invoked sendPostedEvents can be detected // and handled properly. QThreadData *data = QThreadData::current(); QCoreApplicationPrivate::sendPostedEvents(receiver, event_type, data); } void QCoreApplicationPrivate::sendPostedEvents(QObject *receiver, int event_type, QThreadData *data) { if (event_type == -1) { // we were called by an obsolete event dispatcher. event_type = 0; } if (receiver && receiver->d_func()->threadData != data) { qWarning("QCoreApplication::sendPostedEvents: Cannot send " "posted events for objects in another thread"); return; } ++data->postEventList.recursion; QMutexLocker locker(&data->postEventList.mutex); // by default, we assume that the event dispatcher can go to sleep after // processing all events. if any new events are posted while we send // events, canWait will be set to false. data->canWait = (data->postEventList.size() == 0); if (data->postEventList.size() == 0 || (receiver && !receiver->d_func()->postedEvents)) { --data->postEventList.recursion; return; } data->canWait = true; // okay. here is the tricky loop. be careful about optimizing // this, it looks the way it does for good reasons. int startOffset = data->postEventList.startOffset; int &i = (!event_type && !receiver) ? data->postEventList.startOffset : startOffset; data->postEventList.insertionOffset = data->postEventList.size(); // Exception-safe cleaning up without the need for a try/catch block struct CleanUp { QObject *receiver; int event_type; QThreadData *data; bool exceptionCaught; inline CleanUp(QObject *receiver, int event_type, QThreadData *data) : receiver(receiver), event_type(event_type), data(data), exceptionCaught(true) {} inline ~CleanUp() { if (exceptionCaught) { // since we were interrupted, we need another pass to make sure we clean everything up data->canWait = false; } --data->postEventList.recursion; if (!data->postEventList.recursion && !data->canWait && data->hasEventDispatcher()) data->eventDispatcher.load()->wakeUp(); // clear the global list, i.e. remove everything that was // delivered. if (!event_type && !receiver && data->postEventList.startOffset >= 0) { const QPostEventList::iterator it = data->postEventList.begin(); data->postEventList.erase(it, it + data->postEventList.startOffset); data->postEventList.insertionOffset -= data->postEventList.startOffset; Q_ASSERT(data->postEventList.insertionOffset >= 0); data->postEventList.startOffset = 0; } } }; CleanUp cleanup(receiver, event_type, data); while (i < data->postEventList.size()) { // avoid live-lock if (i >= data->postEventList.insertionOffset) break; const QPostEvent &pe = data->postEventList.at(i); ++i; if (!pe.event) continue; if ((receiver && receiver != pe.receiver) || (event_type && event_type != pe.event->type())) { data->canWait = false; continue; } if (pe.event->type() == QEvent::DeferredDelete) { // DeferredDelete events are sent either // 1) when the event loop that posted the event has returned; or // 2) if explicitly requested (with QEvent::DeferredDelete) for // events posted by the current event loop; or // 3) if the event was posted before the outermost event loop. int eventLevel = static_cast(pe.event)->loopLevel(); int loopLevel = data->loopLevel + data->scopeLevel; const bool allowDeferredDelete = (eventLevel > loopLevel || (!eventLevel && loopLevel > 0) || (event_type == QEvent::DeferredDelete && eventLevel == loopLevel)); if (!allowDeferredDelete) { // cannot send deferred delete if (!event_type && !receiver) { // we must copy it first; we want to re-post the event // with the event pointer intact, but we can't delay // nulling the event ptr until after re-posting, as // addEvent may invalidate pe. QPostEvent pe_copy = pe; // null out the event so if sendPostedEvents recurses, it // will ignore this one, as it's been re-posted. const_cast(pe).event = 0; // re-post the copied event so it isn't lost data->postEventList.addEvent(pe_copy); } continue; } } // first, we diddle the event so that we can deliver // it, and that no one will try to touch it later. pe.event->posted = false; QEvent *e = pe.event; QObject * r = pe.receiver; --r->d_func()->postedEvents; Q_ASSERT(r->d_func()->postedEvents >= 0); // next, update the data structure so that we're ready // for the next event. const_cast(pe).event = 0; struct MutexUnlocker { QMutexLocker &m; MutexUnlocker(QMutexLocker &m) : m(m) { m.unlock(); } ~MutexUnlocker() { m.relock(); } }; MutexUnlocker unlocker(locker); QScopedPointer event_deleter(e); // will delete the event (with the mutex unlocked) // after all that work, it's time to deliver the event. QCoreApplication::sendEvent(r, e); // careful when adding anything below this point - the // sendEvent() call might invalidate any invariants this // function depends on. } cleanup.exceptionCaught = false; } /*! \since 4.3 Removes all events of the given \a eventType that were posted using postEvent() for \a receiver. The events are \e not dispatched, instead they are removed from the queue. You should never need to call this function. If you do call it, be aware that killing events may cause \a receiver to break one or more invariants. If \a receiver is null, the events of \a eventType are removed for all objects. If \a eventType is 0, all the events are removed for \a receiver. You should never call this function with \a eventType of 0. If you do call it in this way, be aware that killing events may cause \a receiver to break one or more invariants. \threadsafe */ void QCoreApplication::removePostedEvents(QObject *receiver, int eventType) { QThreadData *data = receiver ? receiver->d_func()->threadData : QThreadData::current(); QMutexLocker locker(&data->postEventList.mutex); // the QObject destructor calls this function directly. this can // happen while the event loop is in the middle of posting events, // and when we get here, we may not have any more posted events // for this object. if (receiver && !receiver->d_func()->postedEvents) return; //we will collect all the posted events for the QObject //and we'll delete after the mutex was unlocked QVarLengthArray events; int n = data->postEventList.size(); int j = 0; for (int i = 0; i < n; ++i) { const QPostEvent &pe = data->postEventList.at(i); if ((!receiver || pe.receiver == receiver) && (pe.event && (eventType == 0 || pe.event->type() == eventType))) { --pe.receiver->d_func()->postedEvents; pe.event->posted = false; events.append(pe.event); const_cast(pe).event = 0; } else if (!data->postEventList.recursion) { if (i != j) qSwap(data->postEventList[i], data->postEventList[j]); ++j; } } #ifdef QT_DEBUG if (receiver && eventType == 0) { Q_ASSERT(!receiver->d_func()->postedEvents); } #endif if (!data->postEventList.recursion) { // truncate list data->postEventList.erase(data->postEventList.begin() + j, data->postEventList.end()); } locker.unlock(); for (int i = 0; i < events.count(); ++i) { delete events[i]; } } /*! Removes \a event from the queue of posted events, and emits a warning message if appropriate. \warning This function can be \e really slow. Avoid using it, if possible. \threadsafe */ void QCoreApplicationPrivate::removePostedEvent(QEvent * event) { if (!event || !event->posted) return; QThreadData *data = QThreadData::current(); QMutexLocker locker(&data->postEventList.mutex); if (data->postEventList.size() == 0) { #if defined(QT_DEBUG) qDebug("QCoreApplication::removePostedEvent: Internal error: %p %d is posted", (void*)event, event->type()); return; #endif } for (int i = 0; i < data->postEventList.size(); ++i) { const QPostEvent & pe = data->postEventList.at(i); if (pe.event == event) { #ifndef QT_NO_DEBUG qWarning("QCoreApplication::removePostedEvent: Event of type %d deleted while posted to %s %s", event->type(), pe.receiver->metaObject()->className(), pe.receiver->objectName().toLocal8Bit().data()); #endif --pe.receiver->d_func()->postedEvents; pe.event->posted = false; delete pe.event; const_cast(pe).event = 0; return; } } } /*!\reimp */ bool QCoreApplication::event(QEvent *e) { if (e->type() == QEvent::Quit) { quit(); return true; } return QObject::event(e); } /*! \enum QCoreApplication::Encoding \obsolete This enum type used to define the 8-bit encoding of character string arguments to translate(). This enum is now obsolete and UTF-8 will be used in all cases. \value UnicodeUTF8 UTF-8. \omitvalue Latin1 \omitvalue DefaultCodec UTF-8. \omitvalue CodecForTr \sa QObject::tr(), QString::fromUtf8() */ void QCoreApplicationPrivate::ref() { quitLockRef.ref(); } void QCoreApplicationPrivate::deref() { if (!quitLockRef.deref()) maybeQuit(); } void QCoreApplicationPrivate::maybeQuit() { if (quitLockRef.load() == 0 && in_exec && quitLockRefEnabled && shouldQuit()) QCoreApplication::postEvent(QCoreApplication::instance(), new QEvent(QEvent::Quit)); } /*! Tells the application to exit with return code 0 (success). Equivalent to calling QCoreApplication::exit(0). It's common to connect the QGuiApplication::lastWindowClosed() signal to quit(), and you also often connect e.g. QAbstractButton::clicked() or signals in QAction, QMenu, or QMenuBar to it. Example: \snippet code/src_corelib_kernel_qcoreapplication.cpp 1 \sa exit(), aboutToQuit(), QGuiApplication::lastWindowClosed() */ void QCoreApplication::quit() { exit(0); } /*! \fn void QCoreApplication::aboutToQuit() This signal is emitted when the application is about to quit the main event loop, e.g. when the event loop level drops to zero. This may happen either after a call to quit() from inside the application or when the user shuts down the entire desktop session. The signal is particularly useful if your application has to do some last-second cleanup. Note that no user interaction is possible in this state. \sa quit() */ #endif // QT_NO_QOBJECT #ifndef QT_NO_TRANSLATION /*! Adds the translation file \a translationFile to the list of translation files to be used for translations. Multiple translation files can be installed. Translations are searched for in the reverse order in which they were installed, so the most recently installed translation file is searched first and the first translation file installed is searched last. The search stops as soon as a translation containing a matching string is found. Installing or removing a QTranslator, or changing an installed QTranslator generates a \l{QEvent::LanguageChange}{LanguageChange} event for the QCoreApplication instance. A QGuiApplication instance will propagate the event to all toplevel windows, where a reimplementation of changeEvent can re-translate the user interface by passing user-visible strings via the tr() function to the respective property setters. User-interface classes generated by Qt Designer provide a \c retranslateUi() function that can be called. The function returns \c true on success and false on failure. \sa removeTranslator(), translate(), QTranslator::load(), {Dynamic Translation} */ bool QCoreApplication::installTranslator(QTranslator *translationFile) { if (!translationFile) return false; if (!QCoreApplicationPrivate::checkInstance("installTranslator")) return false; QCoreApplicationPrivate *d = self->d_func(); d->translators.prepend(translationFile); #ifndef QT_NO_TRANSLATION_BUILDER if (translationFile->isEmpty()) return false; #endif #ifndef QT_NO_QOBJECT QEvent ev(QEvent::LanguageChange); QCoreApplication::sendEvent(self, &ev); #endif return true; } /*! Removes the translation file \a translationFile from the list of translation files used by this application. (It does not delete the translation file from the file system.) The function returns \c true on success and false on failure. \sa installTranslator(), translate(), QObject::tr() */ bool QCoreApplication::removeTranslator(QTranslator *translationFile) { if (!translationFile) return false; if (!QCoreApplicationPrivate::checkInstance("removeTranslator")) return false; QCoreApplicationPrivate *d = self->d_func(); if (d->translators.removeAll(translationFile)) { #ifndef QT_NO_QOBJECT if (!self->closingDown()) { QEvent ev(QEvent::LanguageChange); QCoreApplication::sendEvent(self, &ev); } #endif return true; } return false; } static void replacePercentN(QString *result, int n) { if (n >= 0) { int percentPos = 0; int len = 0; while ((percentPos = result->indexOf(QLatin1Char('%'), percentPos + len)) != -1) { len = 1; QString fmt; if (result->at(percentPos + len) == QLatin1Char('L')) { ++len; fmt = QLatin1String("%L1"); } else { fmt = QLatin1String("%1"); } if (result->at(percentPos + len) == QLatin1Char('n')) { fmt = fmt.arg(n); ++len; result->replace(percentPos, len, fmt); len = fmt.length(); } } } } /*! \reentrant Returns the translation text for \a sourceText, by querying the installed translation files. The translation files are searched from the most recently installed file back to the first installed file. QObject::tr() provides this functionality more conveniently. \a context is typically a class name (e.g., "MyDialog") and \a sourceText is either English text or a short identifying text. \a disambiguation is an identifying string, for when the same \a sourceText is used in different roles within the same context. By default, it is null. See the \l QTranslator and \l QObject::tr() documentation for more information about contexts, disambiguations and comments. \a n is used in conjunction with \c %n to support plural forms. See QObject::tr() for details. If none of the translation files contain a translation for \a sourceText in \a context, this function returns a QString equivalent of \a sourceText. This function is not virtual. You can use alternative translation techniques by subclassing \l QTranslator. \warning This method is reentrant only if all translators are installed \e before calling this method. Installing or removing translators while performing translations is not supported. Doing so will most likely result in crashes or other undesirable behavior. \sa QObject::tr(), installTranslator() */ QString QCoreApplication::translate(const char *context, const char *sourceText, const char *disambiguation, int n) { QString result; if (!sourceText) return result; if (self && !self->d_func()->translators.isEmpty()) { QList::ConstIterator it; QTranslator *translationFile; for (it = self->d_func()->translators.constBegin(); it != self->d_func()->translators.constEnd(); ++it) { translationFile = *it; result = translationFile->translate(context, sourceText, disambiguation, n); if (!result.isNull()) break; } } if (result.isNull()) result = QString::fromUtf8(sourceText); replacePercentN(&result, n); return result; } /*! \fn static QString QCoreApplication::translate(const char *context, const char *key, const char *disambiguation, Encoding encoding, int n = -1) \obsolete */ // Declared in qglobal.h QString qtTrId(const char *id, int n) { return QCoreApplication::translate(0, id, 0, n); } bool QCoreApplicationPrivate::isTranslatorInstalled(QTranslator *translator) { return QCoreApplication::self && QCoreApplication::self->d_func()->translators.contains(translator); } #else QString QCoreApplication::translate(const char *context, const char *sourceText, const char *disambiguation, int n) { Q_UNUSED(context) Q_UNUSED(disambiguation) QString ret = QString::fromUtf8(sourceText); if (n >= 0) ret.replace(QLatin1String("%n"), QString::number(n)); return ret; } #endif //QT_NO_TRANSLATE // Makes it possible to point QCoreApplication to a custom location to ensure // the directory is added to the patch, and qt.conf and deployed plugins are // found from there. This is for use cases in which QGuiApplication is // instantiated by a library and not by an application executable, for example, // Active X servers. void QCoreApplicationPrivate::setApplicationFilePath(const QString &path) { if (QCoreApplicationPrivate::cachedApplicationFilePath) *QCoreApplicationPrivate::cachedApplicationFilePath = path; else QCoreApplicationPrivate::cachedApplicationFilePath = new QString(path); } /*! Returns the directory that contains the application executable. For example, if you have installed Qt in the \c{C:\Qt} directory, and you run the \c{regexp} example, this function will return "C:/Qt/examples/tools/regexp". On OS X and iOS this will point to the directory actually containing the executable, which may be inside an application bundle (if the application is bundled). \warning On Linux, this function will try to get the path from the \c {/proc} file system. If that fails, it assumes that \c {argv[0]} contains the absolute file name of the executable. The function also assumes that the current directory has not been changed by the application. \sa applicationFilePath() */ QString QCoreApplication::applicationDirPath() { if (!self) { qWarning("QCoreApplication::applicationDirPath: Please instantiate the QApplication object first"); return QString(); } QCoreApplicationPrivate *d = self->d_func(); if (d->cachedApplicationDirPath.isNull()) d->cachedApplicationDirPath = QFileInfo(applicationFilePath()).path(); return d->cachedApplicationDirPath; } /*! Returns the file path of the application executable. For example, if you have installed Qt in the \c{/usr/local/qt} directory, and you run the \c{regexp} example, this function will return "/usr/local/qt/examples/tools/regexp/regexp". \warning On Linux, this function will try to get the path from the \c {/proc} file system. If that fails, it assumes that \c {argv[0]} contains the absolute file name of the executable. The function also assumes that the current directory has not been changed by the application. \sa applicationDirPath() */ QString QCoreApplication::applicationFilePath() { if (!self) { qWarning("QCoreApplication::applicationFilePath: Please instantiate the QApplication object first"); return QString(); } QCoreApplicationPrivate *d = self->d_func(); if (d->argc) { static const char *procName = d->argv[0]; if (qstrcmp(procName, d->argv[0]) != 0) { // clear the cache if the procname changes, so we reprocess it. QCoreApplicationPrivate::clearApplicationFilePath(); procName = d->argv[0]; } } if (QCoreApplicationPrivate::cachedApplicationFilePath) return *QCoreApplicationPrivate::cachedApplicationFilePath; #if defined(Q_OS_WIN) QCoreApplicationPrivate::setApplicationFilePath(QFileInfo(qAppFileName()).filePath()); return *QCoreApplicationPrivate::cachedApplicationFilePath; #elif defined(Q_OS_MAC) QString qAppFileName_str = qAppFileName(); if(!qAppFileName_str.isEmpty()) { QFileInfo fi(qAppFileName_str); if (fi.exists()) { QCoreApplicationPrivate::setApplicationFilePath(fi.canonicalFilePath()); return *QCoreApplicationPrivate::cachedApplicationFilePath; } return QString(); } #endif #if defined( Q_OS_UNIX ) # if defined(Q_OS_LINUX) && (!defined(Q_OS_ANDROID) || defined(Q_OS_ANDROID_NO_SDK)) // Try looking for a /proc//exe symlink first which points to // the absolute path of the executable QFileInfo pfi(QString::fromLatin1("/proc/%1/exe").arg(getpid())); if (pfi.exists() && pfi.isSymLink()) { QCoreApplicationPrivate::setApplicationFilePath(pfi.canonicalFilePath()); return *QCoreApplicationPrivate::cachedApplicationFilePath; } # endif if (!arguments().isEmpty()) { QString argv0 = QFile::decodeName(arguments().at(0).toLocal8Bit()); QString absPath; if (!argv0.isEmpty() && argv0.at(0) == QLatin1Char('/')) { /* If argv0 starts with a slash, it is already an absolute file path. */ absPath = argv0; } else if (argv0.contains(QLatin1Char('/'))) { /* If argv0 contains one or more slashes, it is a file path relative to the current directory. */ absPath = QDir::current().absoluteFilePath(argv0); } else { /* Otherwise, the file path has to be determined using the PATH environment variable. */ absPath = QStandardPaths::findExecutable(argv0); } absPath = QDir::cleanPath(absPath); QFileInfo fi(absPath); if (fi.exists()) { QCoreApplicationPrivate::setApplicationFilePath(fi.canonicalFilePath()); return *QCoreApplicationPrivate::cachedApplicationFilePath; } } return QString(); #endif Q_UNREACHABLE(); } /*! \since 4.4 Returns the current process ID for the application. */ qint64 QCoreApplication::applicationPid() { #if defined(Q_OS_WIN) return GetCurrentProcessId(); #elif defined(Q_OS_VXWORKS) return (pid_t) taskIdCurrent; #else return getpid(); #endif } /*! \since 4.1 Returns the list of command-line arguments. Usually arguments().at(0) is the program name, arguments().at(1) is the first argument, and arguments().last() is the last argument. See the note below about Windows. Calling this function is slow - you should store the result in a variable when parsing the command line. \warning On Unix, this list is built from the argc and argv parameters passed to the constructor in the main() function. The string-data in argv is interpreted using QString::fromLocal8Bit(); hence it is not possible to pass, for example, Japanese command line arguments on a system that runs in a Latin1 locale. Most modern Unix systems do not have this limitation, as they are Unicode-based. On Windows, the list is built from the argc and argv parameters only if modified argv/argc parameters are passed to the constructor. In that case, encoding problems might occur. Otherwise, the arguments() are constructed from the return value of \l{http://msdn2.microsoft.com/en-us/library/ms683156(VS.85).aspx}{GetCommandLine()}. As a result of this, the string given by arguments().at(0) might not be the program name on Windows, depending on how the application was started. \sa applicationFilePath(), QCommandLineParser */ QStringList QCoreApplication::arguments() { QStringList list; if (!self) { qWarning("QCoreApplication::arguments: Please instantiate the QApplication object first"); return list; } const int ac = self->d_func()->argc; char ** const av = self->d_func()->argv; list.reserve(ac); #if defined(Q_OS_WIN) && !defined(Q_OS_WINRT) // On Windows, it is possible to pass Unicode arguments on // the command line. To restore those, we split the command line // and filter out arguments that were deleted by derived application // classes by index. QString cmdline = QString::fromWCharArray(GetCommandLine()); #if defined(Q_OS_WINCE) wchar_t tempFilename[MAX_PATH+1]; if (GetModuleFileName(0, tempFilename, MAX_PATH)) { tempFilename[MAX_PATH] = 0; cmdline.prepend(QLatin1Char('\"') + QString::fromWCharArray(tempFilename) + QLatin1String("\" ")); } #endif // Q_OS_WINCE const QCoreApplicationPrivate *d = self->d_func(); if (d->origArgv) { const QStringList allArguments = qWinCmdArgs(cmdline); Q_ASSERT(allArguments.size() == d->origArgc); for (int i = 0; i < d->origArgc; ++i) { if (contains(ac, av, d->origArgv[i])) list.append(allArguments.at(i)); } return list; } // Fall back to rebuilding from argv/argc when a modified argv was passed. #endif // defined(Q_OS_WIN) && !defined(Q_OS_WINRT) for (int a = 0; a < ac; ++a) { list << QString::fromLocal8Bit(av[a]); } return list; } /*! \property QCoreApplication::organizationName \brief the name of the organization that wrote this application The value is used by the QSettings class when it is constructed using the empty constructor. This saves having to repeat this information each time a QSettings object is created. On Mac, QSettings uses \l {QCoreApplication::}{organizationDomain()} as the organization if it's not an empty string; otherwise it uses organizationName(). On all other platforms, QSettings uses organizationName() as the organization. \sa organizationDomain, applicationName */ /*! \fn void QCoreApplication::organizationNameChanged() \internal While not useful from C++ due to how organizationName is normally set once on startup, this is still needed for QML so that bindings are reevaluated after that initial change. */ void QCoreApplication::setOrganizationName(const QString &orgName) { if (coreappdata()->orgName == orgName) return; coreappdata()->orgName = orgName; #ifndef QT_NO_QOBJECT if (QCoreApplication::self) emit QCoreApplication::self->organizationNameChanged(); #endif } QString QCoreApplication::organizationName() { return coreappdata()->orgName; } /*! \property QCoreApplication::organizationDomain \brief the Internet domain of the organization that wrote this application The value is used by the QSettings class when it is constructed using the empty constructor. This saves having to repeat this information each time a QSettings object is created. On Mac, QSettings uses organizationDomain() as the organization if it's not an empty string; otherwise it uses organizationName(). On all other platforms, QSettings uses organizationName() as the organization. \sa organizationName, applicationName, applicationVersion */ /*! \fn void QCoreApplication::organizationDomainChanged() \internal Primarily for QML, see organizationNameChanged. */ void QCoreApplication::setOrganizationDomain(const QString &orgDomain) { if (coreappdata()->orgDomain == orgDomain) return; coreappdata()->orgDomain = orgDomain; #ifndef QT_NO_QOBJECT if (QCoreApplication::self) emit QCoreApplication::self->organizationDomainChanged(); #endif } QString QCoreApplication::organizationDomain() { return coreappdata()->orgDomain; } /*! \property QCoreApplication::applicationName \brief the name of this application The value is used by the QSettings class when it is constructed using the empty constructor. This saves having to repeat this information each time a QSettings object is created. If not set, the application name defaults to the executable name (since 5.0). \sa organizationName, organizationDomain, applicationVersion, applicationFilePath() */ /*! \fn void QCoreApplication::applicationNameChanged() \internal Primarily for QML, see organizationNameChanged. */ void QCoreApplication::setApplicationName(const QString &application) { coreappdata()->applicationNameSet = !application.isEmpty(); QString newAppName = application; if (newAppName.isEmpty() && QCoreApplication::self) newAppName = QCoreApplication::self->d_func()->appName(); if (coreappdata()->application == newAppName) return; coreappdata()->application = newAppName; #ifndef QT_NO_QOBJECT if (QCoreApplication::self) emit QCoreApplication::self->applicationNameChanged(); #endif } QString QCoreApplication::applicationName() { return coreappdata() ? coreappdata()->application : QString(); } // Exported for QDesktopServices (Qt4 behavior compatibility) Q_CORE_EXPORT QString qt_applicationName_noFallback() { return coreappdata()->applicationNameSet ? coreappdata()->application : QString(); } /*! \property QCoreApplication::applicationVersion \since 4.4 \brief the version of this application \sa applicationName, organizationName, organizationDomain */ /*! \fn void QCoreApplication::applicationVersionChanged() \internal Primarily for QML, see organizationNameChanged. */ void QCoreApplication::setApplicationVersion(const QString &version) { if (coreappdata()->applicationVersion == version) return; coreappdata()->applicationVersion = version; #ifndef QT_NO_QOBJECT if (QCoreApplication::self) emit QCoreApplication::self->applicationVersionChanged(); #endif } QString QCoreApplication::applicationVersion() { return coreappdata()->applicationVersion; } #ifndef QT_NO_LIBRARY Q_GLOBAL_STATIC_WITH_ARGS(QMutex, libraryPathMutex, (QMutex::Recursive)) /*! Returns a list of paths that the application will search when dynamically loading libraries. The return value of this function may change when a QCoreApplication is created. It is not recommended to call it before creating a QCoreApplication. The directory of the application executable (\b not the working directory) is part of the list if it is known. In order to make it known a QCoreApplication has to be constructed as it will use \c {argv[0]} to find it. Qt provides default library paths, but they can also be set using a \l{Using qt.conf}{qt.conf} file. Paths specified in this file will override default values. Note that if the qt.conf file is in the directory of the application executable, it may not be found until a QCoreApplication is created. If it is not found when calling this function, the default library paths will be used. The list will include the installation directory for plugins if it exists (the default installation directory for plugins is \c INSTALL/plugins, where \c INSTALL is the directory where Qt was installed). The colon separated entries of the \c QT_PLUGIN_PATH environment variable are always added. The plugin installation directory (and its existence) may change when the directory of the application executable becomes known. If you want to iterate over the list, you can use the \l foreach pseudo-keyword: \snippet code/src_corelib_kernel_qcoreapplication.cpp 2 \sa setLibraryPaths(), addLibraryPath(), removeLibraryPath(), QLibrary, {How to Create Qt Plugins} */ QStringList QCoreApplication::libraryPaths() { QMutexLocker locker(libraryPathMutex()); if (coreappdata()->manual_libpaths) return *(coreappdata()->manual_libpaths); if (!coreappdata()->app_libpaths) { QStringList *app_libpaths = new QStringList; coreappdata()->app_libpaths.reset(app_libpaths); const QByteArray libPathEnv = qgetenv("QT_PLUGIN_PATH"); if (!libPathEnv.isEmpty()) { QStringList paths = QFile::decodeName(libPathEnv).split(QDir::listSeparator(), QString::SkipEmptyParts); for (QStringList::const_iterator it = paths.constBegin(); it != paths.constEnd(); ++it) { QString canonicalPath = QDir(*it).canonicalPath(); if (!canonicalPath.isEmpty() && !app_libpaths->contains(canonicalPath)) { app_libpaths->append(canonicalPath); } } } QString installPathPlugins = QLibraryInfo::location(QLibraryInfo::PluginsPath); if (QFile::exists(installPathPlugins)) { // Make sure we convert from backslashes to slashes. installPathPlugins = QDir(installPathPlugins).canonicalPath(); if (!app_libpaths->contains(installPathPlugins)) app_libpaths->append(installPathPlugins); } // If QCoreApplication is not yet instantiated, // make sure we add the application path when we construct the QCoreApplication if (self) self->d_func()->appendApplicationPathToLibraryPaths(); } return *(coreappdata()->app_libpaths); } /*! Sets the list of directories to search when loading libraries to \a paths. All existing paths will be deleted and the path list will consist of the paths given in \a paths. The library paths are reset to the default when an instance of QCoreApplication is destructed. \sa libraryPaths(), addLibraryPath(), removeLibraryPath(), QLibrary */ void QCoreApplication::setLibraryPaths(const QStringList &paths) { QMutexLocker locker(libraryPathMutex()); // setLibraryPaths() is considered a "remove everything and then add some new ones" operation. // When the application is constructed it should still amend the paths. So we keep the originals // around, and even create them if they don't exist, yet. if (!coreappdata()->app_libpaths) libraryPaths(); if (coreappdata()->manual_libpaths) *(coreappdata()->manual_libpaths) = paths; else coreappdata()->manual_libpaths.reset(new QStringList(paths)); locker.unlock(); QFactoryLoader::refreshAll(); } /*! Prepends \a path to the beginning of the library path list, ensuring that it is searched for libraries first. If \a path is empty or already in the path list, the path list is not changed. The default path list consists of a single entry, the installation directory for plugins. The default installation directory for plugins is \c INSTALL/plugins, where \c INSTALL is the directory where Qt was installed. The library paths are reset to the default when an instance of QCoreApplication is destructed. \sa removeLibraryPath(), libraryPaths(), setLibraryPaths() */ void QCoreApplication::addLibraryPath(const QString &path) { if (path.isEmpty()) return; QString canonicalPath = QDir(path).canonicalPath(); if (canonicalPath.isEmpty()) return; QMutexLocker locker(libraryPathMutex()); QStringList *libpaths = coreappdata()->manual_libpaths.data(); if (libpaths) { if (libpaths->contains(canonicalPath)) return; } else { // make sure that library paths are initialized libraryPaths(); QStringList *app_libpaths = coreappdata()->app_libpaths.data(); if (app_libpaths->contains(canonicalPath)) return; coreappdata()->manual_libpaths.reset(libpaths = new QStringList(*app_libpaths)); } libpaths->prepend(canonicalPath); locker.unlock(); QFactoryLoader::refreshAll(); } /*! Removes \a path from the library path list. If \a path is empty or not in the path list, the list is not changed. The library paths are reset to the default when an instance of QCoreApplication is destructed. \sa addLibraryPath(), libraryPaths(), setLibraryPaths() */ void QCoreApplication::removeLibraryPath(const QString &path) { if (path.isEmpty()) return; QString canonicalPath = QDir(path).canonicalPath(); if (canonicalPath.isEmpty()) return; QMutexLocker locker(libraryPathMutex()); QStringList *libpaths = coreappdata()->manual_libpaths.data(); if (libpaths) { if (libpaths->removeAll(canonicalPath) == 0) return; } else { // make sure that library paths is initialized libraryPaths(); QStringList *app_libpaths = coreappdata()->app_libpaths.data(); if (!app_libpaths->contains(canonicalPath)) return; coreappdata()->manual_libpaths.reset(libpaths = new QStringList(*app_libpaths)); libpaths->removeAll(canonicalPath); } locker.unlock(); QFactoryLoader::refreshAll(); } #endif //QT_NO_LIBRARY #ifndef QT_NO_QOBJECT /*! Installs an event filter \a filterObj for all native events received by the application in the main thread. The event filter \a filterObj receives events via its \l {QAbstractNativeEventFilter::}{nativeEventFilter()} function, which is called for all native events received in the main thread. The QAbstractNativeEventFilter::nativeEventFilter() function should return true if the event should be filtered, i.e. stopped. It should return false to allow normal Qt processing to continue: the native event can then be translated into a QEvent and handled by the standard Qt \l{QEvent} {event} filtering, e.g. QObject::installEventFilter(). If multiple event filters are installed, the filter that was installed last is activated first. \note The filter function set here receives native messages, i.e. MSG or XCB event structs. \note Native event filters will be disabled in the application when the Qt::AA_PluginApplication attribute is set. For maximum portability, you should always try to use QEvent and QObject::installEventFilter() whenever possible. \sa QObject::installEventFilter() \since 5.0 */ void QCoreApplication::installNativeEventFilter(QAbstractNativeEventFilter *filterObj) { if (QCoreApplication::testAttribute(Qt::AA_PluginApplication)) { qWarning("Native event filters are not applied when the Qt::AA_PluginApplication attribute is set"); return; } QAbstractEventDispatcher *eventDispatcher = QAbstractEventDispatcher::instance(QCoreApplicationPrivate::theMainThread); if (!filterObj || !eventDispatcher) return; eventDispatcher->installNativeEventFilter(filterObj); } /*! Removes an event \a filterObject from this object. The request is ignored if such an event filter has not been installed. All event filters for this object are automatically removed when this object is destroyed. It is always safe to remove an event filter, even during event filter activation (i.e. from the nativeEventFilter() function). \sa installNativeEventFilter() \since 5.0 */ void QCoreApplication::removeNativeEventFilter(QAbstractNativeEventFilter *filterObject) { QAbstractEventDispatcher *eventDispatcher = QAbstractEventDispatcher::instance(); if (!filterObject || !eventDispatcher) return; eventDispatcher->removeNativeEventFilter(filterObject); } /*! \deprecated This function returns \c true if there are pending events; otherwise returns \c false. Pending events can be either from the window system or posted events using postEvent(). \note this function is not thread-safe. It may only be called in the main thread and only if there are no other threads running in the application (including threads Qt starts for its own purposes). \sa QAbstractEventDispatcher::hasPendingEvents() */ #if QT_DEPRECATED_SINCE(5, 3) bool QCoreApplication::hasPendingEvents() { QAbstractEventDispatcher *eventDispatcher = QAbstractEventDispatcher::instance(); if (eventDispatcher) return eventDispatcher->hasPendingEvents(); return false; } #endif /*! Returns a pointer to the event dispatcher object for the main thread. If no event dispatcher exists for the thread, this function returns 0. */ QAbstractEventDispatcher *QCoreApplication::eventDispatcher() { if (QCoreApplicationPrivate::theMainThread) return QCoreApplicationPrivate::theMainThread.load()->eventDispatcher(); return 0; } /*! Sets the event dispatcher for the main thread to \a eventDispatcher. This is only possible as long as there is no event dispatcher installed yet. That is, before QCoreApplication has been instantiated. This method takes ownership of the object. */ void QCoreApplication::setEventDispatcher(QAbstractEventDispatcher *eventDispatcher) { QThread *mainThread = QCoreApplicationPrivate::theMainThread; if (!mainThread) mainThread = QThread::currentThread(); // will also setup theMainThread mainThread->setEventDispatcher(eventDispatcher); } #endif // QT_NO_QOBJECT /*! \macro Q_COREAPP_STARTUP_FUNCTION(QtStartUpFunction ptr) \since 5.1 \relates QCoreApplication \reentrant Adds a global function that will be called from the QCoreApplication constructor. This macro is normally used to initialize libraries for program-wide functionality, without requiring the application to call into the library for initialization. The function specified by \a ptr should take no arguments and should return nothing. For example: \snippet code/src_corelib_kernel_qcoreapplication.cpp 3 Note that the startup function will run at the end of the QCoreApplication constructor, before any GUI initialization. If GUI code is required in the function, use a timer (or a queued invocation) to perform the initialization later on, from the event loop. If QCoreApplication is deleted and another QCoreApplication is created, the startup function will be invoked again. */ /*! \fn void qAddPostRoutine(QtCleanUpFunction ptr) \relates QCoreApplication Adds a global routine that will be called from the QCoreApplication destructor. This function is normally used to add cleanup routines for program-wide functionality. The cleanup routines are called in the reverse order of their addition. The function specified by \a ptr should take no arguments and should return nothing. For example: \snippet code/src_corelib_kernel_qcoreapplication.cpp 4 Note that for an application- or module-wide cleanup, qaddPostRoutine() is often not suitable. For example, if the program is split into dynamically loaded modules, the relevant module may be unloaded long before the QCoreApplication destructor is called. In such cases, if using qaddPostRoutine() is still desirable, qRemovePostRoutine() can be used to prevent a routine from being called by the QCoreApplication destructor. For example, if that routine was called before the module was unloaded. For modules and libraries, using a reference-counted initialization manager or Qt's parent-child deletion mechanism may be better. Here is an example of a private class that uses the parent-child mechanism to call a cleanup function at the right time: \snippet code/src_corelib_kernel_qcoreapplication.cpp 5 By selecting the right parent object, this can often be made to clean up the module's data at the right moment. \sa qRemovePostRoutine() */ /*! \fn void qRemovePostRoutine(QtCleanUpFunction ptr) \relates QCoreApplication \since 5.3 Removes the cleanup routine specified by \a ptr from the list of routines called by the QCoreApplication destructor. The routine must have been previously added to the list by a call to qAddPostRoutine(), otherwise this function has no effect. \sa qAddPostRoutine() */ /*! \macro Q_DECLARE_TR_FUNCTIONS(context) \relates QCoreApplication The Q_DECLARE_TR_FUNCTIONS() macro declares and implements two translation functions, \c tr() and \c trUtf8(), with these signatures: \snippet code/src_corelib_kernel_qcoreapplication.cpp 6 This macro is useful if you want to use QObject::tr() or QObject::trUtf8() in classes that don't inherit from QObject. Q_DECLARE_TR_FUNCTIONS() must appear at the very top of the class definition (before the first \c{public:} or \c{protected:}). For example: \snippet code/src_corelib_kernel_qcoreapplication.cpp 7 The \a context parameter is normally the class name, but it can be any text. \sa Q_OBJECT, QObject::tr(), QObject::trUtf8() */ QT_END_NAMESPACE | __label__pos | 0.871951 |
Practice worksheet included with online video training.
Transcript
When you're working with text in Excel, you'll frequently need to change case.
In this video we'll look at three functions that allow you to easily change case of text in Excel: UPPER, LOWER, and PROPER.
In this worksheet, we have two columns that contain names. Column B contains last names in uppercase text, and column C contains first names with the first letter capitalized.
In column D, I'll add a formula that capitalizes the first name using the UPPER function. The UPPER function takes just one argument: the text you want in upper case. When I add the formula and copy it down, we'll get all first names in uppercase text.
What if you need both first and last names in upper case? To do that, you just need to concatenate the first and the last names with a space inside the UPPER function.
This formula can be as flexible as you need. For example, I can easily reverse these names and add a comma between them, instead of a space.
In column E, let's convert the names to lower case using the LOWER function. Just like the UPPER function, you only need to provide a single argument: the text you'd like in lower case.
To take this example a bit further, let's assume you need to create an email address for each person in the list, using first and last names, separated by a period.
First, I'll add a domain name above the list to keep this information in only one place. I'll use the generic name "acme.com" for the domain. I'll also go ahead and name this cell "domain" to make the email address formula easier to read.
Now I can assemble the email address using a formula. Once I add the names, I need to add the "@" symbol and the domain.
Technically, the domain doesn't need to be inside the LOWER function, since it's already lower case, but there's no harm in putting it there.
Finally, let's try out the PROPER function. The PROPER function capitalizes the first letter only of each word you provide. It just takes one argument, and it will always convert all text to lower case before capitalizing, so it doesn't matter if the text you provide is upper case, lower case, or any combination of the two.
Using PROPER, I can simply concatenate the first and last names with a space and get a full name that uses standard capitalization.
Dave Bruns Profile Picture
AuthorMicrosoft Most Valuable Professional Award
Dave Bruns
Hi - I'm Dave Bruns, and I run Exceljet with my wife, Lisa. Our goal is to help you work faster in Excel. We create short videos, and clear examples of formulas, functions, pivot tables, conditional formatting, and charts. | __label__pos | 0.897299 |
Written by 2:12 pm eCommerce
How to link your cPanel email to Gmail in 2023?
Link cPanel email to Gmail
What is a cPanel? cPanel is a web-based control panel that allows website owners and hosting providers to manage various aspects of their websites and servers. It provides a user-friendly interface with a range of tools and features that make it easy to manage your website and host your account.
Here is an example of what the cPanel dashboard might look like:
cPanel
As you can see, the dashboard provides an overview of your hosting account and offers a range of options for managing different aspects of your website. You can access different features and tools by clicking on the icons in the dashboard or using the search bar to find specific options.
cPanel is a powerful tool that can help you save time and effort when managing your website and hosting account. It is beneficial for those unfamiliar with server administration or who do not have the technical skills to manage their websites manually.
Overall, cPanel is an essential tool for anyone who owns or manages a website, and it can help you take control of your online presence and ensure that your website is running smoothly and efficiently.
How to link cPanel with a Gmail account?
Now to connect your Gmail account with cPanel, follow these steps:
1. Log in to your cPanel account by visiting the URL provided by your hosting provider and entering your login details. The login page should look similar to this:
cpanel dashboard
1. Once you have logged in, you will be taken to the cPanel dashboard. In the “Email” section, click on the “Email Accounts” icon.
cPanel Gmail to your Gmail
1. On the Email Accounts page, you will see a list of any email accounts that have already been set up for your domain. To create a new email account, scroll down to the “Create a New Email Account” section.
Gmail Account
1. In the “Email” field, enter the desired username for the new account. This will become the first part of the email address, so if you enter “nestnepal,” the email address will be [email protected].
2. In the “Password” field, enter a strong password for the new account. It is important to use a unique and secure password to protect your email account from unauthorized access.
3. In the “Password (Again)” field, re-enter the password to confirm it.
4. In the “Mailbox Quota” field, enter the amount of storage space you want to allocate for the email account. This is the amount of space the account can use for storing emails and attachments.
5. When you have finished entering the account details, click the “Create Account” button to create a new email account.
Gmail account details
1. Once the account has been created, you will see a success message and the new email account will be listed on the Email Accounts page.
cPanel Gmail
1. To connect your Gmail account to cPanel, click on the “Connect Devices” button next to the new email account.
1. On the “Connect Devices” page, you will see a list of different mail clients and devices that you can use to access your email account. To connect your Gmail account, click on the “Configure Mail Client” button and select “Gmail” from the drop-down menu.
cPanel Gmail
1. You will be taken to a page with instructions on how to connect your Gmail account to cPanel. Follow these instructions to complete the process.
cPanel Gmail
1. The instructions will include a link to a Google login page, where you will be asked to enter your Gmail login credentials and allow cPanel access to your account.
cPanel Gmail
14. Enter the email address associated with the account that you want to add to your Gmail account and complete the further steps as it comes.
Login to gmail
1. Once you have completed the steps in the instructions, your Gmail account should be successfully connected to cPanel. You should now be able to send and receive emails from your Gmail account through cPanel.
Want to read more, check my blog post:
1. How to do SEO from scratch to advance in 2023?
2. How to connect a custom domain to a blogger in 2023?
Please visit our hosting plan.
Thanks for reading!!
(Visited 36 times, 1 visits today)
Last modified: January 5, 2023 | __label__pos | 0.553624 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.